我已经按照教程在C#中使用OAuth保护Web API。
我正在进行一些测试,到目前为止,我已成功从/token
获取访问令牌。我使用名为"高级REST客户端"的Chrome扩展程序。测试它。
{"access_token":"...","token_type":"bearer","expires_in":86399}
这是我从/token
回来的。一切都很好看。
我的下一个请求是我的测试API控制器:
namespace API.Controllers
{
[Authorize]
[RoutePrefix("api/Social")]
public class SocialController : ApiController
{
....
[HttpPost]
public IHttpActionResult Schedule(SocialPost post)
{
var test = HttpContext.Current.GetOwinContext().Authentication.User;
....
return Ok();
}
}
}
请求是POST
并且标题为:
Authorization: Bearer XXXXXXXTOKEHEREXXXXXXX
我得到:Authorization has been denied for this request.
以JSON格式返回。
我也尝试过GET,我得到了我期望的结果,因为我没有实现它,所以不支持该方法。
以下是我的授权提供商:
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 (var 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(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
context.Validated(identity);
}
}
任何帮助都会很棒。我不确定是请求还是代码错误。
编辑:
这是我的Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
ConfigureOAuth(app);
}
public void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
答案 0 :(得分:30)
问题很简单: 更改OWIN管道的订单。
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
对于配置的OWIN管道顺序非常重要。在您的情况下,您尝试在OAuth处理程序之前使用Web API处理程序。在其中,您验证了您的请求,找到了安全操作,并尝试根据当前Owin.Context.User
对其进行验证。此时此用户不存在,因为它的设置来自带有OAuth Handler的令牌,后者稍后调用。
答案 1 :(得分:2)
您必须使用此架构添加声明:
http://schemas.microsoft.com/ws/2008/06/identity/claims/role
最好的办法是使用预先定义的一组声明:
identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
您可以在ClaimTypes
中找到System.Security.Claims
。
您必须考虑的另一件事是控制器/操作中的过滤器角色:
[Authorize(Roles="User")]
你可以找到一个简单的示例应用程序,带有jquery客户端here的自托管owin。
答案 2 :(得分:0)
看起来与其他Owin程序集共存的“ System.IdentityModel.Tokens.Jwt”的版本不合适。
如果您使用的是“Microsoft.Owin.Security.Jwt”2.1.0版,则应该使用版本3.0.2的“System.IdentityModel.Tokens.Jwt”程序集。
在包管理器控制台中,尝试:
Update-Package System.IdentityModel.Tokens.Jwt -Version 3.0.2