1

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

1

1 Answer 1

2

Hey I have solution for this please refer below point

  1. 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"]))
           };
       });
  1. 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
  2. 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();
   });
  1. then after you you have to add in your controller
   [Authorize(Roles = "Employee,Student")]
   public ActionResult Leave()
   {
         // your code here
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.