如何制作和使用基于JWT角色的身份验证? [英] How do I make and use JWT role based authentication?

查看:67
本文介绍了如何制作和使用基于JWT角色的身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我点击下面的教程链接.

I follow the tutorial link below.

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

我试图了解它的工作原理,并且想通过此令牌使用基于角色的身份验证.因此我在 Startup.cs 文件中制定了另一个策略,如下所示.

I am trying to understand how it works and I want to use role-based authentication using this token. so I made another policy in the Startup.cs file as below.

我试图在控制器中像 [Authorize(Policy ="admin")] [Authorize(Policy ="ApiUser")] 一样使用它,但每个我尝试使用 postman 获得未经身份验证的时间.我想念什么?如何基于教程进行基于角色的身份验证?

And I tried to use it like [Authorize(Policy = "admin")] or [Authorize(Policy = "ApiUser")]in the controller but every time I try I get unauthenticated using postman. What am I missing? how to make roles-based authentication based on the tutorial?

启动

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"))
);


身份验证控制器

// 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";
}

推荐答案

首先,请确保已在 appsettings.json 中添加json字符串,否则,您始终会获得 401未经授权:

Firstly,be sure you have add json string in your appsettings.json otherwise you would always get 401 unauthorized:

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

我想念什么?如何基于教程进行基于角色的身份验证?

What am I missing? how to make roles-based authentication based on the tutorial?

1.如果要使用以下方式注册服务:

1.If you want to use the following way to register the service:

services.AddAuthorization(options =>
    options.AddPolicy("admin", policy => policy.RequireRole("admin"))
);

authorize属性应如下所示:

The authorize attribute should be like below:

[Authorize(Policy  = "admin")]

2.如果要使用以下方式:

2.If you want to use the following way:

[Authorize(Roles = "admin")]

您需要从Startup.cs中删除该服务:

You need to remove the service from Startup.cs:

//services.AddAuthorization(options =>
//    options.AddPolicy("admin", policy => policy.RequireRole("admin"))
//);

然后,不要忘记在 JwtFactory.GenerateEncodedToken 中扮演角色,如下所示:

Then,don't forget to add claim with role in JwtFactory.GenerateEncodedToken like below:

public async Task<string> GenerateEncodedToken(string userName, ClaimsIdentity identity)
{
    var claims = new[]
    {
            new Claim(JwtRegisteredClaimNames.Sub, userName),
            new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
            new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
            identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol),
            identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id),
            new Claim(ClaimTypes.Role,"admin")
    };
        //...
}

这篇关于如何制作和使用基于JWT角色的身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