Swagger with Google OAuth 2.0 authorization - oauth-2.0

Swagger passes access_code by default to headers. Is it possible to pass id_token?
I'm documenting my NodeJS REST API with swagger.yaml version 2.0

Yes this is possible even though it's not a good idea as mentioned by #DalmTo.
You need to add x-tokenName: id_token to the Google OAuth security definition in your API definition.
swagger: '2.0'
...
securityDefinitions:
google_oauth:
type: oauth2
description: Google OAuth
flow: accessCode
authorizationUrl: https://accounts.google.com/o/oauth2/v2/auth
tokenUrl: https://www.googleapis.com/oauth2/v4/token
x-tokenName: id_token # <-------
scopes:
...
Note: To use x-tokenName in OpenAPI 2.0 definitions you need Swagger UI 3.8.12+; to use it in OpenAPI 3.0 you need Swagger UI 3.25.0+.

You can make Swagger or Nswagg use a different token (id_token or access_token) by setting the x-tokenName in the security configuration, such as following:
services.AddSwaggerDocument(config =>
{
config.PostProcess = document =>
{
document.Info.Title = "API OpenBankWeb";
document.Info.Description = "Uma simples Web API feita em ASP.NET Core consumindo AWS.\nClique nos títulos abaixo para expandir.";
};
config.AddSecurity("oauth2", new NSwag.OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.OAuth2,
ExtensionData = new Dictionary<string, object>
{
{ "x-tokenName", "id_token" }
},
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = _domain + "/oauth2/authorize",
TokenUrl = _domain + "/oauth2/token"
}
}
});
This can be very handy when using AWS Cognito, since it uses only id token for authentification.

Related

Swashbuckle Swagger UI not sending client_secret and client_id to OAuth endpoint when using authentication form

I have a .NET 5 API project documented with SwaggerGen for which I'm trying to use Swashbuckle as the documentation UI. My auth provider is Auth0, so I'm looking to have the docs generate a JWT bearer token by making a valid OAuth2 call to the Auth0 /oauth/token endpoint. The Authorize button is appearing on the generated page and produces a form that asks the user for the client_id and client_secret, but when I press the Authorize button it issues a POST request that is missing client_id and client_secret. Specifically, it goes to the correct endpoint (/oauth/token) but has no query string parameters and only grant_type: client_credentials in the POST body. I can see this in the Chrome developer tools. Somehow the UI is just completely disregarding the values I've typed into the client_id and client_secret form fields.
Is there a trick to making the auth request use the values from the form? Here is the relevant part of my SwaggerGen configuration:
options.AddSecurityDefinition("OAuth2", new OpenApiSecurityScheme {
Type = SecuritySchemeType.OAuth2,
Name = "Bearer",
Description = "Authorization using the OAuth2 access token authorization flow",
Scheme = "Bearer",
In = ParameterLocation.Header,
Flows = new OpenApiOAuthFlows {
ClientCredentials = new OpenApiOAuthFlow {
TokenUrl = new Uri($"https://{_configuration["Auth0:HostedDomain"]}/oauth/token"),
AuthorizationUrl = new Uri($"https://{_configuration["Auth0:HostedDomain"]}/authorize")
}
}
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "OAuth2"
}
},
new List<string>()
}
});
Are you sure the Swagger UI does not send them, i.e. in the authorization header?
I had a similar problem because our OpenID server recognizes only client credentials (client_id, client_secret) sent in the body form and we have to select the correct "Client credentials location" option in the authorization dialog (Request body):
Then the client_id is sent in the request body correctly:

How can I set the Bearer token after authentication in Swagger UI

