【发布时间】:2017-02-04 18:00:47
【问题描述】:
我已将我的 Web API 2 项目配置为使用 OWIN 使用 OAuth
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new MyAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
MyAuthorizationServerProvider 的实现:
public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var repo = new AuthRepository();
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var user = repo.ValidateUserCredentials(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);
}
}
我可以得到一个令牌..
然后我将它发送到一个用[Authorized] 装饰的控制器并且仍然得到
{
"message": "Authorization has been denied for this request."
}
这里带有token的请求头:
Content-Type:application/json
Authorization:Bearer m6ukGHOmp_MgM6rsb70n8Rd_BlBEXbgyPNr5ZNzGzkm__7zdntVPYAMAhFPXVdw1S6-ohv960c6mzMMwkY0G_AL-2uIq2aOjkoojxDPKuITuml8sgC4ng0KC2AqUFrBBEn0eCsSAnc3UK_jyKSB59Ao_eL9JPoJHoJHP-xBs42KGAGl4iKdYtzdfg2zY0Ucif_IpPH3Gbvs6iyLVMf0jlKgj4EOBtrDHanikeqkWc0W2pWjIIac8cyUrOtZCj7h3
我在这里做错了什么?
还有 .. 想知道 .. 令牌存储在哪里? Web API 如何验证接收到的令牌是否附加到相关用户?
我是否缺少某些令牌存储类的自定义实现?如果是这样,我在哪里可以找到有关如何实现自定义令牌存储的信息?
【问题讨论】:
标签: c# asp.net-web-api oauth asp.net-web-api2 owin