我已按照教程使用 C# 中的 OAuth 保护 Web API。
我正在做一些测试,到目前为止我已经能够成功地从/token
。我正在使用名为“Advanced 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
I get: 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());
}
}