我正在使用Angular JS和Web API2构建SPA,使用Oauth2进行身份验证。我的问题,令牌'出口是固定的,比如20分钟。那么如果用户在20分钟内没有任何请求,我们如何重定向到logion页面呢?
刷新令牌不起作用,因为系统会自动刷新令牌,尽管用户在有效时间内没有任何操作。
干杯,
答案 0 :(得分:1)
您无需在客户端应用中控制超时。 当客户端向资源服务器发出请求时,资源服务器验证访问令牌,如果它已过期,则返回401 - 未授权响应。 当客户端从资源服务器获取401时,需要使用资源所有者凭据或刷新令牌从授权服务器获取新的访问令牌。 这是OAuth 2.0 protocol指定的行为。 如果您需要更深入的解释,请告诉我。
答案 1 :(得分:0)
我使用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所提到的,你可以让你的客户只使用刷新令牌。取决于你是想要你的后端还是前端来做大部分的腿部工作。
希望它有所帮助。