С токеном JWT и набором политик я получаю неавторизованный 401 - PullRequest
0 голосов
/ 24 апреля 2020

Я перехожу по учебной ссылке ниже.

https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

Я пытаюсь понять, как это работает, и я хочу использовать аутентификацию на основе ролей, используя это маркер. поэтому я сделал другую политику в файле Startup.cs, как показано ниже.

И я пытался использовать его как [Authorize(Policy = "admin")] контроллер, но каждый раз, когда я пытаюсь, я получаю unauthenticated, используя postman. Что мне не хватает? Как сделать аутентификацию на основе ролей на основе учебника?

Настроить

public void ConfigureServices(IServiceCollection services)
    { 
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.WithOrigins("http://localhost:4200", "http://localhost:44318")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

        var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

        // Configure JwtIssuerOptions
        services.Configure<JwtIssuerOptions>(options =>
        {
            options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
            options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
        });
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

            ValidateAudience = true,
            ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,

            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(configureOptions =>
        {
            configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            configureOptions.TokenValidationParameters = tokenValidationParameters;
            configureOptions.SaveToken = true;
        });

        // api user claim policy
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
        });
        services.AddAuthorization(options =>
            options.AddPolicy("admin", policy => policy.RequireRole("admin"))
        );
        var builder = services.AddIdentityCore<AppUser>(o =>
        {
            // configure identity options
            o.Password.RequireDigit = false;
            o.Password.RequireLowercase = false;
            o.Password.RequireUppercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequiredLength = 6;
        });
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
        builder.AddEntityFrameworkStores<CDSPORTALContext>().AddDefaultTokenProviders().AddRoles<IdentityRole>(); 
        //.AddRoles<IdentityRole>()
        services.AddControllers();
        services.AddAutoMapper(typeof(Startup));
        services.AddSingleton<IJwtFactory, JwtFactory>();
        services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>(); 

        services.AddScoped<IRegionRepository, RegionRepository>();
        services.AddScoped<IRegionService, RegionService>();
        services.AddScoped<IEmailHelper, EmailHelper>();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseCors("CorsPolicy");
        app.UseExceptionHandler(
                builder =>
                {
                    builder.Run(
                      async context =>
                      {
                          context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                          context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                          var error = context.Features.Get<IExceptionHandlerFeature>();
                          if (error != null)
                          {
                              context.Response.AddApplicationError(error.Error.Message);
                              await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                          }
                      });
                });


        app.UseRouting();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseAuthorization();


        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();

        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "Client";
            spa.UseAngularCliServer(npmScript: "start");
        });


    }
}

Auth Controller

// POST api/auth/login
[HttpPost("login")]
public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);



    if (identity == null)
    {
        //return null;
        return BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
    }
    var id = identity.Claims.Single(c => c.Type == "id").Value; 
    var user = await _userManager.FindByIdAsync(id);
    IList<string> role = await _userManager.GetRolesAsync(user);
    var jwt = await Tokens.GenerateJwt(identity, role[0], _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });


    return new OkObjectResult(jwt);

}

Я пытался всеми методами, но ни один из они работают

[Authorize(Policy = "ApiUser")]
[HttpGet("getPolicy")]
public string GetPolicy()
{
    return "policyWorking";
}
[Authorize(Roles = "admin")]
[HttpGet("getAdmin")]
public string GetAdmin()
{
    return "adminWorking";
}
[Authorize ]
[HttpGet("getAuthorize")]
public string GetAuthorize()
{
    return "normal authorize Working";
}

Декодированный токен

  "jti": "840d507d-b2d0-454b-bd1f-007890d3e669",
  "iat": 1587699300,
  "rol": "api_access",
  "id": "1ac370e2-f5e9-4404-b017-8a3c087e2196",
  "nbf": 1587699299,
  "exp": 1587706499

1 Ответ

0 голосов
/ 24 апреля 2020

Я забыл добавить это в appsetting.

  "JwtIssuerOptions": {
    "Issuer": "webApi",
    "Audience": "http://localhost:4200/"
  }

...