Role-based authorization in ASP.NET Web API - how to set roles on the principal?

霸气de小男生 提交于 2019-12-11 08:36:09

问题


I am using recipe 10-3 in the newly released book ASP.NET Web Api 2 Recipes to support basic authentication in my Web API. This recipe utilizes a 3rd party library from Thinktecture. As seen from the below code, I am authentication the user against my own account service.

using Thinktecture.IdentityModel.WebApi.Authentication.Handler;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...            

        var authenticationConfiguration = new AuthenticationConfiguration();
        var accountService = ServiceLocator.Get<AccountService>();
        authenticationConfiguration.AddBasicAuthentication((userName, password) => accountService.Authenticate(userName, password));
        config.MessageHandlers.Add(new AuthenticationHandler(authenticationConfiguration));

        ...
   }
}

Now I want to make role-based authorization in my controllers using the Authorize attribute:

[Authorize(Roles="administrator")]
public IHttpActionResult Get()
{
    ...
}

My account service obviously knows about the users and their assigned roles, but this information is not available to the Authorize attibute (the roles are not set on the principal).

How do I accomplish this? Can the Thinktecture authentication handler be configured to set the roles on the principal? Or should I make my own custom Authorize attribute (deriving from the Authorize attribute)? And if so, should I override the OnAuthorization method to create and set the principal using my account service? Or maybe override the IsAuthorized method directly? Or maybe something else...


回答1:


The AuthenticationHandler only does authentication. You'd need to set the roles in a separate step (e.g. in a delegating handler).

If you are on Web API v2 - I'd rather recommend switching to the basic auth OWIN middleware

https://github.com/thinktecture/Thinktecture.IdentityModel/tree/master/source/Thinktecture.IdentityModel.Owin.BasicAuthentication

This gives you full control over the principal that gets created.

https://github.com/thinktecture/Thinktecture.IdentityModel/blob/master/samples/OWIN/AuthenticationTansformation/KatanaAuthentication/Startup.cs

There is also a nuget.




回答2:


I found out that the AddBasicAutentication method actually has an overload that takes a delegate for providing the roles. This is exactly what I was looking for. So now the call to AddBasicAuthentication looks like this, and everything works like a charm:

authenticationConfiguration.AddBasicAuthentication((userName, password) => accountService.Authenticate(userName, password), (username) => accountService.GetRoles(username));


来源:https://stackoverflow.com/questions/25572870/role-based-authorization-in-asp-net-web-api-how-to-set-roles-on-the-principal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!