How do I remove this Artifact - swashbuckle

I am using swashbuckle to document my API. When I open the swagger page, I get this item highlighted in the image. How do I get rid of it or replace it? Using v5 of the swashbuckle tooling

Here are the section.
Startup.cs - Services
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v0", new OpenApiInfo
{
Version = "v0",
Title = "LTK Manager",
Description = "Sample Description",
TermsOfService = new Uri("https://example.com/terms"),
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.IgnoreObsoleteActions();
c.IgnoreObsoleteProperties();
});
Startup.cs - Configuration
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v0/swagger.json", "LTK Manager V0 (alpha)");
c.DisplayOperationId();
});
Route Decoration
/// <summary>
/// Retrieves a parameter store value from an account/region
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Returns an Object Containing the response from the API.</response>
[HttpPost]
[Route("getParamStoreValue")]
[ProducesResponseType(200)]
public IActionResult getKey([FromBody] ParamStoreRequest req)

Related

Added claims from AWS custom lambda Authorizer, how to access those claims in ASP.NET Core 6 Web API?

I have created AWS custom lambda Authorizer, which is validating token and add claims in APIGatewayCustomAuthorizerResponse with Context property.
private APIGatewayCustomAuthorizerResponse AuthorizedResponse(TokenIntrospectionResponse result) // result with claims after validating token
{
return new APIGatewayCustomAuthorizerResponse()
{
PrincipalID = "uniqueid",
PolicyDocument = new APIGatewayCustomAuthorizerPolicy()
{
Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>
{
new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement()
{
Effect = "Allow",
Resource = new HashSet<string> { "*" },
Action = new HashSet<string> { "execute-api:Invoke" }
}
}
},
Context = PrepareRequestContextFromClaims(result.Claims) //APIGatewayCustomAuthorizerContextOutput
};
}
private APIGatewayCustomAuthorizerContextOutput PrepareRequestContextFromClaims(IEnumerable<System.Security.Claims.Claim> claims)
{
APIGatewayCustomAuthorizerContextOutput contextOutput = new APIGatewayCustomAuthorizerContextOutput();
var claimsGroupsByType = claims.GroupBy(x => x.Type);
foreach (var claimsGroup in claimsGroupsByType)
{
var type = claimsGroup.Key;
var valuesList = claimsGroup.Select(x => x.Value);
var values = string.Join(',', valuesList);
contextOutput[type] = values;
}
return contextOutput;
}
Added this lambda authorizer with API GW method request.
For integration request, I have added HTTP Proxy request, which is an ASP.NET Core 6 Web API.
I am trying to access claims from the headers, that were added by authorizer in Web API routes, but not getting any claims.
_httpContext.HttpContext.Request.Headers
// not getting with headers
_httpContext.HttpContext.Items["LAMBDA_REQUEST_OBJECT"] as APIGatewayProxyRequest
// not getting with this as well
Is there any way to achieve this?
Needs to configure claim key value with API Gateway's Method & Integration request.
For example, if custom lambda authorizer validates token and add claim 'role' in Context of APIGatewayCustomAuthorizerResponse => we have to add optional role in headers with 'Method Request' and also need to add header with 'Integration request' as (Name : role, Mapped from : context.authorizer.role).
then after we will get 'role' from headers using _httpContext.HttpContext.Request.Headers['role'] with .Net Core 6 Web API.

Swashbuckle: Customize endpoint path (AspNetCore)

