通过Jwt Bearer声明/角色进行身份验证和授权

时间:2019-08-07 14:30:27

标签: c# asp.net jwt

我正在尝试使用jwt承载创建授权,但是我无法在我的应用程序上进行授权,当我对邮递员进行操作时,它正在发生我想要的事情,但是在我的应用程序上却没有...

Service.ts(角度8)

getAll(): Observable<...[]> {
    return this.httpClient.get<...[]>(environment.url + "api",
    { headers: {'Authorization' : 'Bearer ' + token });
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    var symetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"]));
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = symetricSecurityKey
            };
        });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

AuthController.cs

[HttpPost]
[Route("login")]
public async Task<AccountModel> Login([FromBody] AccountModel model)
{

    if (ModelState.IsValid)
    {
        var user = new ApplicationUser();
        var signInResultado = new Microsoft.AspNetCore.Identity.SignInResult();

        Task.Run(async () =>
        {
            user = await _userManager.FindByEmailAsync(model.Email);
        }).Wait();

        Task.Run(async () =>
        {
            await _userManager.CheckPasswordAsync(user, model.Password);
        }).Wait();

        Task.Run(async () =>
        {
            signInResultado = await _signInManager.PasswordSignInAsync(
            user.UserName,
            model.Password,
            isPersistent: false,
            lockoutOnFailure: false);
        }).Wait();

        if (signInResultado.Succeeded)
        {
            var appUser = _userManager.Users.FirstOrDefault(u => u.Id == user.Id);
            var claims = await GetValidClaims(appUser);
            var accountModel = new AccountModel(user, _roleManager);

            accountModel.Token = GenerateJwtToken(appUser, claims);
            return accountModel;
        }

    }
    return model;
}
private string GenerateJwtToken(ApplicationUser user, List<Claim> claims)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_configuration["JwtKey"]);


    var tokens = new JwtSecurityToken(
        claims: claims,
        expires: DateTime.UtcNow.AddDays(1),
        signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        );

    return new JwtSecurityTokenHandler().WriteToken(tokens);

}
private async Task<List<Claim>> GetValidClaims(ApplicationUser user)
{
    IdentityOptions _options = new IdentityOptions();
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(_options.ClaimsIdentity.UserIdClaimType, user.Id.ToString()),
        new Claim(_options.ClaimsIdentity.UserNameClaimType, user.UserName)
    };
    var userClaims = await _userManager.GetClaimsAsync(user);
    var userRoles = await _userManager.GetRolesAsync(user);
    claims.AddRange(userClaims);
    foreach (var userRole in userRoles)
    {
        claims.Add(new Claim(ClaimTypes.Role, userRole));
        var role = await _roleManager.FindByNameAsync(userRole);
        if (role != null)
        {
            var roleClaims = await _roleManager.GetClaimsAsync(role);
            foreach (Claim roleClaim in roleClaims)
            {
                claims.Add(roleClaim);
            }
        }
    }
    return claims;
}

任何具有Role = Admin的方法

[HttpGet]
[Authorize(Roles = "Admin")]
public ActionResult<IEnumerable<RoleModel>> Get()

邮递员-登录(创建令牌)

enter image description here

邮递员-使用Role = Admin获取任何方法

enter image description here

在处理我的应用程序时,它重定向到了Identity / Account / Login

enter image description here enter image description here

0 个答案:

没有答案