如何在JWT中使用策略进行授权

时间:2020-04-26 20:44:49

标签: asp.net-core asp.net-core-3.1 jwt-auth

我按照下面的链接进行了JWT令牌认证和class Scratch { // "static void main" must be defined in a public class. public static void main(String[] args) { String str = "bbaaabbbbccbbbbbbzzzbbbbb"; System.out.println(str.length() - 1); Solution s = new Solution(); System.out.println(s.longestRepeatingSubstring(str)); } static class Solution { public int longestRepeatingSubstring(String s) { int max = -1; int currentLength = 1; char[] array = s.toCharArray(); for (int index = 1; index < array.length; index++) { if (array[index - 1] == array[index]) { currentLength++; max = Math.max(max, currentLength); } else { currentLength = 1; } } return max; } } } https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

然后,我想使用诸如以下ASP.NET CORE 3.1 IDENTITY代码中的配置之类的策略来控制我的控制器。当我对其进行解码时,它显示Startup.cs。我想要实现的是,当用户登录时,我想检查用户是否为admin,然后为api_accessadmin创建令牌,如果角色为admin policy然后制作一个user。 我得到了角色,并在生成身份时检查角色是user policy还是user。 在将admin行放入控制器后,我尝试了Postman,然后出现以下错误。

错误

403禁止进入

[Authorize(Policy = "Admin")]

常量

services.AddAuthorization(options =>
{
    options.AddPolicy("Admin", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Role, Constants.Strings.JwtClaims.Admin));
});
services.AddAuthorization(options =>
{
    options.AddPolicy("User", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Role, Constants.Strings.JwtClaims.User));
}); 

JWT工厂生成令牌方法

public static class Strings
{
    public static class JwtClaimIdentifiers
    {
        public const string Role = "role", Id = "id";
    }

    public static class JwtClaims
    {
        public const string Admin = "admin";
        public const string User = "user";
        public const string Dashboard = "dashboard";
    }
}

AuthController

 public async Task<string> GenerateEncodedToken(string userName, string role, 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.Role),
                 identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id)
            };

            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return encodedJwt;
        }

        public ClaimsIdentity GenerateClaimsIdentity(string userName, string role, string id)
        {
            if (role == "admin")
            {
              return new ClaimsIdentity(new GenericIdentity(userName, "Token"), new[]
              {
                new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, id),
                new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Role, Helpers.Constants.Strings.JwtClaims.Admin)
              });
            }
            return new ClaimsIdentity(new GenericIdentity(userName, "Token"), new[]
            {
                new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, id),
                new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Role, Helpers.Constants.Strings.JwtClaims.User)
            });

        }


0 个答案:

没有答案