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

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);
}

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:

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:

Getting Group Claims With ADFS 4.0 OAuth2 Token

I successfully set up an ADFS 4.0 instance (Windows Server 2016) which I intend to use to authenticate and authorize the users of a single-page application towards a WebApi.
I pretty much followed this tutorial: https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/development/single-page-application-with-ad-fs .. which is modifying a sample that uses Azure Active Directory.
Now.. all seems to work fine, I can get a basic JWT token from the /oauth2/authorize endpoint:
{
"aud": "d668d637-7fd4-45ef-9eab-46fee230dcbc",
"iss": "https://fs.contoso.com/adfs",
"iat": 1494341035,
"exp": 1494344635,
"auth_time": 1494341035,
"nonce": "c91e3f78-c31a-402e-a685-8d1586915227",
"sub": "Rl7sOj0nDbgh8BVWZegrkvgAKaB/SwNuEbmORcWcae4=",
"upn": "john.doe#contoso.com",
"unique_name": "CONTOSO\\JohnDoe"
}
The token from AzureAD contained more properties, particularly family_name and given_name. But I was also hoping to add explicit group claims to the token. I thought I should be able to make this happen by setting the 'Issuance Transform Rules' correctly in the Web application Properties ( Application Groups -> MyApp -> MyApp - WebApplication -> Properties). However, it seems no matter what I do, nothing seems to have any effect on the properties contained in the JWT returned from the endpoint. I always get exactly the same token structure.
I am not really sure how the 'Outgoing Claims' map to the token properties as nothing except the 'UPN' and the 'unique name' seems to be transferred. Any pointers what I may be doing wrong here?
As indicated in nzpcmad's answer, it appears that custom claims in the id_token using the default URL-parameter-encoded GET redirect is simply not supported. The reason for this may be that there is an URL length limit, but I find that quite questionable.
Anyway, apparently this restriction does not apply when the token is returned in a POST redirect. That's also why people describe it working just fine for MVC applications.
So I was able to work around the problem by redirecting the response to a backend API endpoint (POST), which just redirects it to the frontend (SPA) again, but as a GET request with URL-endcoded parameters:
public class LoginController : ApiController
{
[HttpPost]
[Route("login")]
public HttpResponseMessage Login(FormDataCollection formData)
{
var token = formData["id_token"];
var state = formData["state"];
var response = Request.CreateResponse(HttpStatusCode.Moved);
var frontendUri = ConfigurationManager.AppSettings["ad:FrontendUri"];
response.Headers.Location = new Uri($"{frontendUri}#id_token={token}&state={state}");
return response;
}
}
Note that to change the response method from GET to POST, one simply has to add &response_mode=form_post to the OAuth request URL.
Windows Server 2016 is ADFS 4.0.
SPA uses OAuth implicit flow and there are a number of posts around this suggesting that this flow doesn't allow extra claims, especially if you are using ADAL.
e.g. ADFS 4.0, Adal JS - No claims.

Microsoft Graph API access token validation failure

