我想在我的Web API
中实施授权,以实现与我在下面所做的相同:
我在控制器的API方法顶部放置了Authorize
属性:
[Authorize(Roles = "ApplicationOwner")]
public String Index()
{
return "Testing based on role";
}
但是这段代码无效。
我想通过使用OWIN
授权相同...我尝试使用客户端调用Web API
方法而不发送承载令牌,但我的方法每次都被调用。
请帮我修改相同的步骤。
以下是启动代码: -
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
var OAuthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
Provider = new Providers.MyAuthorizationServerProvider(),
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
var config = new HttpConfiguration();
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new
HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
每次我在承载令牌中发送适当的角色时,我都会收到错误401.我的要求是创建安全的webapi,如果消费者在请求头中发送了承载令牌,则可以访问该webapi。
公共类ApplicationOAuthProvider:OAuthAuthorizationServerProvider { private readonly string _publicClientId;
public ApplicationOAuthProvider()
{
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Role, "Application_Approver"));
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
AuthenticationProperties properties = CreateProperties("Application_Approver");
AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public static AuthenticationProperties CreateProperties(string userName, string Roles)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{"roles",Roles}
};
return new AuthenticationProperties(data);
}