我使用 OWIN 来支持 oauth2.0 并且它运行良好,但几个小时后令牌由于某种原因无效。
进行身份验证以获取令牌
在每个请求中发送令牌(授权:Bearer token
)
它首先完美运行,然后几个小时后它变得无效并出现此错误(在 OWIN 跟踪中)
Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware Warning: 0 : invalid bearer token received
所以基本上客户端会收到错误 401。 这是使用不同的客户端类型(移动应用/邮递员/提琴手)进行测试的
Startup.cs
var options = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/path/to/token"),
Provider = new AppOAuthProvider(),
RefreshTokenProvider = new RefreshTokenProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true,
};
app.UseOAuthBearerTokens(options);
AppOAuthProvider.cs
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// Initialization.
string usernameVal = context.UserName;
string passwordVal = context.Password;
User User = authenticate();
if (User == null )
{
context.SetError("invalid_grant", "Invalid user/password");
context.Response.Headers.Add(OwinChallengeFlag, new[] { ((int)HttpStatusCode.Unauthorized).ToString() }); //Little trick to get this to throw 401, refer to AuthenticationMiddleware for more
return;
}
/*
Set permissions/claims
Permissions are set here
*/
// Setting Claim Identities for OAUTH 2 protocol.
ClaimsIdentity oAuthClaimIdentity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesClaimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
// Setting user authentication.
AuthenticationProperties properties = CreateProperties(usernameVal, User, Permissions);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthClaimIdentity, properties);
// Grant access to authorize user.
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesClaimIdentity);
}
请注意,该服务正在共享主机上运行。
答案 0 :(得分:0)
共享主机问题; IIS 每次重启都会生成一个新的机器密钥,访问令牌是基于机器密钥生成的,因此令牌在 x 时间后无法通过身份验证,其中 x 是 asp.net 或 IIS 的重启时间(取决于托管服务提供商)。
要解决此问题,请生成一个机器密钥并将其放入 web.config
中,如下所示:
<system.web>
<httpRuntime targetFramework="4.8" />
<machineKey validation="SHA1" decryption="AES" validationKey="yyyysecret" decryptionKey="xxxxsecrect" />
</system.web>
如果需要,您可以使用在线工具生成机器密钥。