I have this setup where I want to organize multiple APIs served by the same application
.
For each api I get the prefix from the subdomain and redirect it to the application server, example:
user.api.example.com/v1/profile --> api.example.com/user/v1/profile
admin.api.example.com/v1/companies --> api.example.com/admin/v1/companies
With this setup, I need to remove the path prefix ("/user", "/admin") when generating the swagger json file.
Is it possible to configure a function that will manipulate the path for each endpoint before generating the json file?
I only want to alter what goes into the swagger json file, not the actual endpoint path!
Document Filters were the answers to that particular need:
public class PathPrefixDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var editedPaths = new OpenApiPaths();
foreach(var kv in swaggerDoc.Paths)
{
var newKey = string.Join("/", kv.Key.Split('/').Skip(2));
editedPaths.Add("/"+newKey, kv.Value);
}
swaggerDoc.Paths = editedPaths;
var a = swaggerDoc.Paths;
}
}

Amazon lex-chatbot-not able to embed using predefined libraries

I have developed chatbot and want to integrate in a website.I am following this github link that has predefined libraries for chatbotUI to embbed as an iframe. https://github.com/aws-samples/aws-lex-web-ui Below is the code from github:
<html>
<head>
<title>My Parent Page</title>
</head>
<body>
<h1>Welcome to my parent page</h1>
<!-- loader script -->
<script src="./lex-web-ui-loader.js"></script>
<script>
/*
The loader library creates a global object named ChatBotUiLoader
It includes the IframeLoader constructor
An instance of IframeLoader has the load function which kicks off
the load process
*/
// options for the loader constructor
var loaderOptions = {
// you can put the chatbot UI config in a JSON file
configUrl: './chatbot-ui-loader-config.json',
// the full page chatbot UI that will be iframed
iframeSrcPath: './chatbot-index.html#/?lexWebUiEmbed=true'
};
// The following statement instantiates the IframeLoader
var iframeLoader = new ChatBotUiLoader.IframeLoader(loaderOptions);
// chatbot UI config
// The loader can also obtain these values from other sources such
// as a JSON file or events. The configUrl variable in the
// loaderOptions above can be used to put these config values in a file
// instead of explicitly passing it as an argument.
var chatbotUiConfig = {
ui: {
// origin of the parent site where you are including the chatbot UI
// set to window.location.origin since hosting on same site
parentOrigin: window.location.origin,
},
iframe: {
// origin hosting the HTML file that will be embedded in the iframe
// set to window.location.origin since hosting on same site
iframeOrigin: window.location.origin,
},
cognito: {
// Your Cognito Pool Id - this is required to provide AWS credentials
poolId: '<your cognito pool id>'
},
lex: {
// Lex Bot Name in your account
botName: '<your lex bot name>'
}
};
// Call the load function which returns a promise that is resolved
// once the component is loaded or is rejected if there is an error
iframeLoader.load(chatbotUiConfig)
.then(function () {
console.log('iframe loaded');
})
.catch(function (err) {
console.error(err);
});
</script>
</body>
</html>
I went to parent.html (almost similar to the code above)inside src/website/parent.html of the github folder and made changes to the srcipt src path ,cognito poolid and lex name referring to the above code.
1)In config url inside the code above,I dont know what path to give for chatbot-ui-loader-config.json.There is no such json file inside dist directory.Should I create my own ?
2)I created an website using EC2 linux instance.I have my index file and aws-lex-web-ui (github folder) inside my var/www/html.Inside index file,I am calling the parent.html of aws-lex-web-ui folder.Is this method correct?
In output I am getting the heading content of the parent .html page .But It seems its not invoking the lex-web-ui-loader.js .I am not sure where I go wrong.
I have given a wrong path .I pointed the loader file lex-web-ui-loader.js to a correct location inside my folder and it worked.

Virtual Hosting on Next.js app with Apollo GraphQL

