【发布时间】:2016-12-04 06:24:37
【问题描述】:
我坚持使用 OAuth 令牌授权。我已经配置了 OAuth,并且我有自己的 OAuth 服务器提供程序。
配置代码:
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AuthorizeEndpointPath = new PathString("/authorize"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
Provider = new SimpleAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
服务器提供商:
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
当我发送:grand_type=password, username=MyUserName, password=MyPassword 到 OAuth 令牌端点 "localhost/token" 时,它很好地创建了我的 OAuth 持有者令牌。但是从这里开始,我不知道如何使用这个生成的令牌,它的存储位置(如何获取它),以及如何使用 ASP.NET MVC 控制器上的[Authorize] 属性进行成功验证。我只是想使用我生成的令牌,当我从一个视图转到另一个视图时,它具有[Authorize] 属性,并成功通过它。我怎样才能做到这一点?
【问题讨论】:
-
你可以为你生成的刷新令牌创建一个cookie,这可以跨多个视图访问,记住你的访问令牌有效期只有1小时,你需要每小时生成一个新的访问令牌
标签: asp.net asp.net-mvc oauth asp.net-mvc-5 bearer-token