【发布时间】:2015-03-10 19:27:03
【问题描述】:
我按照教程在 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
我得到: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());
}
}
【问题讨论】:
标签: c# oauth asp.net-web-api2 owin