通过OWIN AuthenticationManager.SignIn添加ClaimsIdentity不起作用

时间:2017-07-29 16:50:38

标签: c# owin claims-based-identity authorize-attribute current-principal

我确实创建了应该处理Jwt Bearer令牌的自定义AuthorizeAttribute,然后创建ClaimsIdentity。但是,当我再次发送请求时,无论如何我都无法看到授权用户,必须再次创建ClaimsIdentity并再次将用户添加到CurrentPricipal。我做错了什么?

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

1 个答案:

答案 0 :(得分:0)

Signin用于创建cookie。你有一个cookie Auth中间件来处理登录吗?