我已經遵循教程來保護在C#中使用OAuth的Web API。返回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
我得到:在JSON返回Authorization has been denied for this request.
。
我試着做一個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());
}
}
如果你沒有註冊WebApi,你將如何做到這一點?我只是使用默認的Web API模板。 GET請求正常工作,POST請求給我401.雖然令牌是相同的。 – mwijnands
這讓我抓不住!感謝您花時間發佈此答案。 – heymega
重構後幾小時,我試圖找出這個問題的原因。 – Tomino