How to handle authentication tokens in MEAN stack application - mean-stack

I am a newbie to MEAN stack and developing an end-to-end application using MEAN. I have a small confusion on how to handle authentication tokens on client side (i.e. in Angularjs).
I created an authentication token after either the user signup's or login to the application. I followed this link for creating authentication token. I set the authentication token in response headers and saving it on the browsers localStorage on client side. I accessed it whenever i did a REST call.
Is it a good practice to access tokens directly from the localStorage or i need to access the token by creating either a factory or a service ?. I have seen many SO answers, in which they access the tokens by creating either a factory or a service, but my confusion is if i can able to access the token straight away from localStorage why i need to create a factory or service ? Is there any best practices for it ?

MEAN.IO provide methodology of Test-Driving-Development and has several Karma test cases from the box. For unit testing you should to write factory app.factory('getTokens) and then write test case for it like:
User Logged In -> Ok.
User Not Logged In -> Throw Error.
But If you, for some reason, does not support TDD - you shouldn't.

Related

Elixir Phoenix Absinthe GraphQL API authentication in both web and mobile app's

I'm working on an Absinthe GraphQL API for my app. I'm still learning the procedure(so please go easy on me).
I've a Absinthe/GraphQL MyAppWeb.schema.ex file in which I use for my queries and mutations. My question is how do I use this API for authenticating the user on both Mobile and Web app?
How do set a cookie(httpOnly & secure) in my web app and access/refresh tokens in a single Absinthe API to serve my website and mobile app. Basically what I'm trying to learn is how do I authenticate the user based on specific platform.
If my question sounds bit confusing, I would be happy to provide more information related to my question. I would really be grateful if someone could explain the procedure, I've been very stuck on this for a while.
I would avoid using authentication mechanisms provided by absinthe(if there are any). Depending on what front-end you are using, I would go with JSON API authentication. The flow on server goes the following way:
Create a endpoint for login that will receive a user and password and will return a refresh token.
Create a endpoint for exchanging refresh token for access token.
Use a library like guardian to generate your refresh/access tokens.
Create a phoenix plug for authentication that will check your tokens, guardian has some built-in plugs for this.
Now on device you have to implement:
Ability to save refresh and access token on device.
Have a global handler for injecting access token on authorized requests.
Have a global handler for case when access token is expired. (you usually check if your request returns Unauthorized, then you should request a new access token from the server using your refresh token)
This seems like a crude implementation, however I would advise in implementing your system instead of using a black box library that you have no idea how it works under the hood.

How to access a secured API in the frontend?

There is a lot of good content on the internet that explains how to secure a Spring API with Keycloak: Create a Client that represents the API Service in Keycloak and use a link like the one below to get the access and refresh token:
<Domain>/auth/realms/<realm>/protocol/openid-connect/auth/{some parameters}
This yields both tokens. So far so good.
Now, however, I am not sure how the flow for the frontend accessing the API should look like.
Should the frontend directly access this endpoint and, therefore, obtain the access and refresh token? That would mean that the API can only have the access-type public because there is no way to store the client (the API) secret securely.
Or should there be a third server that somehow stores the refresh token for each user, that the user can call if his access token is no longer valid. This server would then use the client's refresh token (and the client secret that could be stored securely, since it would be in the backend) to get a new access token from Keycloak and would forward it to the user.
I guess the main question that I am asking is, whether the client/user should get the refresh token.
If one needs to implement a logic according to the second option, I would be interested in a link or description of how something like this can be done in Spring.
I think, in either case you need to use the Authorization Code Flow. The implicit flow, which was recommended for SPAs (frontends without a backend server) in former versions of OAuth2 must not be used anymore.
The best option is to have a backend server, so the user retrieves the auth code via redirection and the backend server exchanges this auth code with the access and refresh tokens (and keep them without forwarding them to the frontend).
If there is no backend in place and your frontend needs to retrieve and hold the tokens directly, I would recommend to use the Authorization Code Flow with a public client and the PKCE extension (which - put simply - ensures that the entity asking for the auth code is the same as the entity asking for the tokens and that the auth code was not stolen and used by a foreign entity). There are several sources with more detailed explanations, which might help you, for example: https://auth0.com/docs/flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce
Hope this helps you with your architectural considerations.

spring oauth 2 authorization server app share same security context with another app

I have two authorization server application ( spring boot 2.0.5 ).
The two authorization server application are similaire
When a user ask for a token, spring will register a session for that specific user and give back a token, with that token you can access to the resource of application 1 but you can't access to the resource of application 2.
My question is if there is a way to share the same security context in addion when you generate token from application 1 you can use to access of application 2 resource
What you can do is to make your applications stateless when it comes to security.
What does it mean?
Spring Security will no longer generate a session for a new logged in user. When the user logs in, you will issue him a token (e.g. JWT). Each time when the user accesses secured content, he/she will have to provide a token and your applications will verify that token with a public or private key (depending on which type of token encryption you will use - symmetric or asymmetric). In the end, you will not need to share anything, if both of your applications have same keys to verify incoming tokens.
Some tips:
A token you send upon each request to access secured resources is called "access token". Make it expirable and make it short lived (like 15 mins). Why? This token cannot be immediately invalidated unlike session which can be simply deleted. In case if someone hijacks it, it will be still able to access secured resources.
Since your "access token" is short lived, it would be annoying for a user to logs in every 15 minutes. To prolong its life, you can have another type of token called "refresh token" that can be stored in some database. This token can be immediately invalidated by simply deleting it from the database. Therefore, if someone even hijacks it, user will be able to revoke it and the hijacker will not be able to prolong his session.
References: Stateless authentication with JWT
We are also facing similar problem.
For web pages we are using SSO which cache token in clientContext and using Authorization-server-1
For making call to API-1 we are using token generated by Authorization-server-2. In this case we have create another session bean for clientContext and that is caching token (having its own oauth2RestTemplate and clientCredientialResource)
This is two legged scenario
We doing research, how to use three legged scenario for calling web/rest service, but we were not able to do so, as access token retrieval is two step process (using authorization code) and call back will execute the whole method again and not continue from line after call to rest api

IdentityServer4 how to store and renew tokens in authorization code flow

I am looking for the best approach to work with the IdentityServer4 autorization code flow.
My apps system is quite ordinary: I have an MVC client, a WebAPI and the IS. I also use AJAX to request the API from the client side. So I need the access token on the client side to put it into the authorization header.
Is it good idea to store access token in the cookies?
Do I need self-contained or reference token (it is about security, I suppose)?
What is the best approach to renew when it was expired?
I thought about the two strategies:
Update access token when the first 401 status code was recieved. Can be the problem cause I send more than 1 query to the API and I need to synchronized them and recall the first one (to get result);
Every time before API calling call the MVC client method with GetTokenAsync, check the expire time and get or update and get access token. Seems cheating, cause I need to call the MVC client every time when I want to call the API.
Could you help me to find the best way?
"Is it good idea to store access token in the cookies?"
No, not with the authorization code flow. If you are using an MVC web application you should find a way to store tokens in some kind of datastore away from the browser. All the MVC application should administer is a cookie to access future MVC endpoints (that will make subsequent calls to Identity Server with the appropriate access token in the datastore).
"Do I need self-contained or reference token (it is about security, I suppose)?"
That's all up to you and what you think is best for your use cases. If you'd like to see the information in the access token and skip the extra backend call for validation then use reference tokens. Strategy 2 requires you to use self-contained tokens so that you can check the expiry.
"Could you help me to find the best way?
I don't know if I can give the "best" way, but I'd probably go with strategy 2 and use self-contained tokens.
EDIT: If you wanted to use "axios , to get data from the API" then I would suggest using the implicit flow which has no concept of a refresh token. In this case, leaving it in the cookie should be OK.

How to achieve long lived login session with Oauth2 and javascript client(Spring Oauth2 + Angularjs)

I've a spring backend with Spring OAuth2 and Angular client.
What is the proper way to achieve long lived logins which is still arguably secure.
I guess I can use password flow and refresh tokens, but this doesn't seem any safer than using long lived access tokens with implicit flow for browser clients. I think I can use:
Redirects - which will interfere with whatever user was doing
Popups - which will get blocked without user interaction
on the client level. But is there any better approach?
P.S: Cloudfoundry's new UI seems to have achieved exactly what I want.
The auth code flow is always superior (more secure and less chance of leaking user cerdentials). If you are writing a browser-hosted client contacting the OAuth2 service directly then unfortunately you won't be able to get hold of the access token from the auth code flow. For that reason I think I would prefer to use access tokens between machine (non-browser) clients, and standard cookie-based authentication between the browser and the front end server. You can still use OAuth2 on the front end server to do the authentication (I'm pretty sure that's what the CloudFoundry server is doing) if you expose a /me or /user_info type endpoint.
Or if you really need to get the access token in your client (I guess there are libraries for dealing with it), you can use password or implicit grant. Implicit is strongly preferred on security grounds (since the user only types his password into the auth server authentication UI), but in both cases you need to take care to segregate your client data so the (unauthenticated) clients don't get access to anything they shouldn't.
Solution to me was to use hidden iframes with implicit grant.

Resources