Access AngularJs application via link from email - angularjs

I need some suggestions from people who maybe had an experience with similar types of applications.
I am building and app that should be use for on line testing. For example if you want a job in some company, HR can create test session for you, and send you a link to an app.
That email will contain a link.
On link click I want to hit my angularjs app. AngularJs will get session id from the link it should make a request to server.
Server then needs to check db and try to find a test session with that Id, and return some response. (session data if it's ok or some message that session is expired, etc.)
The problem here is usage of JWT tokens. For example, when HR uses part of app, it has to be authenticated, which is done by jwt tokens.
What is the best practice when you have users on the other side? Like people who will take the test. They do not have jwt token, but server will expect something for authentication.
Should user get some custom token that will expired when test session expires, then maybe I can decode that token on angular side and check user role or something like that.
Did anybody had experience with building an app that can be access over a link?

Here is a possible scenario
HR connect to the app and generate a new test session
Create a new test session in the database with all the necessary info + add 2 columns : Token + Token_Expiration. The Token will be a random string and the Token_Expiration is now + x hours
Send link with token to the user by email. e.g : http://myapp.com/?token=ahdk5d5ek4945gol
User click on the link that redirects him to the landing page.
Retrieve the token from the url and send it to the server
Server must check if this token exists inside the database
If the token does not exist - Forbidden access
If the token exists - Check if the current time does not exceed the Token_Expiration
User finish the test
Server must remove the Tokenor use a third column Valid and set it to false

Send custom token with link and based on that authenticate user
then find session id for that custom token and return response
and invalidate custom token after completion of test.

Related

IdentityServer4: How to set a role for Google user?

I have 3 applications:
An IdentityServer4 API which provides Google authentication and also provides an access token to authorize the resource API.
A simple Resource API which provides some data from DB.
A simple Client in React which have 4 buttons:
Login, for Google auth
Logout
Get data - a simple request with the access token to the Resource API and gets the data from Db
Get user data - returns user profile and token (for debug purpose)
I didn't put any sample code because my problem is not code related, it's knowledge that I'm missing and I ask for guidance.
The workflow is working just fine: the user press the Login button, it is redirected to IdentityServer4 API for Google Auth. From there it is redirected to a Callback Page from the Client and from there to the Index page. I receive the user data and the token, I can request data from the Resource API and it's working.
My problem is: How do I give a Role to the Google Users ?
I don't have users saved in DB. I want three types of Users: SuperAdmin, Admin, Viewer and each of these roles have limited Endpoints which can access.
For limiting their access I saw that I can use Claims-based authorization or Role-based authorization.
So, my question is how ca I give a Google User who wants to login in my app, a specific Claim/Role ? What is the workflow ? I must save it first in DB ? Or there exists a service from Google where I can add an email address and select a Role for that address ?
Thank you very much !
After you get the response from Google in your callback you can handle the user and do what ever you want to do with it. Below are the some typical tasks that you can do in callback that I took from documentation page of identityserver4 link:
Handling the callback and signing in the user
On the callback page your typical tasks are:
inspect the identity returned by the external provider.
make a decision how you want to deal with that user. This might be
different based on the fact if this is a new user or a returning
user.
new users might need additional steps and UI before they are allowed
in.
probably create a new internal user account that is linked to the
external provider.
store the external claims that you want to keep.
delete the temporary cookie
sign-in the user
What I would do is creating an new internal user account that is linked to the external provider and add a role to that user.
If you don't want to save users in db, you can add an extra claim to user in callback method and use that claim in token. and i think this link will help with that.

Check authorization token in ReactJS against a Rest API

I am currently trying to design a new web-application for a rest-api service I have running. In basic I am trying to realize the login/logoff system. For authorization-management the API provides three endpoints:
/login, which takes username and password via a POST request and returns a token embedded in a json answer. This token is not a JWT, but its some arbitrary unique string. It is valid for X hours and everytime it used it is reset to be X hours valid again. The validity is check on the server in each request.
/logout, which makes the token invalid on the server.
/validate, which takes a token as json in POST request and checks if it is valid. If not it returns a 401.
Now I realized a login procedure following https://www.digitalocean.com/community/tutorials/how-to-add-login-authentication-to-react-applications . The application finally should used the react-router to provide the different pages. My problem is not how to integrate the validation of the token on each page change and if a 401 is returned, switch to the login page again.
PS: The server is written in C++ and accesses a custom database.
As Suggested By You That You Want To Integrate Validation, So You Need To Create A Component Over The Current Route Component.
It would serve as the private Route and as soon as you get a 401 Response From Your Server You Would Redirect To The Login Page By Updating the Token as empty depenedending upon the storage you are using i.e. session storage or localstorage.
This way whenever your token expires the next request responds with 401 and you are logged out.
Further I am Linking An Example Gist For Creating Private Routes And Logging Out
https://gist.github.com/EduVencovsky/f8f6c275f42f7352571c92a59309e31d

How to interact with back-end after successful auth with OAuth on front-end?

I want to build small application. There will be some users. I don't want to make my own user system. I want to integrate my application with oauth/oauth2.0.
There is no problem in integration of my front-end application and oauth 2.0. There are so many helpful articles, how to do this, even on stackoverflow.com. For example this post is very helpful.
But. What should I do after successful authorization on front-end? Of course, I can just have flag on client, which says "okay, mate, user is authenticated", but how I should interact with my backend now? I can not just make some requests. Back-end - some application, which provides API functions. EVERYONE can access this api.
So, I need some auth system anyway between my FE and BE. How this system should work?
ps I have some problems with English and may be I can not just correctly 'ask google' about it. Can you provide correct question, please :) or at least give some articles about my question.
UPD
I am looking for concept. I don't want to find some solution for my current problem. I don't think it is matters which FE and BE I use (anyway I will
provide information about it below)
FE and BE will use JSON for communication. FE will make requests, BE will send JSON responses. My application will have this structure (probably):
Frontend - probably AngularJS
Backend - probably Laravel (laravel will implement logic, also there is database in structure)
Maybe "service provider" like google.com, vk.com, twitter.com etc remembers state of user? And after successful auth on FE, I can just ask about user state from BE?
We have 3 main security concerns when creating an API.
Authentication: An identify provider like Google is only a partial solution. Because you don't want to prompt the user to login / confirm their identity for each API request, you must implement authentication for subsequent requests yourself. You must store, accessible to backend:
A user's ID. (taken from the identity provider, for example: email)
A user token. (A temporary token that you generate, and can verify from the API code)
Authorization: Your backend must implement rules based on the user ID (that's your own business).
Transport security: HTTPS and expiring cookies are secure and not replayable by others. (HTTPS is encrypting traffic, so defeats man-in-the-middle attacks, and expiring cookies defeats replay attacks later in time)
So your API / backend has a lookup table of emails to random strings. Now, you don't have to expose the user's ID. The token is meaningless and temporary.
Here's how the flow works, in this system:
User-Agent IdentityProvider (Google/Twitter) Front-End Back-End
|-----------------"https://your.app.com"---------->|
|---cookies-->|
your backend knows the user or not.
if backend recognizes cookie,
user is authenticated and can use your API
ELSE:
if the user is unknown:
|<--"unknown"-|
|<----"your/login.js"----------+
"Do you Authorize this app?"
|<------------------+
|--------"yes"----->|
+----------auth token--------->|
|<---------/your/moreinfo.js---|
|-------access_token ---------->|
1. verify access token
2. save new user info, or update existing user
3. generate expiring, random string as your own API token
+----------->|
|<-------------- set cookie: your API token --------------------|
NOW, the user can directly use your API:
|--------------- some API request, with cookie ---------------->|
|<-------------- some reply, depends on your logic, rules ------|
EDIT
Based on discussion - adding that the backend can authenticate a user by verifying the access token with the identity provider:
For example, Google exposes this endpoint to check a token XYZ123:
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123
I read through all the answers very carefully, and more than half the people who responded are missing the question completely. OP is asking for the INITIAL connection between FE & BE, after the OAuth token has been issued by the Service Provider.
How does your backend know that the OAuth token is valid? Well keep in mind that your BE can send a request to the Service Provider & confirm the validity of the OAuth token, which was first received by your FE. This OAuth key can be decrypted by the Service Provider only because only they have the secret key. Once they decrypt the key, they usually will respond with information such as username, email and such.
In summary:
Your FE receives OAuth token from Service Provider after user gives authorization. FE passes OAuth token to BE. BE sends OAuth token to Service Provider to validate the OAuth token. Service Provider responds to BE with username/email information. You can then use the username/email to create an account.
Then after your BE creates the account, your BE should generate its own implementation of an OAuth token. Then you send your FE this OAuth token, and on every request, your FE would send this token in the header to your BE. Since only your BE has the secret key to validate this token, your application will be very safe. You could even refresh your BE's OAuth token on every request, giving your FE a new key each time. In case someone steals the OAuth token from your FE, that token would be quickly invalidated, since your BE would have already created a new OAuth token for your FE.
There's more info on how your BE can validate the OAuth token. How to validate an OAuth 2.0 access token for a resource server?
let's use OAuth concept to begin,FE here is Client , BE here is Resource Server.
Since your client already authorized, Authorization server should grant
Access token to the client.
Client make request to the resource server with the Access token
Resource server validate the Access token, if valid, handle the request.
You may ask, what is the Access token, Access token was issued by authorization server, grant to client, and recognized by resource server.
Access token is a string indicate the authorization information(e.g. user info, permission scope, expires time...).
Access token may encrypted for security, and you should make sure resource server can decrypt it.
for more details, please read OAuth2.0 specification https://www.rfc-editor.org/rfc/rfc6749.
Well you don'y need User-System on your Front End side.
The front end is just a way to interact with your server and ask for token by valid user and password.
Your server supposed to manage users and the permissions.
User login scenario
User asking for token by entering his username and password.
The server-API accept the request because it's anonymous method (everyone can call this method without care if he's logged in or not.
The server check the DB (Or some storage) and compare the user details to the details he has.
In case that the details matches, the server will return token to the user.
From now, the user should set this token with any request so the server will recognize the user.
The token actually hold the user roles, timestamp, etc...
When the user request for data by API, it fetch the user token from the header, and check if the user is allowed to access that method.
That's how it works in generally.
I based on .NET in my answer. But the most of the BE libaries works like that.
As am doing a project for SSO and based on my understanding to your question, I can suggest that you create an end-point in your back-end to generate sessions, once the client -frontend- has successfully been authorized by the account owner, and got the user information from the provider, you post that information to the back-end endpoint, the back-end endpoint generates a session and stores that information, and send back the session ID -frequently named jSessionId- with a cookie back to the client -frontend- so the browser can save it for you and every request after that to the back-end considered an authenticated user.
to logout, simply create another endpoint in the back-end to accepts a session ID so the back-end can remove it.
I hope this be helpful for you.
You need to store the token in the state of your app and then pass it to the backend with each request. Passing to backend can be done in headers, cookies or as params - depends on how backend is implemented.
Follow the code to see a good example of all the pieces in action (not my code)
This example sets the Authorization: Bearer TOKEN header
https://github.com/cornflourblue/angular-registration-login-example

Google OAuth2 flow and id_token refresh

I am having troubles in implementing OAuth in the right way.
I use a client/API architecture (Angular for front and Node.js for back) and I would like user to sign in using Google OAuth authentication only.
Here is what I think is the right way for the moment (tell me if I misunderstood something) :
Angular open a Google popup asking user's consent.
Once the user agree, Google Authorization server sends back to angular a verification code.
This verification code is forwarded to an API endpoint.
Then, the API asks Google Authorization server to exchange this code for an access_token, an id_token and a refresh_token.
Google sends those 3 tokens.
The API uses access_token to retrieve user from Google API
The API persists the user
Here is the little dillema, in my opinion, the access_token and refresh_token should be stored into the database and the id_token should be sent back to Angular client.
This way, it would allow the API to ask for resource in Google API and if the token expires it can still ask for a new token thanks to the refresh_token.
Client-side, the id_token is embedded in all requests thus allowing the API to identify the client and verify his authentication with Google certs from https://www.googleapis.com/oauth2/v3/certs.
Supposing this is right way to use tokens, how could I deal with id_token expiration since client does not have any refresh token ?
Thanks !
I do it slightly different (I have the same basic architecture though).
Angular decides the user needs to log in and displays a login popup.
The url in the login popup is not serviced by angular, but is instead directly run off of the backend server: /auth/google . (I use hapijs and bell, personally).
/auth/google is serviced by a bell plugin and initiates the OAUTH dance.
the end of the OAUTH dance results in my node server generating a local token (I just generate random bytes and store them in redis mapped to user ids)
because the initial login popup was created by window.open, the success page (generated on the api side rather than in angular) can use window.opener.postMessage to communicate the token back to the angular runtime.
This way, all my sensitive google credentials (the user's oauth token, refresh token if needed, and my application's api ID and secret) are only on the server, except for during the OAUTH dance relay when they're in a URL string during the client redirects. This is reasonably secure.
Then for all the actual user interactions with the api, I use the token I generated in step four to authenticate. This could be a JWT if you wanted, but I don't do it that way; I just use redis to map from 'longrandostring' -> userId. That lets me (for example) force everyone to re-login if I wipe the redis database that has all the tokens stored, or I can write a lua script to delete all the entries that map to a certain userid.
If you need a refresh token, you can set access_type=offline in the initial request to oauth2/auth, and you'll get a refresh token as part of the response, unless you've previously gotten a refresh token. You can then persist it on the server side and get new access tokens as needed. If you set approval_prompt=force as well, you'll force a new consent screen and be guaranteed a refresh token (but after some small number of refresh tokens granted to a user, older ones expire on the same application so it's best to only request them if really needed).

