cjskywalker
cjskywalker

Reputation: 3285

AngularJS + ASP.NET Access Control Authentication

I am working on a project needs AngularJS on the client side and ASP.NET Web Api on the server side, seems I am fairly new to Angualrjs, I couldn't find a good way to handle access control in AngularJS. AngularJS routing seems to only "work" within "App", if a user access a URL directly (http://www.test.com/customer?userid=12345), it will not work. Therefore I am thinking to let ASP.NET MVC to handle the routing for each AngularJS apps and let AngularJS routing to handle routing within each app.

My question is, once the client app (angularjs) is authenticated by the server (Token), How do I add that authentication in my ASP.NET MVC ? so I can use something like User.Identity and get all the necessary Claims from the server? or I should do the other way to let ASP.NET MVC to make the authentication call with API and store the token somewhere else for angularjs to pick it up? or is there any other way to do it ?

Upvotes: 0

Views: 1471

Answers (1)

Xavier Egea
Xavier Egea

Reputation: 4763

Once the client app (angularjs) is authenticated by the server (Token), how do I add that authentication in my ASP.NET MVC?

You have to insert the [Authorize] attribute in the actions and/or controllers that require Authentication and Authorization. There are other possibilities to achive that implementing an Authorize filter or Authenticate filter, but for the moment [Authorize] attribute it's a good point to start.

Can use something like User.Identity and get all the necessary Claims from the server?

Yes, of course. Once you retrieve the user from Db

IdentityUser user = await repository.FindUser(context.UserName, context.Password);

you will be able to get Claims, Roles, ... But this is only an example. You will be able to get the user from the token sent by you AngularJS. In fact, to get the user claims, there exists the class ClaimsPrincipal of the System.Security.Claims for this prupose.

However, it's quite difficult to answer this questions without code, so I recommend you the following series of tutorials. I'm sure they will help you:

  1. Token Based Authentication
  2. AngularJS Token Authentication
  3. Enable OAuth Refresh tokens

Edited

If you have 2 projects, one for ASP.NET MVC and other for Web API project, you have to be sure that both WebConfig files have the same machineKey tag:

<system.web>
...
<machineKey validationKey="57B449BBA8F9E656087FF7848727E122C5F5966F65AC0FC25FB3532193B59CFCD13B370883FFC184C1F1500638F33E6F67B37CAED1D9BC65BBC6CFFB232BFD0B" decryptionKey="6D9FBE88D16B3FA5B5E6B37460BBE50DA85D5B4C482159006B5A337C58AA9E79" validation="SHA1" decryption="AES" />
...
</system.web>

Use this machine Key Generator. Token is created based on the machineKey, so you have to be sure that this field is identical. If not, the token created on one project will not be valid for the other.

Upvotes: 1

Related Questions