Role Based Navigation Display on the Frontend - angularjs

I have a REST API served by Spring boot and I'm using JWT tokens that I generate on my backend server and give the token to the frontend application which is based on AngularJS and HTML5. I want to now control the display of the navigation based on the role of the logged in user.
The question is:
How could the newly logged in user with his token be identified on the frontend as admin so that I can show navigation link A, B and C for example..? Should my AngularJS fronend unpack the token?
When a non Admin user logs in, I can show just navigation links A and B.
How could I do this? Any suggestions?

Should my AngularJS fronend unpack the token?
Yes, if you want to depend on data that is in the token, use it, that is one of the benefits of JWT.
Place an admin or similar claim on your token, and use it. Don't worry about "security", and having an invalid token, because you are using Angular, all your views and logic is easily accessible anyway via developer tools or similar tool, and your "real" security is by checking the token on the server-side anyway.
You can use angular-jwt module for simple JWT handling in AngularJS app.

Related

Authentication and Authorization in React app

In a .NET app I can add authentication and authorization using web.config and/or IIS. I can also use [Authorize (Roles = "RoleABC")] in a MVC app's controller or action. And even extend the AuthorizationAttribute
I'm looking into creating a React app for intranet use, and reading these tutorials (ReactJS and MS), but can't find authentication/authorization details.
Even though the app will be Single Page App, I still would like to authenticate and authorize users for certain options within the app, just like I can do in MVC app.
Is the only option to do that way is creating Blazor app instead?
For authentication and authorization, you should use auth tokens (like JWT). Your backend should create an auth token when a client logs in to the system and sends it to the client. Your server also should send the authenticated user information to the client (react app) so that you can render correct pages according to the user type. For example, you can render the admin page for an admin type of user, and the guest page for a guest type of user. You can save this user data as JSON in Redux. Hence you can access the user data from any component of your react. Also, in your backend, you must restrict the endpoints according to the auth token which is sent by the client. In the backend of my app, I follow the below steps:
Authentication check -> Authorization check -> controller (endpoint) -> result
React isn't opinionated on this, so it's up to you to design the implementation. A basic way to do this is:
Log in and obtain an authorized JWT token from the backend and include the account ID when you sign it
Store the JWT token in localStorage, store the account info in Redux
Conditionally limit routes based on account info (ie. admin group) on the front end
Have every auth-required API call include the JWT token in the x-auth-token header, then on the backend use middleware to check if it's still valid. You can then also decode the account ID in order to check its privileges so that you can limit API access
This may be helpful: https://medium.com/#faizanv/authentication-for-your-react-and-express-application-w-json-web-tokens-923515826e0#5f52
Not sure whether you still need this - I personally feel we should have something bridging the authZ gap between server and client to make it easy. So I spent a few days on a github project for this purpose, here it is: authzyin.
What I tried to do is to leverage policy based authorization from asp.net core - which I think it's very cool - and automatically bring the same definition to the client to use in React via hooks.
For authentication I am using msal.js against AAD - so authN is done on the client and jwt bearer token auth is used for all requests.
It has a client lib and a server lib which can be used together or separately. Of course it might still be lacking some features - please feel free to take it as a reference (contribution is also welcome).

Returning Permissions From Web Api to AngularJs client

I am building an application with a set of user types. I have a .Net MVC 5 Web Api web service and an angularjs SPA. I would like to have my SPA display pages relative to the user type logged in. I am authenticating with bearer tokens which I then store in localStorage.
I have thought of making web api, return the token with the user's claims and roles, I can then use this information to decide what pages to display to the user, however, I worry that the user can easily alter this information.
Could you please advise how I can achieve this without introducing a security exploit.
Thanks in advance.
In the server side which is your controller, you should add some authorization filter. Resolve the token to the requesting user and verify authorization. Implement some caching so you are not querying the database (or some user store) each time. You don't have control on the client-side. They can alter however they want in the display and compose their request. So that is why it is important to put these authentication/authorization in each request.

Oauth social login using MEAN.js Restful sessionless API backend

I'm developing a Restful API using MEAN.js, which will be consumed by an AngularJS Web site and Phonegap Mobile Apps.
I'd like the user to be able to create an account and/or login using Faceboo, Google and Twitter.
I'm trying to use the same sample code that comes with MEAN.js seed application, but with the Node side of it, on port 3000 serving only the API, and the web site running on another server (currently on port 9000).
I','ve already implemented Token authentication using a Passport custom Local strategy, which generates a token, and the Bearer Strategy to autheticate API calls.
But I'm having problems with social login, to link social accounts to existing users.
From the Angular Client I call an api endpoint that redirects the user to the oauth provider (e.g. Twitter). When the user comes back, my serve has no knowledge of the logged user, since I'm not using sessions anymore.
I've tried to return the provider token to the client, but have problems parsing the anguler url. Then I coded another page outside angular that receives the provider token and calls an api endpoint sending the oauth token and the token issued by my api. It worked for Google, but not for Twitter. It seems twitter needs a session.
Anyway, what is the best approach to achieve what I want? How can I make this work?
Since your using Angularjs, take a look at this Angularjs library https://github.com/sahat/satellizer. The library pretty much opens up an oauth popup and checks the popup url for tokens. You can easily replicate the approach or just use this library. It works with a few social media providers like Twitter and its easy to add more.
I was in need of the same thing and so I set out to create my own. It's still in development but should give you a good start. Feel free to create a pull request and help to make it better. Maybe we can eventually merge it into their codebase.
https://github.com/elliottross23/MeanJsSocialLoginTokenAuth

