如何从Cookie中检索不记名令牌?

时间:2018-12-04 10:04:23

标签: asp.net-mvc cookies bearer-token authorize-attribute cookie-authentication

我使用了承载令牌认证。我决定将令牌存储在客户端的cookie中。我已经创建了继承ServerAuthProvider的自定义OAuthAuthorizationServerProvider。我已经覆盖了将令牌放入cookie的TokenEndpointResponse()方法(将令牌添加到cookie可以正常工作):

public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
{
    if(String.IsNullOrEmpty(context.AccessToken))
    {
        context.Response.Redirect("/Authentication/Login");
    }
    else
    {
        context.Response.Cookies.Append("SocialNetworkApp", context.AccessToken);
    }

    return base.TokenEndpointResponse(context);
}

然后,我创建了一个继承自SimpleAuthorizeAttribute的自定义AuthorizeAttribute,并且重写了OnAuthorization(),该自定义从cookie中获取令牌并将其添加到请求的标头中。但是问题是,HandleUnauthorizedRequest()总是会打电话。

public class SimpleAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var tokenKey = "SocialNetworkApp";
        var cookies = filterContext.HttpContext.Request.Cookies;

        if (cookies.AllKeys.Contains(tokenKey))
        {
            var token = cookies[tokenKey].Value;
            filterContext.HttpContext.Request.Headers.Add("Authorization", "Bearer " + token);

            var tokenFrom = filterContext.HttpContext.Request.Headers.Get("Authorization");
        }

        base.OnAuthorization(filterContext);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            //if not logged, it will work as normal Authorize and redirect to the Login
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Authentication", action = "Login" }));
        }
        else
        {
            //logged and wihout the role to access it - redirect to the custom controller action
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home"}));
        }
    }
}

如果我在客户端设置了“ Authorization”标头(例如Postman),则可以正常工作。我该如何解决这个问题?

0 个答案:

没有答案