Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning User Roles to an AngularJS app from ASP.NET Identity using OAuth and bearer tokens

I'm implementing an AngularJS SPA with a backend implemented as a WebAPI seeded from a Visual Studio 2013 template. AngularJS does everything including login and I've successfully got it submitting to //localhost/token and received back a token which I add to subsequent request headers. However, I now want to make decisions on what AngularJS templates to render based on the users role(s) and therefore I need the role(s) client-side (I'm securing all my server code by role so having these decisions made client-side is fine.)

To that end I'm thinking of adding something along the lines of this...

foreach (var claim in context.Identity.Claims.Where(c => c.Type.EndsWith("/role")))
{
    context.AdditionalResponseParameters.Add("role", claim.Value);
}

... to the ApplicationOAuthProvider.TokenEndpoint() method so that the role(s) are added to the JSON that's returned back to the AngularJS code when the token is fetched.

I realise the code above doesn't work for more that one role at the moment but I'm more interested in knowing if this is the correct way to access role information and whether I'm adding it in the correct fashion?

like image 554
Phil Avatar asked Jan 18 '14 20:01

Phil


1 Answers

ng-conf happened a few days ago and a nicely thought out solution was presented. Here is the link to the video. He talks about authorization for ~10 minutes.

Basically it involves providing an activeUser service to your app and then conditionally loading directives based on features described in that service.

As for getting roles...

var userRoles = await UserManager.GetRolesAsync(User.Identity.GetUserId());
// or if not async
var userRoles = UserManager.GetRoles(User.Identity.GetUserId());

update

Since your conclusion, I might suggest something like this:

-link-

It is basically the solution spoken about at ng-conf but it's rendered inside a web-api controller. Forgoing the need for MVC all together.

What the model contains or even what index.cshtml is rendered depends upon whatever logic you use for determining whether a user is authenticated and authorized for.

like image 60
calebboyd Avatar answered Nov 12 '22 22:11

calebboyd