访问令牌和刷新令牌是两个不同的东西。
访问令牌用于访问资源。您在每次请求时都将访问令牌发送到资源。
刷新令牌用于获取新的访问令牌,而无需发送凭据。
刷新令牌被发送到授权端点。但仅在访问令牌过期后(返回未经授权的响应)。
确保在访问令牌过期之前刷新令牌不会过期。因为否则您将不得不再次发送凭据。
另请注意,刷新令牌应保密,因为它可用于检索令牌而无需发送凭据。始终通过安全线路发送。
-- 更新--
刷新令牌的服务器端
我假设您有一个 OAuthAuthorizationServerProvider 来处理登录。比如:
internal class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
为了选择加入,您可以覆盖 GrantRefreshToken 以接受刷新令牌:
public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
{
// chance to change authentication ticket for refresh token requests
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var appUser = await userManager.FindByNameAsync(context.Ticket.Identity.Name);
var oAuthIdentity = await appUser.GenerateUserIdentityAsync(userManager);
var newTicket = new AuthenticationTicket(oAuthIdentity, context.Ticket.Properties);
context.Validated(newTicket);
}
添加提供程序以将刷新令牌添加到票证:
internal class ApplicationOAuthRefreshTokenProvider : AuthenticationTokenProvider
{
public override void Create(AuthenticationTokenCreateContext context)
{
var form = context.Request.ReadFormAsync().Result;
var grantType = form.GetValues("grant_type");
// If I remember correctly we arrive here for all implemented grant types.
// But we don't want to add a refresh token to the refresh token itself.
if (grantType[0] != "refresh_token")
{
// 35 days.
int expire = 35 * 24 * 60 * 60;
context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
context.SetToken(context.SerializeTicket());
}
base.Create(context);
}
public override void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
base.Receive(context);
}
}
别忘了在启动时注册:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// Other statements ...
// Configure the application for OAuth based flow
var oAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider("self"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
#if LIVE
AllowInsecureHttp = false,
#else
AllowInsecureHttp = true,
#endif
RefreshTokenProvider = new ApplicationOAuthRefreshTokenProvider()
};
app.UseOAuthBearerTokens(oAuthOptions);
}