Как сделать политику JWT в зависимости от пользователя, вошедшего в систему? - PullRequest
0 голосов
/ 25 апреля 2020

Я перешел по ссылке ниже для аутентификации токена JWT и ASP.NET CORE 3.1 IDENTITY. https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

Затем я хотел управлять своими контроллерами, используя политику, такую ​​как конфигурация в Startup.cs коде ниже. Когда я его декодирую, он показывает api_access. Чего я хочу добиться - когда пользователь входит в систему, я хочу проверить, является ли пользователь администратором, а затем создать токен для admin и admin policy, если роль dashboard, а затем сделать dashboard policy , Я думаю, что когда пользователь входит в систему, я получаю role, затем, если role равен admin, тогда я добавляю admin policy и то же самое для other roles. Является ли этот подход правильным? Ребята, вы знаете или у вас есть другие примеры, которым я могу следовать или читать?

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

Константы

public class Constants
{

    public static class Strings
    {
        public static class JwtClaimIdentifiers
        {
            public const string Rol = "rol", Id = "id";
        }

        public static class JwtClaims
        {
            public const string ApiAccess = "api_access";
        }
    }

}

Метод фабричной генерации JWT

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

    // Create the JWT security token and encode it.
    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;
}


AuthController

[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 BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
    }


    var jwt = await Tokens.GenerateJwt(identity, _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });
    return new OkObjectResult(jwt);
}

...