我在ASP.NET MVC应用程序中使用OWIN Oauth为移动应用程序提供访问令牌。以下是OAuth的设置:
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/authenticate/login"),
Provider = dependencyContainer.GetService<IOAuthAuthorizationServerProvider>(),
RefreshTokenProvider = dependencyContainer.GetService<IAuthenticationTokenProvider>(),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(applicationSettings.AccessTokenLifeTimeInMinutes),
AllowInsecureHttp = true
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
我也有自定义提供程序和自定义刷新令牌提供程序,如上所示。一切正常,当移动设备的请求过期或无效时,我使用自定义 AuthorizeAttribute 返回带有“未授权”消息的json
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new JsonResult
{
Data = new
{
success = false,
error = "Unauthorized"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
但是在一种情况下,移动应用程序需要区分响应服务器2种情况:访问令牌已过期,或访问令牌无效(例如,在中间修改)。我不确定如何实现这一要求。我尝试创建一个自定义访问令牌提供程序,继承自 AuthenticationTokenProvider ,在上面的 UseOAuthAuthorizationServer()中注册它,但是当服务器不调用Receive()和ReceiveAsync()时从移动设备接收访问令牌
答案 0 :(得分:3)
解决了这个问题。我创建自定义访问令牌提供程序的方法有效。最初我使用 UseOAuthAuthorizationServer ()注册了它,但应该使用 UseOAuthBearerAuthentication ()来注册
这是我的自定义课程,以防有人需要:
public class CustomAccessTokenProvider : AuthenticationTokenProvider
{
public override void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
var expired = context.Ticket.Properties.ExpiresUtc < DateTime.UtcNow;
if (expired)
{
//If current token is expired, set a custom response header
context.Response.Headers.Add("X-AccessTokenExpired", new string[] { "1" });
}
base.Receive(context);
}
}
在设置OWIN OAuth时注册:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenProvider = new CustomAccessTokenProvider()
});