Example of an SPA with a login screen that uses AngularJS and connects to ASP.NET Web API 2?

I would like to create a new AngularJS, Web API Single page application. Does anyone have any examples that show how I can set up a user login screen that connects to a WEB API controller for a simple login (no need for google/facebook login etc) that uses ASP.NET Identity and without the need for user registration.
Also how can I handle showing a new view once the login has been completed. What I would like is to have a solution that does not show routing in the browser URL. So for example I would like to be able to switch from the login view and a couple of other different views without the url changing from www.abc.com.
In other words I would like to avoid showing www.abc.com/login, www.abc.com/screen1, www.abc.com/screen2
Any advice would be much appreciated.
So, instead of trying to find an example, I created one instead (link at the bottom). To explain how the functionality works, I want to go over a few things:
The new ASP.NET Identity system provides an OAuth 2.0 Bearer token implementation which can be used with clients that consume a Web API resource over HTTP. Since the authentication is not stored in a session cookie, the server is not responsible for maintaining the authentication state. The side-effect is that the consumer has to manage authenticating the server and managing the returned token. This is the system that Microsoft uses in the SPA template that it provides with VS 2013.
AngularJS makes no assumptions about authentication, so it's up to you how to authenticate.
AngularJS provides the $http service for querying remote HTTP-based services as well as $resource which is built on top of $http. Using Authorization headers with the Bearer token implementation above, you can combine both to provide authenticated access to server resources over HTTP. AngularJS allows you to set a 'default' Authorization header which it will use in every subsequent HTTP transaction.
With that in mind, the way I accomplished this is by creating a User service that handles all of the authentication details, including setting the HTTP Authorization header, between the Web API server and the SPA. Based on the authentication status of the user, you can hide certain UI elements in order to prevent navigation. However, if you also define the state as requiring authentication as a property of the resolve object for the state, a watcher set on the $stateChangeError event will capture the error and redirect the user to the login form. Upon proper authentication, it will then redirect the user to the state they were trying to navigate to.
In order to prevent authentication from being lost between browser sessions (since the client is responsible for maintaining the authentication token, and that token is maintained in memory), I also added the ability for the user to persist the authentication to a cookie. All of this is transparent to the user. For them, it is practically identical to traditional form-and-session based authentication.
I'm not sure why you want to prevent the user from seeing the routes, but I have coded it as such. I am in debt to Sedushi's Plunker example of how to use AngularUI Router to navigate in a stateful manner without using URLs. Still, I'm not sure I can personally recommend this for any application I would write on my own.
The full solution (both the WebAPI and the WebUI) is available with step-by-step instructions here.
Let me know about any specific part that is unclear, and I will try to make it more clear in the answer.
Refer the following blog for the demo of single page application (SPA) for ASP.NET Web API 2 and AngularJS, developed by the team at Marlabs.
http://weblogs.asp.net/shijuvarghese/archive/2014/01/25/demo-spa-app-for-asp-net-web-api-2-and-angularjs.aspx
The app is built with following technologies:
ASP.NET Web API 2
EF 6 Code First
AutoMapper
Autofac
Semantic UI
AngularJS 1.1.5
The application is published on github at https://github.com/MarlabsInc/webapi-angularjs-spa.
#DavidAntaramian gave a great example. But if you want a simple one, you can look to this HOL from Microsoft.
Their latest example on github uses .NET Core, but you can download release from October 2015.

AngularJS and Firebase Authentication

I would like to add an authentication mechanism to my AngularJS app with Firebase backend. The requirements are simple:
Authenticated users should be able to access any page.
If unauthenticated users goes to /some_page (any page except /login), they should be redirected to /login. Once they enter the right credentials, they should be redirected to back to /other_page.
Possible solution that is described here makes the following assumption:
My solution assumes the following server side behaviour: for every
/resources/* call, if user is not authorized, response a 401 status
But, I'm not sure if it is possible to enforce this behavior when using Firebase as a backend.
Any help and/or examples to implement such AngularJS+Firebase integration will be appreciated!
One solution is to do your routing on the client side with the $route service.
When a user authenticates through Firebase, save some record of this on the client, like in localstorage, some all-encompassing controller, or your own Angular service (my preferred option).
In your routing controller, if the user is authenticated, redirect to /some_page, otherwise redirect to /login and keep track of the $location where the user intended to go.
If, on the other hand, you want to route with your server, you could use the solution you linked to by having your server generate Firebase auth tokens.
I had the same requirement recently and came across this blog post.
http://www.42id.com/articles/firebase-authentication-and-angular-js/
It explains setting up an Angular JS application that interacts with Firebase. Also included are ways to authenticate against OAuth providers such as Google+ and Github using Firebase API, routing based on authentication status, storing user profile information on Firebase and setting up security rules on Firebase to protect user data.
If you are using Firebase Simple Login (rather than generating the authentication tokens on your own servers), you can see how to detect your login state client-side here:
Displaying text after login

Resources