I have a webapp made with Next.js and Apollo as show in example with-apollo. I want to serve multiple domains with my webapp (name-based virtual hosting). Unfortunately HttpLink of ApolloClient requires absolute server URL with domain but this makes backend app unable to recognize domain which user really visited. Is there a way to configure HttpLink with a dynamic URL based on real request or use relative URL or anything else?
Either use an Apollo Link to intercept the query and set uri property on the context
const authMiddleware = setContext((operation, { uri }) => {
return refreshToken().then(res => ({
uri: this.getURI()
})
}))
Or intercept the request with Angular's HttpClient interceptor and change the endpoint.
https://github.com/apollographql/apollo-angular/tree/master/packages/apollo-angular-link-http#options
Source: Updating uri of apollo client instance
The NextPageContext object passed to getInitialProps includes the req object when called on the server-side. So you can do something like:
WithApollo.getInitialProps = async ctx => {
const { AppTree, req } = ctx
const linkBaseUrl = req ? req.protocol + '://' + req.get('host') : ''
...
}
You can then pass this base url down to createApolloClient along with the initial state and prepend your HttpLink's url with it. On the client side, this will prepend an empty string (you only need the full URL on the server).

How to calculate AWS signature V4 in Swagger before request

For our AWS API Endpoints we use AWS_IAM authorization and want to make a call from Swagger UI.
To make a successful call there must be 2 headers 'Authorization' and 'x-amz-date'. To form 'Authorization' we use following steps from aws doc.
We must to change 'x-amz-date' with every call to go through authorization.
The question is: How to write script in Swagger to sign request, which run every time before request send to aws?
(We know how to specify both headers one time before loading Swagger page, but this process should be re-run before every call).
Thanks in advance.
There is built-in support in swagger-js to add requestInterceptors to do just this. The swagger-ui project uses swagger-js under the hood.
Simply create a request interceptor like such:
requestInterceptor: {
apply: function (request) {
// modify the request object here
return request;
}
}
and apply it to your swagger instance on creation:
window.swaggerUi = new SwaggerUi({
url: url,
dom_id: "swagger-ui-container",
requestInterceptor: requestInterceptor,
Here you can set headers in the request object (note, this is not the standard javascript http request object, inspect it for details). But you do have access to all headers here, so you can calculate and inject them as needed.
You can pretty easily monkeypatch signing from the AWS SDK into SwaggerJS(and thus SwaggerUI). See here
I have a slightly modified SwaggerUI here. Given some AWS credentials and an API ID, it will pull down the Swagger definition, display it in SwaggerUI, and then you can call the API using sigv4.
The Authorizer implementation looks like this:
var AWSSigv4RequestSigner = function(credentialProvider, aws) {
this.name = "sigv4";
this.aws = aws;
this.credentialProvider = credentialProvider;
};
AWSSigv4RequestSigner.prototype.apply = function(options, authorizations) {
var serviceName = "execute-api";
//If we are loading the definition itself, then we need to sign for apigateway.
if (options && options.url.indexOf("apigateway") >= 0) {
serviceName = "apigateway";
}
if(serviceName == "apigateway" || (options.operation && options.operation.authorizations && options.operation.authorizations[0].sigv4))
{
/**
* All of the below is an adapter to get this thing into the right form for the AWS JS SDK Signer
*/
var parts = options.url.split('?');
var host = parts[0].substr(8, parts[0].indexOf("/", 8) - 8);
var path = parts[0].substr(parts[0].indexOf("/", 8));
var querystring = parts[1];
var now = new Date();
if (!options.headers)
{
options.headers = [];
}
options.headers.host = host;
if(serviceName == "apigateway")
{
//For the swagger endpoint, apigateway is strict about content-type
options.headers.accept = "application/json";
}
options.pathname = function () {
return path;
};
options.methodIndex = options.method;
options.search = function () {
return querystring ? querystring : "";
};
options.region = this.aws.config.region || 'us-east-1';
//AWS uses CAPS for method names, but swagger does not.
options.method = options.methodIndex.toUpperCase();
var signer = new this.aws.Signers.V4(options, serviceName);
//Actually add the Authorization header here
signer.addAuthorization(this.credentialProvider, now);
//SwaggerJS/yourbrowser complains if these are still around
delete options.search;
delete options.pathname;
delete options.headers.host;
return true;
}
return false;
};