I'm trying to figure out where I went wrong.
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "MySite API", Version = "v1" });
options.OperationFilter<AuthorizeCheckOperationFilter>();
options.OperationFilter<AddSwaggerHeadersOperationFilter>();
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = "authorization url",
TokenUrl = "token url",
Scopes = new Dictionary<string, string>()
{
{ "scope", "Scope" }
}
});
});
//Configure Method
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "MySite API V1");
options.OAuthClientId("MyClientId");
options.OAuthAppName("Swagger Api Calls");
//c.RoutePrefix = string.Empty;
});
//AuthorizeCheckOperationFilter
internal class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (context.ApiDescription.TryGetMethodInfo(out var methodInfo))
{
var attributes = methodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes(true);
if (attributes.OfType<AuthorizeAttribute>().Any())
{
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
operation.Responses.Add("403", new Response { Description = "Forbidden" });
operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
operation.Security.Add(new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new [] { "api1" } }
});
}
}
}
}
//Extra field
internal class AddSwaggerHeadersOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "SomeField",
In = "header",
Type = "string",
Required = true,
Default = "some value"
});
}
}
Now when I open up the swagger page I get the Authorize button, to which I click and when I fill out the details there I get redirected to my Identity Website which logs me in and redirects right back to swagger. Swagger then says authorized, as if everything is fine.
Then I try to use an API which requires Bearer token to be passed and it doesn't pass it. I don't see it in the header and by my logs from the identity website nothing was passed.
Any idea why or how to fix this? I'm using Swashbuckle.AspNetCore 4.1 package.
You can add DocumentFilter :
public class SecurityRequirementsDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument document, DocumentFilterContext context)
{
document.Security = new List<IDictionary<string, IEnumerable<string>>>()
{
new Dictionary<string, IEnumerable<string>>()
{
{ "oauth2", new string[]{ "openid", "profile", "email" } },
}
};
}
}
And then register the filter in AddSwaggerGen function :
options.DocumentFilter<SecurityRequirementsDocumentFilter>();
Reference : https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/603#issuecomment-368487641
I test with your code sample and it works as expected :
Related
I am currently learning how microservices work for an application i am building for my portfolio and for a small community of people that want this specific application. I have followed a tutorial online and successfully got IdentityServer4 to authenticate an MVC Client, however, I am trying to get swagger to work alongside the API's especially if they require authentication. Each time I try to authorize swagger with IdentityServer4, I am getting invalid_scope error each time I try authenticate. I have been debugging this problem for many hours an am unable to figure out the issue. I have also used the Microsoft eShopOnContainers as an example but still no luck. Any help would be greatly appreciated. Ill try keep the code examples short, please request any code not shown and ill do my best to respond asap. Thank you.
Identiy.API project startup.cs:
public class Startup {
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddInMemoryClients(Config.GetClients())
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryApiScopes(Config.GetApiScopes())
.AddTestUsers(Config.GetTestUsers())
.AddDeveloperSigningCredential(); // #note - demo purposes only. need X509Certificate2 for production)
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseStaticFiles();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}
Config.cs (i removed the test users to keep the code shorter, since it is not relevant).
#note -I created a WeatherSwaggerUI client specifically for use with swagger since this was apart of eShopOnContainers example project provided by microsoft:
public static class Config
{
public static List<TestUser> GetTestUsers()
{
return new List<TestUser>(); // removed test users for this post
}
public static IEnumerable<Client> GetClients()
{
// #note - clients can be defined in appsettings.json
return new List<Client>
{
// m2m client credentials flow client
new Client
{
ClientId = "m2m.client",
ClientName = "Client Credentials Client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = { new Secret("SuperSecretPassword".ToSha256())},
AllowedScopes = { "weatherapi.read", "weatherapi.write" }
},
// interactive client
new Client
{
ClientId = "interactive",
ClientSecrets = {new Secret("SuperSecretPassword".Sha256())},
AllowedGrantTypes = GrantTypes.Code,
RedirectUris = {"https://localhost:5444/signin-oidc"},
FrontChannelLogoutUri = "https://localhost:5444/signout-oidc",
PostLogoutRedirectUris = {"https://localhost:5444/signout-callback-oidc"},
AllowOfflineAccess = true,
AllowedScopes = {"openid", "profile", "weatherapi.read"},
RequirePkce = true,
RequireConsent = false,
AllowPlainTextPkce = false
},
new Client
{
ClientId = "weatherswaggerui",
ClientName = "Weather Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = {"https://localhost:5445/swagger/oauth2-redirect.html"},
PostLogoutRedirectUris = { "https://localhost:5445/swagger/" },
AllowedScopes = { "weatherswaggerui.read", "weatherswaggerui.write" },
}
};
}
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("weatherapi", "Weather Service")
{
Scopes = new List<string> { "weatherapi.read", "weatherapi.write" },
ApiSecrets = new List<Secret> { new Secret("ScopeSecret".Sha256()) },
UserClaims = new List<string> { "role" }
},
new ApiResource("weatherswaggerui", "Weather Swagger UI")
{
Scopes = new List<string> { "weatherswaggerui.read", "weatherswaggerui.write" }
}
};
}
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource
{
Name = "role",
UserClaims = new List<string> { "role" }
},
};
}
public static IEnumerable<ApiScope> GetApiScopes()
{
return new List<ApiScope>
{
// weather API specific scopes
new ApiScope("weatherapi.read"),
new ApiScope("weatherapi.write"),
// SWAGGER TEST weather API specific scopes
new ApiScope("weatherswaggerui.read"),
new ApiScope("weatherswaggerui.write")
};
}
}
Next project is the just the standard weather api when creating a web api project with vs2019
WeatherAPI Project startup.cs (note i created extension methods as found in eShopOnContainers as i liked that flow):
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCustomAuthentication(Configuration)
.AddSwagger(Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger()
.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Weather.API V1");
options.OAuthClientId("weatherswaggerui");
options.OAuthAppName("Weather Swagger UI");
});
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
public static class CustomExtensionMethods
{
public static IServiceCollection AddSwagger(this IServiceCollection services, IConfiguration configuration)
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Find Scrims - Weather HTTP API Test",
Version = "v1",
Description = "Randomly generates weather data for API testing"
});
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri($"{ configuration.GetValue<string>("IdentityUrl")}/connect/authorize"),
TokenUrl = new Uri($"{ configuration.GetValue<string>("IdentityUrl")}/connect/token"),
Scopes = new Dictionary<string, string>()
{
{ "weatherswaggerui", "Weather Swagger UI" }
},
}
}
});
options.OperationFilter<AuthorizeCheckOperationFilter>();
});
return services;
}
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
var identityUrl = configuration.GetValue<string>("IdentityUrl");
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = identityUrl;
options.RequireHttpsMetadata = false;
options.Audience = "weatherapi";
});
return services;
}
}
Lastly is the AuthorizeCheckOperationFilter.cs
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ||
context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();
if (!hasAuthorize) return;
operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" });
operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" });
var oAuthScheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
}
};
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[oAuthScheme ] = new [] { "weatherswaggerui" }
}
};
}
}
again, any help, or recommendations on a guide would be greatly appreciated as google has not provided me with any results to fixing this issue. Im quite new to IdentityServer4 and am assuming its a small issue due with clients and ApiResources and ApiScopes. Thank you.
The swagger client needs to access the api and to do so it requires api scopes. What you have for swagger scopes are not doing this. Change the scopes for swagger client ‘weatherswaggerui’ to include the api scopes like this:
AllowedScopes = {"weatherapi.read"}
I have a .NET 5 API using OpenApi.
Is it possible to hide all API endpoints in swagger but the login one until user is authorized with a JWT Bearer Token?
This is the code I use in startup.cs
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {
Title = "API", Version = "v1",
Description = "API (.NET 5.0)",
Contact = new OpenApiContact()
{
Name = "Contact",
Url = null,
Email = "email#email.com"
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = #"Autorización JWT utilizando el esquema Bearer en header. <br />
Introducir el token JWT generado por AuthApi.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
});
I managed to hide swagger endpoints before authentication by hacking a middleware to remove endpoints from swagger.json file for unauthenticated users and using swagger request/response interceptors to persist the received token and refresh the page after user login to re-fetch the swagger.json file.
I wrote the solution down here:
https://medium.com/#milad665/hide-endpoints-in-swagger-ui-for-unauthenticated-users-4054a4e15b89
You will need to implement your own middleware and check the endpoint path. If it starts with "/swagger" then you should challenge the authentication.
Below code authored by someone else here
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using System;
/// <summary>
/// The extension methods that extends <see cref="IApplicationBuilder" /> for authentication purposes
/// </summary>
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Requires authentication for paths that starts with <paramref name="pathPrefix" />
/// </summary>
/// <param name="app">The application builder</param>
/// <param name="pathPrefix">The path prefix</param>
/// <returns>The application builder</returns>
public static IApplicationBuilder RequireAuthenticationOn(this IApplicationBuilder app, string pathPrefix)
{
return app.Use((context, next) =>
{
// First check if the current path is the swagger path
if (context.Request.Path.HasValue && context.Request.Path.Value.StartsWith(pathPrefix, StringComparison.InvariantCultureIgnoreCase))
{
// Secondly check if the current user is authenticated
if (!context.User.Identity.IsAuthenticated)
{
return context.ChallengeAsync();
}
}
return next();
});
}
}
And then in your startup.cs (below sequence matters)
app.RequireAuthenticationOn("/swagger");
app.UseSwagger();
app.UseSwaggerUI();
I finally ended up hidding swagger enpoints using appsettings.json parameters, not exactly what I was asking for, but I'll post the solution in case it helps someone as it may work to filter logged users:
There are some commented blocks and unused code that may be useful for you, as it came with the example I found on the web.
Swagger ignore filter class:
public class SwaggerIgnoreFilter : IDocumentFilter
{
private IServiceProvider _provider;
public SwaggerIgnoreFilter(IServiceProvider provider)
{
if (provider == null) throw new ArgumentNullException(nameof(provider));
this._provider = provider;
}
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(i => i.GetTypes()).ToList();
var http = this._provider.GetRequiredService<IHttpContextAccessor>();
var authorizedIds = new[] { "00000000-1111-2222-1111-000000000000" }; // All the authorized user id's.
// When using this in a real application, you should store these safely using appsettings or some other method.
var userId = http.HttpContext.User.Claims.Where(x => x.Type == "jti").Select(x => x.Value).FirstOrDefault();
var show = http.HttpContext.User.Identity.IsAuthenticated && authorizedIds.Contains(userId);
//var Securitytoken = new JwtSecurityTokenHandler().CreateToken(tokenDescriptor);
//var tokenstring = new JwtSecurityTokenHandler().WriteToken(Securitytoken);
//var token = new JwtSecurityTokenHandler().ReadJwtToken(tokenstring);
//var claim = token.Claims.First(c => c.Type == "email").Value;
Parametros parametros = new Parametros();
if (!show)
{
var descriptions = context.ApiDescriptions.ToList();
foreach (var description in descriptions)
{
// Expose login so users can login through Swagger.
if (description.HttpMethod == "POST" && description.RelativePath == "denarioapi/v1/auth/login")
continue;
var route = "/" + description.RelativePath.TrimEnd('/');
OpenApiPathItem path;
swaggerDoc.Paths.TryGetValue(route, out path);
switch(route)
{
case string s when s.Contains("/Contabilidad"):
if (parametros.contabilidadApi != "1")
{
swaggerDoc.Paths.Remove(route);
}
break;
case string s when s.Contains("/Identificativos"):
if (parametros.identificativosApi != "1")
{
swaggerDoc.Paths.Remove(route);
}
break;
case string s when s.Contains("/Centros"):
if (parametros.centrosApi != "1")
{
swaggerDoc.Paths.Remove(route);
}
break;
case string s when s.Contains("/Contratos"):
if (parametros.contratosApi != "1")
{
swaggerDoc.Paths.Remove(route);
}
break;
case string s when s.Contains("/Planificacion"):
if (parametros.planificacionApi != "1")
{
swaggerDoc.Paths.Remove(route);
}
break;
case string s when s.Contains("/Puestotrabajo"):
if (parametros.puestotrabajoApi != "1")
{
swaggerDoc.Paths.Remove(route);
}
break;
case string s when s.Contains("/Usuarios"):
if (parametros.usuariosApi != "1")
{
swaggerDoc.Paths.Remove(route);
}
break;
default:
break;
}
// remove method or entire path (if there are no more methods in this path)
//switch (description.HttpMethod)
//{
//case "DELETE": path. = null; break;
//case "GET": path.Get = null; break;
//case "HEAD": path.Head = null; break;
//case "OPTIONS": path.Options = null; break;
//case "PATCH": path.Patch = null; break;
//case "POST": path.Post = null; break;
//case "PUT": path.Put = null; break;
//default: throw new ArgumentOutOfRangeException("Method name not mapped to operation");
//}
//if (path.Delete == null && path.Get == null &&
// path.Head == null && path.Options == null &&
// path.Patch == null && path.Post == null && path.Put == null)
//swaggerDoc.Paths.Remove(route);
}
}
foreach (var definition in swaggerDoc.Components.Schemas)
{
var type = allTypes.FirstOrDefault(x => x.Name == definition.Key);
if (type != null)
{
var properties = type.GetProperties();
foreach (var prop in properties.ToList())
{
var ignoreAttribute = prop.GetCustomAttribute(typeof(OpenApiIgnoreAttribute), false);
if (ignoreAttribute != null)
{
definition.Value.Properties.Remove(prop.Name);
}
}
}
}
}
}
Startup.cs ConfigureServices:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "API",
Version = "v1",
Description = "API (.NET 5.0)",
Contact = new OpenApiContact()
{
Name = "Contact name",
Url = null,
Email = "email#email.com"
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = #"Description",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer"
});
c.DocumentFilter<SwaggerIgnoreFilter>();
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
});
First create and add a new DocumentFilter, that strips all information from your swagger.json for unauthorised users. You can be very specific what to remove or keep, but this example simply strips all Endpoints and Schemas but keeps the Auth information which are required for authorisation.
public class RequireAuthenticationDocumentFilter : IDocumentFilter
{
private readonly IHttpContextAccessor _httpContextAccessor;
public RequireAuthenticationDocumentFilter(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
bool isAuthenticated =
_httpContextAccessor.HttpContext?.User.Identity?.IsAuthenticated ?? false;
if (!isAuthenticated)
{
swaggerDoc.Paths.Clear();
context.SchemaRepository.Schemas.Clear();
}
}
}
Then add the RequireAuthenticationDocumentFilter. Your should now see no Endpoints or Schema in your swagger.json and therefore SwaggerUI.
services.AddSwaggerGen(options =>
{
options.DocumentFilter<RequireAuthenticationDocumentFilter>();
}
Next step is to configure SwaggerUI to persist the Auth Token between page reloads. The RequestInterceptor (a JavaScript function you can inject) then uses the persisted token when requesting the swagger.json.
app.UseSwaggerUI(options =>
{
options.EnablePersistAuthorization();
if (settings.RequireAuthentication)
{
options.UseRequestInterceptor("(request) => {" +
// " debugger;" +
" if (!request.url.endsWith('swagger.json')) return request;" +
" var json = window.localStorage?.authorized;" +
" if (!json) return request;" +
" var auth = JSON.parse(json);" +
" var token = auth?.oauth2?.token?.access_token;" +
" if (!token) return request;" +
" request.headers.Authorization = 'Bearer ' + token;" +
" return request;" +
"}");
}
}
Note, that the swagger.json is requested on SwaggerUI page load. After authorising via SwaggerUI you need to manually reload the page in order to request your swagger.json again, but this time with the persisted authorisation information.
When experiencing problems while checking the authentication in the RequireAuthenticationDocumentFilter, make sure that authentication and authorisation takes place, before adding Swagger and SwaggerUI to your ASP.NET Core Middleware Pipeline.
...
app.UseAuthentication();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI();
...
I've seen numerous examples of how to use JWT authentication with Angular, React, Vue etc... clients but can't find any examples of using JWT authentication with ASP.NET Core (specifically 2.2) Web App Mvc.
Does anyone have any examples or advice on how to do this?
Thanks,
You can use this class based on nuget package JWT 3.0.3
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Newtonsoft.Json;
using System;
namespace Common.Utils
{
public class JwtToken
{
private IJwtEncoder encoder;
private IJwtDecoder decoder;
/// <remarks>
/// This requires a key value randomly generated and stored in your configuration settings.
/// Consider that it is a good practice use keys as at least long as the output digest bytes
/// length produced by the hashing algorithm used. Since we use an HMAC-SHA-512 algorithm,
/// then we can provide it a key at least 64 bytes long.
/// <see cref="https://tools.ietf.org/html/rfc4868#page-7"/>
/// </remarks>
public string SecretKey { get; set; }
public JwtToken()
{
IJwtAlgorithm algorithm = new HMACSHA512Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider datetimeProvider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, datetimeProvider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
decoder = new JwtDecoder(serializer, validator, urlEncoder);
SecretKey = "";
}
public JwtToken(string secretKey) : this()
{
SecretKey = secretKey;
}
public bool IsTokenValid(string token)
{
return !string.IsNullOrWhiteSpace(DecodeToken(token));
}
public string GetToken(object payload)
{
try
{
return encoder.Encode(payload, SecretKey);
}
catch (Exception)
{
return encoder.Encode(new DataModel(payload), SecretKey);
}
}
public string DecodeToken(string token)
{
try
{
if (string.IsNullOrWhiteSpace(token) || token == "null")
{
return null;
}
return decoder.Decode(token, SecretKey, true);
}
catch (TokenExpiredException)
{
return null;
}
catch (SignatureVerificationException)
{
return null;
}
}
public T DecodeToken<T>(string token) where T : class
{
try
{
if (string.IsNullOrWhiteSpace(token))
{
return null;
}
return decoder.DecodeToObject<T>(token, SecretKey, true);
}
catch (TokenExpiredException)
{
return null;
}
catch (SignatureVerificationException)
{
return null;
}
catch (Exception)
{
var data = decoder.DecodeToObject<DataModel>(token, SecretKey, true).Data;
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(data));
}
}
}
public class DataModel
{
public DataModel(object data)
{
Data = data;
}
public object Data { get; set; }
}
}
Then in your Startup class Configure method set the jwt middleware
for check authentication status of each request:
app.Use((context, next) =>
{
// verify app access token if not another service call
var appAccessToken = context.Request.Headers["Authorization"];
if (appAccessToken.Count == 0)
{
context.Items["User"] = null;
}
else
{
var token = appAccessToken.ToString().Replace("Bearer ", "");
var jwtToken = new JwtToken(config.JwtTokenSecret); //you need a secret (with requirements specified above) in your configuration (db, appsettings.json)
if (string.IsNullOrWhiteSpace(token) || !jwtToken.IsTokenValid(token))
{
context.Response.StatusCode = 401;
return Task.FromResult(0);
}
dynamic user = jwtToken.DecodeToken<dynamic>(token);
var cachedToken = cache.Get(user.Id); //you need some cache for store your token after login success and so can check against
if (cachedToken == null || cachedToken.ToString() != token)
{
context.Response.StatusCode = 401;
return Task.FromResult(0);
}
context.Items["User"] = new Dictionary<string, string>() {
{ "FullName",user.Name?.ToString()},
{ "FirstName",user.FirstName?.ToString()},
{ "LastName",user.LastName?.ToString()},
{ "Role",user.Role?.ToString()},
{ "Email",user.Email?.ToString()}
};
}
return next();
});
And finally you need generate the token and return it after
authentication:
[AllowAnonymous]
public IActionResult Login(string username, string password)
{
User user = null; //you need some User class with the structure of the previous dictionary
if (checkAuthenticationOK(username, password, out user)) //chackAuthenticationOk sets the user against db data after a succesfull authentication
{
var token = new JwtToken(_config.JwtTokenSecret).GetToken(user); //_config is an object to your configuration
_cache.Set(user.id, token); //store in the cache the token for checking in each request
return Ok(token);
}
return StatusCode(401, "User is not authorized");
}
Add following code to startup
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Issuer"],
ValidAudience = Configuration["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SigningKey"]))
};
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
}
Code for login action in AccountController
[Route("api/[controller]")]
public class AccountController : Controller
{
[AllowAnonymous]
[HttpPost]
[Route("login")]
public IActionResult Login([FromBody]LoginViewModel loginViewModel)
{
if (ModelState.IsValid)
{
var user = _userService.Authenticate(loginViewModel);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, loginViewModel.Username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken
(
issuer: _configuration["Issuer"],
audience: _configuration["Audience"],
claims: claims,
expires: DateTime.UtcNow.AddDays(10),
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SigningKey"])),
SecurityAlgorithms.HmacSha256)
);
return Ok(new
{
access_token = new JwtSecurityTokenHandler().WriteToken(token),
expires_in = (int)token.ValidTo.Subtract(DateTime.UtcNow).TotalSeconds,// TimeSpan.FromTicks( token.ValidTo.Ticks).TotalSeconds,
sub = loginViewModel.Username,
name = loginViewModel.Username,
fullName = user.FullName,
jobtitle = string.Empty,
phone = string.Empty,
email = user.EmailName,
});
}
}
}
I assume you have implemented JWT on the server side. To handle this on client side, first you have to add token to web browser local storage. Add to your main layout javascript (let's named it AuthService.js)
below code adds token to local storage after login button clicked. gettokenfromlocalstorage() retrieve token from local storage.
<script>
var token = "";
function Loginclick() {
var form = document.querySelector('form');
var data = new FormData(form);
var authsevice = new AuthService();
authsevice.LogIn(data.get("username").toString(), data.get("password").toString());
}
function gettokenfromlocalstorage() {
var authserv = new AuthService();
var mytoken = authserv.getAuth();
authserv.LogOut();
}
var AuthService = /** #class */ (function () {
function AuthService() {
this.authKey = "auth";
}
AuthService.prototype.LogIn = function (username, password) {
this.username = username;
this.password = password;
this.grant_type = "password";
this.client_id = "MyClientId";
var loginurl = "/api/Token/Auth";
var xhr = new XMLHttpRequest();
xhr.open("POST", loginurl, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(this));
xhr.onreadystatechange = function () {
console.log("onreadystatechange");
};
xhr.onerror = function () {
var aaa = this.responseText;
};
xhr.onload = function () {
var data = JSON.parse(this.responseText);
var auth = new AuthService();
auth.setAuth(data);
};
};
AuthService.prototype.LogOut = function () {
this.setAuth(null);
return true;
};
AuthService.prototype.setAuth = function (auth) {
if (auth) {
localStorage.setItem(this.authKey, JSON.stringify(auth));
}
else {
localStorage.removeItem(this.authKey);
}
return true;
};
AuthService.prototype.getAuth = function () {
var i = localStorage.getItem(this.authKey);
return i === null ? null : JSON.parse(i);
};
AuthService.prototype.isLoggedIn = function () {
return localStorage.getItem(this.authKey) !== null ? true : false;
};
return AuthService;
}());
var aa = new AuthService();
var gettoken = aa.getAuth();
if (gettoken !== null) {
token = gettoken.token;
}
</script>
To add token to the header of each anchor tag put below script also to
your main layout.
<script>
var links = $('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = function check() {
addheader(this.href);
return false;
}
}
function addheader(object) {
let xhr = new XMLHttpRequest();
xhr.open("GET", object, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.send(null);
xhr.onload = function () {
window.history.pushState("/", "", xhr.responseURL);
//mycontainer is a div for parialview content
$("#mycontainer").html(xhr.responseText);
window.onpopstate = function (e) {
if (e.state) {
$("html").html = e.state;
document.title = e.state.pageTitle;
}
};
};
}
</script>
Remember that using of this approach, each view has to be loaded as a partial view.
If you insert url address in a web browser bar directly this solution doesn't work. I haven't figured it out yet. That's why to manage token authentication is better using single page application, not multipage application.
You can use this boilerplate to understand how to implement JWT tokenization with .Net Core. In the project you can find JWT, Swagger and EF features.
I know that I can add header parameter for all API in swagger as described in Web Api How to add a Header parameter for all API in Swagger
With this approach, the header parameter will show up in swagger UI for all APIs.
But not all of my APIs/controllers need the header parameter, is there a way to add header only for specific controller or even a specific API?
Though this post is old, I thought it would help new comers if they get stuck
in the same situation.
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry,
ApiDescription apiDescription)
{
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
/*System.Diagnostics.Trace.WriteLine(apiDescription.RelativePath +
"=paath");*/
if (apiDescription.RelativePath.Contains(***{url***}))
{
operation.parameters.Add(new Parameter
{
name = "X-User-Token",
#in = "header",
type = "string",
required = false,
description=""
});
operation.parameters.Add(new Parameter
{
name = "authorization",
#in = "header",
description = "Token",
type = "string",
required = true
});
}
else
{
operation.parameters.Add(new Parameter
{
name = "X-User-Token",
#in = "header",
type = "string",
required = false,
description="description"
});
}
}
}
In Asp.Net Core/.net6
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;
namespace YourProduct
{
public class HttpHeaderOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
operation.Parameters.Add(new OpenApiParameter
{
Name = "X-your-Custom-header",
In = ParameterLocation.Header,
AllowEmptyValue = true,
Required = false,
Description = "Your custom header Name"
});
}
}
}
in the action
[HttpPost("[action]")]
[SwaggerOperationFilter(typeof(HttpHeaderOperationFilter))] //<-- point of interest
public IActionResult DoSomething([FromBody] YourModel model)
{
. . . . . . .
And don't forget startup.cs
services.AddSwaggerGen(opt =>
{
opt.EnableAnnotations(); // <-- this
}
I am trying to integrate IdentityServer4 with ASP.NET MVC WebAPI.I want to achieve role based authorization. I have the following projects running.
IdentityServer4 [a separate project]
WebApi
Javascript Application [using Extjs]
I have implemented the ResourceOwnerPassword flow and what I am trying to do is,
Make a post request to AccountController of the WebApi containing username and password
Inside the AccountController call the IdentityServer token endpoint for an access token and return the access token to the client (javascript app)
Make a request to the WebApi containing the access token.
For the above part I am success full, here is the code
POSTMAN call for Login
AccountController
[ActionName("Login")]
[AllowAnonymous]
[HttpPost]
public async Task<BaseModel> Login(LoginModel model)
{
model.RememberMe = false;
var status = await _security.Login(model.Email, model.Password, model.RememberMe);
if (status.Status == LoginStatus.Succeded)
{
return new BaseModel { success = true, message = "login", data = status.Data };
}
}
SecurityService
public async Task<LoginResponse> Login(string userName, string password, bool persistCookie = false)
{
// discover endpoints from metadata
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
// request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");
var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(userName, password, "api1");
if (tokenResponse.IsError)
{
return new LoginResponse { Status = LoginStatus.Failed, Message = tokenResponse.Error };
}
return new LoginResponse { Status = LoginStatus.Succeded, Data = tokenResponse.Json };
}
Security the API
I have two more actions inside the AccountController (just for testing) namely:
values() [returns success and requires no authentication]
SecureValues [returns success and requires authentication]
[HttpGet]
public BaseModel values()
{
return new BaseModel
{
success = true
};
}
[Authorize]
[HttpGet]
public BaseModel SecureValues()
{
return new BaseModel
{
success = true
};
}
calling "Values" action returns the success which is quite obvious, calling the "SecureValues" gives following
Which means that the user is not Authenticated.
My IdentityServer4 configuration is as follows:
public class Config
{
// scopes define the resources in your system
public static IEnumerable<Scope> GetScopes()
{
return new List<Scope>
{
StandardScopes.OpenId,
StandardScopes.Profile,
new Scope
{
Name = "api1",
Description = "My API",
DisplayName = "API Access",
Type = ScopeType.Resource,
IncludeAllClaimsForUser = true,
Claims = new List<ScopeClaim>
{
new ScopeClaim(ClaimTypes.Name),
new ScopeClaim(ClaimTypes.Role)
}
},
new Scope
{
Enabled = true,
Name = "role",
DisplayName = "Role(s)",
Description = "roles of user",
Type = ScopeType.Identity,
Claims = new List<ScopeClaim>
{
new ScopeClaim(ClaimTypes.Role,false)
}
},
StandardScopes.AllClaims
};
}
// clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
},
// resource owner password grant client
new Client
{
ClientId = "ro.client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
},
// OpenID Connect implicit flow client (MVC)
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Implicit,
//flow
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002" },
AllowedScopes =
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
"role"
}
},
//for hybrid flow
new Client
{
ClientId = "mvchybrid",
ClientName ="mvc hybrid client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = {"http://localhost:5003/signin-oidc"},
PostLogoutRedirectUris = {"http://localhost:5003"},
AllowedScopes =
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
StandardScopes.OfflineAccess.Name,
"api1"
}
},
new Client
{
ClientId = "js",
ClientName = "javascript client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser= true,
RedirectUris = {"http://localhost:5004/callback.html"},
PostLogoutRedirectUris = {"http://localhost:5004/index.html"},
AllowedCorsOrigins = {"http://localhost:5004"},
AllowedScopes =
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
"api1",
"role",
StandardScopes.AllClaims.Name
}
},
//aspnet identity client
new Client
{
ClientId = "mvcIdentity",
ClientName = "Mvc Identity Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
RequireConsent = false,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = {"http://localhost:5005/signin-oidc"},
PostLogoutRedirectUris = {"http://localhost:5005"},
AllowedScopes =
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
StandardScopes.OfflineAccess.Name,
"api1"
}
}
};
}
public static List<InMemoryUser> GetUsers()
{
return new List<InMemoryUser>
{
new InMemoryUser
{
Subject = "1",
Username = "alice#yahoo.com",
Password = "password",
Claims = new List<Claim>
{
new Claim("name", "Alice"),
new Claim("website", "https://alice.com"),
new Claim(ClaimTypes.Role,"FreeUser")
}
},
new InMemoryUser
{
Subject = "2",
Username = "bob#yahoo.com",
Password = "password",
Claims = new List<Claim>
{
new Claim("name", "Bob"),
new Claim("website", "https://bob.com"),
new Claim(ClaimTypes.Role,"PaidUser")
}
}
};
}
}
WebApi configuration
public void ConfigureAuth(IAppBuilder app)
{
app.UseIdentityServerBearerTokenAuthentication(new IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions
{
Authority = "localhost:5000",
RequiredScopes = new[] { "api1" },
ClientId = "ro.client",
ClientSecret = "secret",
PreserveAccessToken = true
});
}
It looks like your Authority in your UseIdentityServerBearerTokenAuthentication middleware is wrong. I think it should be "http://localhost:5000".
Also enabling logging (with trace) to console you can see why your authorization was challenged sometimes.