angularjs – Web api 2 oauth2到期滑动

我正在使用Angular JS和Web API2构建SPA,使用Oauth2进行身份验证.我的问题,令牌’出口是固定的,比如20分钟.那么如果用户在20分钟内没有任何请求,我们如何重定向到logion页面呢?

刷新令牌不起作用,因为系统将自动刷新令牌,尽管用户在有效时间内没有任何操作.

干杯,

最佳答案 我使用AuthorizeAttribute并覆盖OnAuthorization

public override void OnAuthorization(HttpActionContext actionContext)
{
     string token = string.Empty;
     AuthenticationTicket ticket;
     //retrieve the token the client sent in the request...
     token = (actionContext.Request.Headers.Any(x => x.Key == "Authorization")) ? actionContext.Request.Headers.Where(x => x.Key == "Authorization").FirstOrDefault().Value.SingleOrDefault().Replace("Bearer ", "") : "";

     //Your OAuth Startup class may be called differently...
     ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(token);

     //verification using the ticket's properties. When it was set to expire (ExpiresUtc) or whatever other properties you may have appended to it's dictionnary.

    //if verification fails..
    //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Verification failed.");
    //return;

    //Otherwise, send a new token with an extended expiration date...
     AuthenticationProperties refreshTokenProperties = new AuthenticationProperties(ticket.Properties.Dictionary)
     {
            IssuedUtc = ticket.Properties.IssuedUtc,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(20)
     };

     AuthenticationTicket newToken = new AuthenticationTicket(ticket.Identity, refreshTokenProperties);
     string newTokenHash = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(newToken);

     //add the new token to request properties. Can't add it to the header here, because creating response/response headers here will prevent process from proceeding to called controller method.
     actionContext.Request.Properties.Add(new KeyValuePair<string, object>("Token", newTokenHash));
}

然后使用ActionFilterAttribute过滤器链接它:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    if (actionExecutedContext.Response == null)
        return;

    var objectContent = actionExecutedContext.Response.Content as ObjectContent;
    //the token we put in the filter above...
    string tokenHash = (actionExecutedContext.Request.Properties.Any(x => x.Key == "Token")) ? (string)actionExecutedContext.Request.Properties.Where(x => x.Key == "Token").FirstOrDefault().Value : "";
}

您可以将新标头附加到响应,放入JSON有效负载响应或将其添加为响应cookie.然后,当您请求任何其他资源时,您使客户端使用此新哈希,这样,到期时间将每次额外滑动20分钟.

您可以在App_Start / WebApiConfig.cs中全局注册这些过滤器属性

config.Filters.Add(new ClassExtendingAuthorizeAttribute());
config.Filters.Add(new ClassExtendingActionFilterAttribute());

但正如jumuro所提到的,您可以让客户只使用刷新令牌.取决于你是否想要你的后端或前端来完成大部分的腿部工作.

希望能帮助到你.

点赞