-1
I am implementing stunning and authentication with Identity using the concept of Claims, after I login, I am not able to save the authorization, the login returns 200 ok, but is not authorized taking then to a status 401 without authorization.
Startup.Cs
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateAudience = true
};
});
Usercontroller.Cs
private async Task<string>GenerateJWToken(User user)
{
var claims = new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName)
};
//var roles = await _userManager.GetRolesAsync(user);
//claimsIdentity.AddClaims(roles.Select(role => new Claim(ClaimTypes.Role, role)));
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token");
claimsIdentity.AddClaims(await _userManager.GetClaimsAsync(user));
var key = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(_config.GetSection("AppSettings:Token").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = claimsIdentity,
//new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
Customauthorization.Cs
public class CustomAuthorization
{
public static bool ValidarClaimsUsuario(HttpContext context, string claimName, string claimValue)
{
return context.User.Identity.IsAuthenticated &&
context.User.Claims.Any(c => c.Type == claimName && c.Value.Split(',').Contains(claimValue));
}
}
public class ClaimsAuthorizeAttribute : TypeFilterAttribute
{
public ClaimsAuthorizeAttribute(string claimName, string claimValue) : base(typeof(RequisitoClaimFilter))
{
Arguments = new object[] { new Claim(claimName, claimValue) };
}
}
public class RequisitoClaimFilter : IAuthorizationFilter
{
private readonly Claim _claim;
public RequisitoClaimFilter(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new StatusCodeResult(401);
return;
}
if (!CustomAuthorization.ValidarClaimsUsuario(context.HttpContext, _claim.Type, _claim.Value))
{
context.Result = new StatusCodeResult(403);
}
}
}