我遵循了一个教程,在C#中使用OAuth保护Web API。
我正在做一些测试,到目前为止,我已经能够成功地从/token
获取访问令牌。我正在使用一个名为"高级REST Client"的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());
}
}
问题很简单:更改 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 处理程序的令牌设置的。
您必须添加具有此架构的声明:
http://schemas.microsoft.com/ws/2008/06/identity/claims/role
最好的办法是使用预定义的声明集:
identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
您可以在System.Security.Claims
中找到ClaimTypes
。
您必须考虑的另一件事是控制器/操作中的筛选器角色:
[Authorize(Roles="User")]
您可以在此处找到一个简单的示例应用程序,带有 jquery 客户端的自托管 owin。
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