我正在尝试动态设置令牌的到期时间,但看来它一直保持默认值20分钟。
这是我的ConfigureAuth:
public void ConfigureAuth(IAppBuilder app)
{
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(""),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
这是我的GrantResourceOwnerCredentials方法:
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var hasValidLogin = (new login().authenticate(context.UserName, context.Password, "") == "valid");
if (hasValidLogin == false)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return Task.FromResult<object>(null);
}
var oAuthIdentity = CreateIdentity(context);
var oAuthProperties = CreateProperties(context);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, oAuthProperties);
context.Validated(ticket);
return Task.FromResult<object>(null);
}
这是我的SetProperties方法,可以在其中设置到期时间:
public static AuthenticationProperties CreateProperties(OAuthGrantResourceOwnerCredentialsContext context)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "client_id", context.ClientId }
};
var response = new AuthenticationProperties(data);
response.ExpiresUtc = DateTime.Now.AddMonths(1);
return response;
}
即使在那之后,令牌也会返回:
{
"access_token": ".....",
"token_type": "bearer",
"expires_in": 1199,
"client_id": ".....",
".expires": "Fri, 13 Nov 2015 20:24:06 GMT",
".issued": "Fri, 13 Nov 2015 20:04:06 GMT"
}
有什么想法为什么我不能将到期时间设置为当前位置?该服务器将使用具有不同指定到期时间的各种不同客户端,因此我认为这是执行此操作的地方。我还有其他地方应该这样做吗?谢谢!
最佳答案
您看到的行为是由以下事实直接造成的:OAuth2授权服务器在GrantResourceOwnerCredentials
通知中进行设置时总是会丢弃您自己的到期(其他Grant*
通知也会受到影响):https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerHandler.cs#L386
解决方法是在中设置到期日期AuthenticationTokenProvider.CreateAsync
(用于OAuthAuthorizationServerOptions.AccessTokenProvider
的类):
只需将context.Ticket.Properties.ExpiresUtc
设置为您选择的到期日期,它就可以按照预期的方式工作:
public class AccessTokenProvider : AuthenticationTokenProvider
{
public override void Create(AuthenticationTokenCreateContext context)
{
context.Ticket.Properties.ExpiresUtc = // set the appropriate expiration date.
context.SetToken(context.SerializeTicket());
}
}
您还可以查看
AspNet.Security.OpenIdConnect.Server
,它是OWIN / Katana提供的OAuth2授权服务器的分支,其本机支持从GrantResourceOwnerCredentials
设置到期日期:https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev关于asp.net - OAuth2 Web Api token 到期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33701398/