I did create custom AuthorizeAttribute
that should handle Jwt Bearer token and then create ClaimsIdentity
. But when I send request again, anyway I can't see authorized user and must create ClaimsIdentity
again and add user to CurrentPricipal
again. What I'm doing wrong?
public class JwtAuthorizeAttribute : AuthorizeAttribute
{
private readonly string role;
public JwtAuthorizeAttribute()
{
}
public JwtAuthorizeAttribute(string role)
{
this.role = role;
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var jwtToken = new JwtToken();
var ctx = actionContext.Request.GetOwinContext();
if (ctx.Authentication.User.Identity.IsAuthenticated) return true;
if (actionContext.Request.Headers.Contains("Authorization"))
{
var token = actionContext.Request.Headers.Authorization.Parameter;
try
{
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
var json = decoder.Decode(token, SiteGlobal.Secret, verify: true);
jwtToken = JsonConvert.DeserializeObject<JwtToken>(json);
if (jwtToken.aud != SiteGlobal.Audience || jwtToken.iss != SiteGlobal.Issuer || role != jwtToken.role)
{
return false;
}
}
catch (TokenExpiredException)
{
return false;
}
catch (SignatureVerificationException)
{
return false;
}
}
else
{
return false;
}
var identity = new ClaimsIdentity("JWT");
identity.AddClaim(new Claim(ClaimTypes.Name, jwtToken.unique_name));
identity.AddClaim(new Claim(ClaimTypes.Role, jwtToken.role));
ctx.Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, identity);
Thread.CurrentPrincipal = new ClaimsPrincipal(identity);
HttpContext.Current.User = new ClaimsPrincipal(identity);
return true;
}
}
Signin is used to create a cookie. Do you have a cookie Auth middleware to handle the signin?