I have a REST API service provider, written in PHP. I tested it successfully in Postman, and it works properly there.
Now I am going to prepare API documentation for it, and I am using Swagger UI 3. I set it up properly and I can process Authorization with the top Authorize button.
After a successful login, I expect the respective Bearer token being set and used by the endpoints. But this is not gonna happen, when I try any endpoint, the REST server complains about lack of Authorization Header. I tested the network traffic, and there is no token along with the HTTP request.
My question is, how can I send the Bearer token in the header in Swagger UI, after successfully login using the Authorize button on the top? Is there any steps/process I should take to accompany the endpoint request with the token?
I used it in a .NET core project, and in the Startup file I had to put the following code part:
services.AddSwaggerGen(options =>
{
//authentication
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
};
options.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
In = "Header",
Description = "Please insert JWT into field",
Name = "Authorization",
Type = "apiKey"
});
options.AddSecurityRequirement(security);
}

Reproducing an ADAL.JS-authenticated request in Postman

I have a .NET Web API and a small vanilla-JS app using ADAL.js, and I've managed to make them talk nicely to each-other and authenticate correctly.
If I console.log the token returned from adalAuthContext.acquireToken() and manually enter it as Authorization: Bearer {{token}} in Postman, I can also get a valid, authenticated, response from my backend.
However, I can't figure out how to configure Postman's built-in OAuth2.0 authentication UI to get me tokens automatically. I have managed to get tokens in several ways, but none of them are accepted by the backend.
How do I configure Postman to get a token the same way the ADAL.js library does?
For completeness, here's some code:
Backend configuration:
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters { ValidAudience = "<app-id>" },
Tenant = "<tenant>",
AuthenticationType = "WebAPI"
});
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
ADAL.js configuration:
const backendUrl = 'http://localhost:55476';
const backendAppId = '<app-id>';
const authContext = new AuthenticationContext({
clientId: backendAppId,
tenant: '<tenant>',
endpoints: [{ [backendAppId]: backendAppId }],
cacheLocation: 'localStorage'
});
Actually making a request:
authContext.acquireToken(backendAppId, (error, token) => {
// error handling etc omitted
fetch(backendUrl, { headers: { Authorization: `Bearer ${token}` } })
.then(response => response.json())
.then(console.log)
})
So since the Azure AD v1 endpoint is not fully standards-compliant, we have to do things in a slightly weird way.
In Postman:
Select OAuth 2.0 under Authorization
Click Get new access token
Select Implicit for Grant Type
Enter your app's reply URL as the Callback URL
Enter an authorization URL similar to this: https://login.microsoftonline.com/yourtenant.onmicrosoft.com/oauth2/authorize?resource=https%3A%2F%2Fgraph.microsoft.com
Enter your app's application id/client id as the Client Id
Leave the Scope and State empty
Click Request token
If you configured it correctly, you'll get a token and Postman will configure the authorization header for you.
Now about that authorization URL.
Make sure you specify either your AAD tenant id or a verified domain name instead of yourtenant.onmicrosoft.com.
Or you can use common if your app is multi-tenant.
The resource is the most important parameter (and non-standards-compliant).
It tells AAD what API you want an access token for.
In this case I requested a token for MS Graph API, which has a resource URI of https://graph.microsoft.com.
For your own APIs, you can use either their client id or App ID URI.
Here is a screenshot of my settings:

How Can I add basic auth in swagger 3.0 automatically with out the user to type in at authorize button?

I am using swagger 3.0 and have multiple endpoints in swagger docs.
I want user not to type in credentials at authorize button every time.
Is there any way I can include authentication in index.html or in my yaml files to automatically authorize the user.
Thanks.
Swagger UI 3.13.0+ provides the preauthorizeBasic method for this purpose. Assuming your API definition includes a security scheme for Basic auth:
swagger: '2.0'
...
securityDefinitions:
basicAuth:
type: basic
security:
- basicAuth: []
you can specify the default username and password for Basic auth like so:
// index.html
const ui = SwaggerUIBundle({
url: "https://my.api.com/swagger.yaml",
...
onComplete: function() {
// "basicAuth" is the key name of the security scheme in securityDefinitions
ui.preauthorizeBasic("basicAuth", "username", "password");
}
})
Now, if you click the "Authorize" button in Swagger UI, you will see that the username and password are pre-filled.
Original answer (for Swagger UI 3.1.6—3.12.1):
You can add the requestInterceptor to your Swagger UI's index.html file in order to add the Authorization header automatically to "try it out" requests. requestInterceptor is supported in Swagger UI 3.1.6 and later.
// index.html
const ui = SwaggerUIBundle({
url: "http://my.api.com/swagger.yaml",
...
requestInterceptor: (req) => {
if (! req.loadSpec) {
// Add the header to "try it out" calls but not spec fetches
var token = btoa("username" + ":" + "password");
req.headers.Authorization = "Basic " + token;
}
return req;
}
})