I use this URL to get id_token:
https://login.microsoftonline.com/common/oauth2/authorize?
response_type=id_token%20code&
client_id=MY_CLIENT_GUID_ID_IN_HERE&
redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fopenid%2Freturn&nonce=alfaYYCTxBK8oypM&
state=6DnAi0%2FICAWaH14e
and this return result like this
http://localhost:3000/auth/openid/return?
code=AAA_code_in_here&
id_token=eyJ0eXAi_xxxx_yyyy_in_here&
state=6DnAi0%2FICAWaH14e&
session_state=xxxx_guid_xxxxx
and then i use the id_token to query Graph (use POST man)
i have see this post InvalidAuthenticationToken and CompactToken issues - Microsoft Graph using PHP Curl but make no sense.
OATH 2.0 requires multiple steps. The first request returns an OAUTH Code. The next step is converting that OATUH code into a Bearer Token. This is the step you are missing here.
I would also recommend using the v2 Endpoint which is a lot easier to work with (particularly with Graph). I wrote a v2 Endpoint Primer that walks through the process and may be helpful as well.
You can't use the token directly, there is one more step to exchange the code you get from the response url into token.
Here is my C# code (using Microsoft.IdentityModel.Clients.ActiveDirectory)
public static AuthenticationResult ExchangeCodeForToken(string InTenantName, string InUserObjId, string InRedirectUri, string InApplicationAzureClientID, string InApplicationAzureClientAppKey)
{
Check.Require(!string.IsNullOrEmpty(InTenantName), "InTenantName must be provided");
Check.Require(!string.IsNullOrEmpty(InUserObjId), "InUserObjId must be provided");
if (CanCompleteSignIn) //redirect from sign-in
{
var clientCredential = new ClientCredential(InApplicationAzureClientID, InApplicationAzureClientAppKey);
var authContext = new AuthenticationContext(Globals.GetLoginAuthority(InTenantName), (TokenCache)new ADALTokenCache(InUserObjId)); //Login Authority is https://login.microsoftonline.com/TenantName
return authContext.AcquireTokenByAuthorizationCode(VerificationCode, new Uri(InRedirectUri), clientCredential, Globals.AZURE_GRAPH_API_RESOURCE_ID); //RESOURCE_ID is "https://graph.microsoft.com/"
}
return null;
}
I had this issue today when I was playing with graph API, the problem in my case was how I was generating the token.
I used postman for generating the token wherein the Auth URL section I was adding the resource = client_id whereas it should be the graph URL. After making that change I was able to make the call via postman.
In order for the above to work, please make sure your application in Azure has delegated permissions to access the Graph API.
To receive the access token and use it for profile requests, you don't need anything from server-side, you can implement the oAuth2 just from the client side.
Use the following URL for login:
https://login.microsoftonline.com/common/oauth2/authorize?client_id=YOUR_CLIENT_ID&resource=https://graph.microsoft.com&response_type=token&redirect_uri=YOUR_REDIRECT_URI&scope=User.ReadBasic.All
After successful login, user will redirected to the page with access_token parameter. Then use the following AJAX call to fetch user info:
var token = login_window.location.href.split('access_token=').pop().split('&')[0];
$.ajax({
url: "https://graph.microsoft.com/v1.0/me",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer '+token);},
success: function(data) {
alert('Hi '+data.displayName);
console.log(data);
}
});
Note that you may need to enable oauth2AllowImplicitFlow:true setting from your Azure Active Directory application manifest file.
Set "oauth2AllowImplicitFlow": false to "oauth2AllowImplicitFlow": true.
Lastly, ensure that your app has required permissions for Microsoft Graph which are sign in users and View users' basic profile
An updated answer to get access with new applications:
Register your app in the app registration portal.
Authorization request example:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?client_id=6731de76-14a6-49ae-97bc-6eba6914391e&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=query&scope=offline_access%20user.read%20mail.read&state=12345
Authorization response will look like this:
https://localhost/myapp/?code=M0ab92efe-b6fd-df08-87dc-2c6500a7f84d&state=12345
Get a token
POST /{tenant}/oauth2/v2.0/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=user.read%20mail.read
&code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&grant_type=authorization_code
&client_secret=JqQX2PNo9bpM0uEihUPzyrh // NOTE: Only required for web apps
Use the access token to call Microsoft Graph
GET https://graph.microsoft.com/v1.0/me
Authorization: Bearer eyJ0eXAiO ... 0X2tnSQLEANnSPHY0gKcgw
Host: graph.microsoft.com
Source:
https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph/api/1.0
You can also get an access token without a user, see here:
https://learn.microsoft.com/en-us/graph/auth-v2-service

MVC 5 Identity 2 and Web API 2 authorization and call api using bearer token

The following scenario: I have an MVC 5 web app using Identity 2.0 and Web API 2.
Once the user authenticates in MVC 5 he should be able to call a WEB API endpoint let's call it: api/getmydetails using a bearer token.
What I need to know is how can I issue the token for that specific user in MVC 5?
I did solve this.
Here are some screenshots and I will also post the demo solution.
Just a simple mvc 5 with web api support application.
The main thing you have to register and after login. For this demo purpose I registered as admin#domain.com with password Password123*.
If you are not logged in you will not get the token. But once you loggin you will see the token:
After you get the token start Fiddler.
Make a get request to the api/service endpoint. You will get 401 Unauthorized
Here is the description of the request:
Now go to the web app, stage 1 and copy the generated token and add the following Authorization header: Authorization: Bearer token_here please notice the Bearer keyword should be before the token as in the image bellow. Make a new request now:
Now you will get a 200 Ok response. The response is actually the user id and user name that show's you are authorized as that specific user:
You can download the working solution from here:
http://www.filedropper.com/bearertoken
If for some reason the link doesn't work just let me know and I will send it to you.
P.S.
Of course in your app, you can use the generated bearer token to make ajax call to the web api endpoint and get the data, I didn't do that but should be quite easy ...
P.S. 2: To generate the token:
private string GetToken(ApplicationUser userIdentity)
{
if (userIdentity == null)
{
return "no token";
}
if (userIdentity != null)
{
ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.UserName));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
DateTime currentUtc = DateTime.UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;
}
return "no token";
}

Resources