【发布时间】:2016-03-31 20:58:19
【问题描述】:
我们想使用 JSON Web Token (JWT) 作为我们新 API 的 API 密钥。它们将在服务器应用程序级别使用,而不是让最终用户持久保存在缓存中。它将允许我们在授权方面比基本身份验证更精细,而不会牺牲简单性。在研究了这个想法后,我们发现一个名为“Auth0”(https://auth0.com/)的服务正在这样做,这似乎验证了我们的想法。
问题是我们似乎无法无限期地发布 JWT,因为 .NET “OAuthAuthorizationServerOptions”似乎迫使我们设置过期时间。我们已经阅读了有关“刷新令牌”的信息,但经过数小时的研究,并不清楚刷新期间发出的请求会发生什么。
例如如果客户端请求一个新的令牌,并且在检索新 JWT 期间正在发出其他请求,那么这些请求不会失败吗?
我发现一些其他平台允许旧令牌额外保持活动一分钟以适应这种情况(例如这篇文章:https://laracasts.com/discuss/channels/general-discussion/how-to-refreshing-jwt-token),但同样,它似乎在 .NET 中不可用。
谁能解释在 .NET 中刷新令牌的正确方法,但具体谈谈在检索新令牌并将其保存在客户端中时遵守请求的问题?
用代码更新我们的问题...
令牌生成:
private void OAuthTokenGeneration(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(365),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat(ConfigurationManager.AppSettings["as:live"])
};
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
授权...
private void OAuthTokenConsumption(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["as:live"];
string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
}
});
}
【问题讨论】: