. NET Core Jwt не может разрешить службу - PullRequest
0 голосов
/ 16 апреля 2020

Это мои настройки jwt в Startup.cs

services.AddIdentity<User, Role>()
    .AddUserManager<CustomUserManager>()
    .AddEntityFrameworkStores<ManagementStudioDbContext>();

    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = "bearer";
        x.DefaultChallengeScheme = "bearer";
    })
    .AddJwtBearer("bearer",x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        //x.TokenValidationParameters = tokenValidationParameters;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable(MSCASGlobals.MS_SecretKey))),
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidIssuer = "SDD",
            ValidAudience = "SDD",
            ClockSkew = TimeSpan.Zero,
        };
        x.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                if(context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                {
                    context.Response.Headers.Add("Token-Expired", "true");
                }
                return Task.CompletedTask;
            }
        };
    });

Когда я пытаюсь запустить мой API аутентификации, я получаю эту ошибку:

Невозможно разрешить службу для типа 'Microfoft.IdentityModel.Tokens.TokenValidationparameters' при попытке активировать 'Appone.Connect.Api.Token'

Этот код для создания токена:

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration[AppOne.ClassLibrary.Globals.MSCASGlobals.MS_SecretKey]));
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.UtcNow.AddMinutes(2),
        SigningCredentials = credentials,
        IssuedAt = DateTime.Now,
        Issuer = "SDD",
        Audience = "SDD"
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    var refreshToken = tokens.GenerateRefreshToken();

Connect .Api это класс контроллера. Это уже введено в мой Startup.cs

public class Token : Controller
{

    public Token()
    {

    }

    public string GenerateRefreshToken()
    {
        var random = new byte[64];
        var rng = RandomNumberGenerator.Create();

        rng.GetBytes(random);
        return Convert.ToBase64String(random).Replace("/", "_").Replace("+", "_");
    }

    public string RefreshToken(string Token, string RefreshToken, string SecretKey)
    {
        var validatedToken = GetPrincipalFromToken(Token, SecretKey);
        if (validatedToken == null)
        {
            return null; 
        }
        return "Hello";
    }

    public ClaimsPrincipal GetPrincipalFromToken(string Token, string SecretKey)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = false, //you might want to validate the audience and issuer depending on your use case
            ValidateIssuer = false,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey)),
            ValidateLifetime = false //here we are saying that we don't care about the token's expiration date
        };
        try
        {
            var principal = tokenHandler.ValidateToken(Token, tokenValidationParameters, out var validatedToken);
            if (!ValidateSecurityAlgorithm(validatedToken))
            {
                return null;
            };
            return principal;
        }
        catch(Exception e)
        {
            return null;
        }
    }

    private bool ValidateSecurityAlgorithm(SecurityToken SecurityToken)
    {
        var res = (SecurityToken is JwtSecurityToken jwtSecurityToken) && jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,StringComparison.InvariantCultureIgnoreCase);
        return res;
    }
}
...