Angular token and user login scenario

I m building app who uses oauth2.
I me using:
Laravel for backend
Oauth2 for Laravel (lucadegasperi)
Angular for frontend because it will be also and native mobile app:D.
My question is?
What is the workflow for user sign in?
Now i have.
User comes to site and enter username and password
Angular send post for access token and when access token is returned i go for user data. Then I store access_token in localstorage. I m using grant_type=password i forget to mention.
I have 2 hours when token gona expire. In that moment when token expire I go for new token by refresh_token functionality.
My Questions are:
Is this good way/approach?
What is supposed to happen when user close browser?
Now when user close browser and again enter to my app. I will check localstorage and then autheticate user by access_token. If Access Token is expired i will get new one.
What about remeber me option or so called keep me signed in?
Does it mean thant i must set token that will be expired in 365 days (lifetime)?
or create cookie/ localstorage with access token so when user comes newt time i read cookie/loaclastorage and then authorize user?
And finnaly about destroying token. Now my token will be detroyed when i log of from the app.
Thanks
We are building the same kind of service/app using the same components. We use a password flow and I store the token in local storage if the user ticks the "remember me" checkbox on the login form, otherwise I just store the token in an un-persisted variable that gets destroyed when the user refreshes or closes the browser.
See some notes on testing protected endpoints here:Testing OAuth 2.0 protected API endpoints in Laravel
Marijan!
I'm working on simple app containing two separate layers. 1) Rails 5 Json API provider. 2) Separate NodeJS server running Angular 2 application.
Angular 2 app on Login requests access token from google
Angular 2 app retrieves UserInfo from google/people API
Angular 2 app now able to POST json with User's display name and some id from Google Response json.
Angular 2 POSTs json to my Rails 5 API server (partially implemented, but already works with login/pass auth).
So far I have implemented implicit OAuth2 using the code similar to this Gist. Using this code I am able to get User Identification Info which is enough for me to identify the user in API provider or create account for it.
This approach works for me. Hope it will work for you as well.
Note: this approach might be insecure.

Resources