Авторизация в Asp.Net приложении с помощью Jose Jwt

Рейтинг: 0Ответов: 1Опубликовано: 22.03.2023

проблема такая - пытаюсь с помощью библиотеки Jose создать token и с ним авторизоваться в приложении.

Первое что я делаю, это добавляю внедрение зависимостей

// The key length needs to be of sufficient length, or otherwise an error will occur.
var tokenSecretKey = Encoding.UTF8.GetBytes(builder.Configuration.GetSection("Secret").Value);

var tokenValidationParameters = new TokenValidationParameters
{
    // Token signature will be verified using a private key.
    ValidateIssuerSigningKey = true,
    RequireSignedTokens = true,
    IssuerSigningKey = new SymmetricSecurityKey(tokenSecretKey),

    // Token will only be valid if contains "accelist.com" for "iss" claim.
    ValidateIssuer = true,
    ValidIssuer = "myName",

    // Token will only be valid if not expired yet, with 5 minutes clock skew.
    ValidateLifetime = true,
    RequireExpirationTime = true,
    ClockSkew = new TimeSpan(0, 5, 0),

    ValidateActor = false,
};

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => { options.TokenValidationParameters = tokenValidationParameters; });

app.UseAuthorization();

Создание самого токена при авторизации

var payload = new Dictionary<string, object>()
            {
                { ClaimTypes.Name, email },
                { ClaimTypes.NameIdentifier, userId.ToString() },
                { "issuer", "myName"},
                { "ex", DateTime.UtcNow.AddMinutes(10).Ticks },
                { ClaimTypes.Role, role }
               };


            byte[] b = System.Text.Encoding.UTF8.GetBytes(_config.GetSection("Secret").Value);

            Jwk key = new Jwk(b);

            string token = Jose.JWT.Encode(payload, key, Jose.JwsAlgorithm.HS256);
            return token;

Как бы я не пытался, мне пишет что токен не валиден, payload переставлял местами как кубик рубик, не могу понять где моя ошибка(

Ответы

▲ 0Принят

Помогло решить проблему 1 - Controller

[Authorize(AuthenticationSchemes = "Bearer", Roles = "user")]

2 - Создание payload

DateTime centuryBegin = new(1970, 1, 1);
            var exp = new TimeSpan(DateTime.Now.AddMinutes(50).Ticks - centuryBegin.Ticks).TotalSeconds;
            var now = new TimeSpan(DateTime.Now.Ticks - centuryBegin.Ticks).TotalSeconds;

            var payload = new Dictionary<string, object>()
            {
                { "email", email },
                { "sub", userId.ToString() },
                { "iss", "pornohub.com=)"},
                { "exp", exp },
                { "iat", now },
                { "roles", listroles }
               };