【发布时间】:2016-06-15 02:42:07
【问题描述】:
我已经设法获得了一个简单的示例代码,它可以创建一个不记名令牌,还可以通过阅读 stackoverflow 上的其他论坛来通过刷新令牌请求新的令牌。
启动类是这样的
public class Startup
{
public static void Configuration(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(
new OAuthBearerAuthenticationOptions());
app.UseOAuthAuthorizationServer(
new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new OAuthAuthorizationServerProvider()
{
OnValidateClientAuthentication = async c =>
{
c.Validated();
},
OnGrantResourceOwnerCredentials = async c =>
{
if (c.UserName == "alice" && c.Password == "supersecret")
{
Claim claim1 = new Claim(ClaimTypes.Name, c.UserName);
Claim[] claims = new Claim[] { claim1 };
ClaimsIdentity claimsIdentity =
new ClaimsIdentity(
claims, OAuthDefaults.AuthenticationType);
c.Validated(claimsIdentity);
}
}
},
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(40),
AllowInsecureHttp = true,
RefreshTokenProvider = new ApplicationRefreshTokenProvider()
});
}
}
我还有一个刷新令牌的类,如下所示:
public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
{
public override void Create(AuthenticationTokenCreateContext context)
{
// Expiration time in seconds
int expire = 2 * 60;
context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
context.SetToken(context.SerializeTicket());
}
public override void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
}
}
我的理解是通过提供一个刷新令牌,你应该得到一个新的访问令牌。然而,这段代码中发生的事情是,当我提供 refresh token 时,也会创建并返回一个新的 refresh token。我希望它在第一次提供用户名/密码时同时创建 access 和 refresh token,但创建新的 refresh tokens 每次使用 刷新令牌 请求新的访问令牌?
例如,如果我给定我的代码,访问令牌有 20 分钟的时间跨度,刷新令牌有两周的时间,新的 访问令牌 可以每 20 分钟创建一次,这很好,但是新的 刷新令牌 也将每 20 分钟创建一次,但持续两周。然后会创建很多刷新令牌,但不会使用。
问题:
我几个小时前才开始阅读/了解这个,所以我很不确定,但这是正确的行为还是我应该以某种方式更改我的代码以仅创建和返回一个新的 访问令牌 当一个 refresh token 被提供并且不创建和返回一个新的 refresh token 时?非常感谢任何帮助或输入,谢谢!
【问题讨论】:
-
刷新令牌替换您的凭据,因此基本上第一次使用您的凭据进行身份验证,然后每次需要再次进行身份验证时使用刷新令牌。作为身份验证的结果,您将获得一个包含身份和声明的身份验证令牌。希望这能澄清这个概念。
标签: c# asp.net-web-api token owin