Use JWT (Authorization: Bearer) in Swagger in ASP.NET Core
Currently Swagger has functionality for authentication with JWT-token and can automatically add token into header (I'm using Swashbuckle.AspNetCore 1.1.0).
The following code should help achieve this.
In the Startup.ConfigureServices():
services.AddSwaggerGen(c =>
{
// Your custom configuration
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.DescribeAllEnumsAsStrings();
// JWT-token authentication by password
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "password",
TokenUrl = Path.Combine(HostingEnvironment.WebRootPath, "/token"),
// Optional scopes
//Scopes = new Dictionary<string, string>
//{
// { "api-name", "my api" },
//}
});
});
Check and configure TokenUrl if your endpoint is different.
In the Startup.Configure():
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
// Provide client ID, client secret, realm and application name (if need)
// Swashbuckle.AspNetCore 4.0.1
c.OAuthClientId("swagger-ui");
c.OAuthClientSecret("swagger-ui-secret");
c.OAuthRealm("swagger-ui-realm");
c.OAuthAppName("Swagger UI");
// Swashbuckle.AspNetCore 1.1.0
// c.ConfigureOAuth2("swagger-ui", "swagger-ui-secret", "swagger-ui-realm", "Swagger UI");
});
If your endpoint for authentication by token follows the OAuth2 standard, all should work. But just in case, I have added sample of this endpoint:
public class AccountController : Controller
{
[ProducesResponseType(typeof(AccessTokens), (int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.Unauthorized)]
[HttpPost("/token")]
public async Task<IActionResult> Token([FromForm] LoginModel loginModel)
{
switch (loginModel.grant_type)
{
case "password":
var accessTokens = // Authentication logic
if (accessTokens == null)
return BadRequest("Invalid user name or password.");
return new ObjectResult(accessTokens);
case "refresh_token":
var accessTokens = // Refresh token logic
if (accessTokens == null)
return Unauthorized();
return new ObjectResult(accessTokens);
default:
return BadRequest("Unsupported grant type");
}
}
}
public class LoginModel
{
[Required]
public string grant_type { get; set; }
public string username { get; set; }
public string password { get; set; }
public string refresh_token { get; set; }
// Optional
//public string scope { get; set; }
}
public class AccessTokens
{
public string access_token { get; set; }
public string refresh_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
}
I struggled with the same problem and found a working solution in this blogpost: http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField
It comes down to adding this in your configurationoptions
services.ConfigureSwaggerGen(options =>
{
options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});
and the code for the operationfilter
public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
if (isAuthorized && !allowAnonymous)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "Authorization",
In = "header",
Description = "access token",
Required = true,
Type = "string"
});
}
}
}
Then you will see an extra Authorization TextBox in your swagger where you can add your token in the format 'Bearer {jwttoken}' and you should be authorized in your swagger requests.