invalid_scope error in access token for client credential flow

I am getting invalid_scope error in access token request for client credential flow. The error log states that "cannot request OpenID scopes in client credentials flow". I haven't requested for the open id scope. I don't know from where it came from. I need to generate access token using client credential flow.
Issue / Steps to reproduce the problem
API Resource definition.
public IEnumerable GetApiResources()
{
return new List {
new ApiResource
{
Name = "WidgetApi",
DisplayName = "Widget Management API",
Description = "Widget Management API Resource Access",
ApiSecrets = new List { new Secret("scopeSecret".Sha256()) },
Scopes = new List {
new Scope("WidgetApi.Read"),
new Scope("WidgetApi.Write")
}
}
};
}
Client Definition;
return new List
{
new Client
{
ClientId = "WidgetApi Client Id",
ClientName = "WidgetApi Client credential",
RequireConsent = false,
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret( clientSecret.Sha256())
},
// scopes that client has access to
AllowedScopes = { "WidgetApi.Read", "WidgetApi.Write"},
AccessTokenLifetime = 3600
};
}
Access token request body (key - value) using postman
grant_type client_credentials
response_type id_token
scope WidgetApi.Read WidgetApi.Write
client_secret xxxxxxxxxxxxxxxxxxxxxx
client_id WidgetApiClientId
Relevant parts of the log file
dbug: Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection[4]
Closing connection to database 'IdentityServer4Db' on server 'localhost\SQLEXPRESS'.
dbug: IdentityServer4.EntityFramework.Stores.ResourceStore[0]
Found PssUserMgtApi.Read, PssUserMgtApi.Write API scopes in database
fail: IdentityServer4.Validation.TokenRequestValidator[0]
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx cannot request OpenID scopes in client credentials flow
fail: IdentityServer4.Validation.TokenRequestValidator[0]
{
"ClientId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ClientName": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"GrantType": "client_credentials",
"Scopes": "xxxxxxxxxx.Read xxxxxxxxxxxxx.Write",
"Raw": {
"grant_type": "client_credentials",
"response_type": "id_token",
"scope": "xxxxxxxxxxxx.Read xxxxxxxxxxxxx.Write",
"client_secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
}
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 5292.2873ms 400 application/json
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
Connection id "0HL51IVGKG792" completed keep alive response.
Since there is no user tagged in a client credential flow, normally, client credential is not intended to have a scope tagged to it, and many frameworks doesnt support it.
https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ says :
scope (optional) :
Your service can support different scopes for the client credentials grant. In practice, not many services actually support this.
Check whether your client credential details are correct or not. You can also find this simple step by step explanation to configure client credential flow using this link
If you have this problem, just remove the 'openid' scope for a given client in the database in ClientScopes.
Actually the question already contains the answer:
grant_type client_credentials
response_type id_token
scope WidgetApi.Read WidgetApi.Write
client_secret xxxxxxxxxxxxxxxxxxxxxx
client_id WidgetApiClientId
The request of client_credentials type should be processed at token endpoint and must not require id_token as the flow is non-interactive. The redundant parameter is breaking the flow.
I get this error with IdentityServer4 2.1.3, but not with IdentityServer4 2.3.2. It seems, from the GitHub issues for the project, that it was fixed in 2.3:
https://github.com/IdentityServer/IdentityServer4/issues/2295#issuecomment-405164127

Resources