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所提到的,您可以让客户只使用刷新令牌.取决于你是否想要你的后端或前端来完成大部分的腿部工作.

希望能帮助到你.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...