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);
}
1 回答
访问令牌和刷新令牌是两回事 .
访问令牌用于 access 资源 . 您可以在每次请求时将访问令牌发送到资源 .
刷新令牌用于获取新的访问令牌,而无需发送凭据 . The refresh token is send to the authorization endpoint. 但仅在访问令牌过期后(返回未经授权的响应) .
确保在访问令牌过期之前刷新令牌不会过期 . 因为否则您将不得不再次发送凭据 .
另请注意,refesh令牌应保密,因为它可用于检索令牌而无需发送凭据 . 始终通过安全线路发送 .
The server side of the refresh token
我假设你有一个OAuthAuthorizationServerProvider来处理登录 . 就像是:
为了选择加入,您可以覆盖GrantRefreshToken以接受刷新令牌:
添加提供程序以向故障单添加刷新令牌:
不要忘记在创业公司注册: