【发布时间】:2021-06-18 21:23:33
【问题描述】:
我使用 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);
}
请注意,服务在共享主机上运行。
【问题讨论】:
标签: c# asp.net asp.net-web-api oauth-2.0 owin