Reputation: 8909
I have following token generation code which is working fine for authentication without any role. I need to enable role based authentication :
public void ConfigureOAuth(IAppBuilder app)
{
double timeout = Convert.ToDouble(ConfigurationManager.AppSettings["Timeout"].ToString());
OAuthAuthorizationServerOptions OAuthserverOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(timeout),
Provider = new SimpleAuthorizationServerProvider()
};
//Token generation
app.UseOAuthAuthorizationServer(OAuthserverOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
How is it possible to enable role base authentication to the above code
So that in my web api action if i put Authorize(Roles="Admin") i can allow or deny access with the roles.
Please advice.
Upvotes: 0
Views: 222
Reputation: 793
You can use code similar to the following (assuming your using apis since your doing token auth):
public class WebApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext ctx)
{
//unauthorized code here
}
//or
protected override bool IsAuthorized(HttpActionContext actionContext)
{
//is authorized
}
}
Notice how your would inherit from System.Web.Http.AuthorizeAttribute
instead of System.Web.Mvc.AuthorizeAttribute
in a mvc controller. Additionally your parameter for HandleUnauthorizedRequest
would be of type HttpActionContext
and not AuthorizationContext
as in a mvc controller.
Now on your APIs you can use [WebApiAuthorize(Roles = "role")]
Upvotes: 1