'Authorizing based on request headers in ASP.NET Core
I have an application behind an SAML Service Provider. That means, the SP does authentication for me and I get user data in HTTP request headers (like SP_USER_NAME or SP_USER_ROLE). For each endpoint, I would like to authorize users according to roles, and show some error if they have insufficient permissions.
I looked at policy-based authorization in the docs, but that seems a bit overkill for checking a header.
How do I authorize in a simple way, based on a specific header? Plese note that I develop in .NET Core 3.1
Solution 1:[1]
Hey I have solution for this please refer below point
- first of all you need to add authentication.
public void ConfigureServices(IServiceCollection services)
services.AddSession(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = >JwtBearerDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = >JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
// Adding Jwt Bearer .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = Configuration["JWTConfig:ValidAudience"], ValidIssuer = Configuration["JWTConfig:ValidIssuer"], IssuerSigningKey = new >SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTConfig:Secret"])) }; });
- After that you have to Use Session for storing authentication token and in this token you have to encrypt token combination of role list whatever role want to pass for the authorization.
Here i have used JWT Bearer token
- Using this session you have to configure in
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
startup.cs file for use header authentication.
app.UseSession(); app.Use(async (context, next) => { var token = context.Session.GetString("Token"); if (!string.IsNullOrEmpty(token)) { context.Request.Headers.Add("Authorization", "Bearer " + token); } await next(); });
- then after you you have to add in your controller
[Authorize(Roles = "Employee,Student")] public ActionResult Leave() { // your code here }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |