This article provides a brief overview of the secure authentication method for Angular-based web applications using Open Authorization and OpenID connect.
OpenID and OAuth are both HTTP-based protocols that are used for authentication and authorization respectively.
Introduction
In a normal or commonly used authentication mechanism, the client receives an access token (a string denoting a specific scope, lifetime, and other access attributes) upon giving their login details. The client uses the access token to access the protected resources hosted by the resource server.
You most probably have encountered scenarios where you are asked to allow access to your personal data or contact information while logging into some site using your social profile like Facebook or Gmail. Then you probably have used OAuth.
Let’s start by clearing a misconception among the terms Authentication & Authorization as these are the underlying concepts behind the above two techniques.
What is Authentication & Authorization?
Authentication – It is the process of verifying identity. Suppose we have a username and password, let’s say a Bus ticket booking site. We enter those credentials and they are validated against and if such username exists and with the entered password, we are allowed to log in.
Authorization – This is the process of giving permission to users for accessing certain protected resources. Let’s say we want to access the bus timing to a route after logging in to the site. This information is intended to be shown only to logged-in users. So a logged-in user is granted access to view this information which resides on the server using the access token.
Again let’s see what OAuth and OpenID are.
What is OAuth?
OAuth 2.0 stands for Open Authorization. It is a standard designed to allow a website or application to access resources hosted by other web apps on behalf of a user. It replaced OAuth 1.0 in 2012 and is now the standard for online authorization.
Roles in OAuth 2.0 –
1. Resource owner – An entity capable of granting access to a protected resource.
2. Client – An application making requests to protected resources, Client can be the application and it may reside on any server, desktop, or other devices.
3. Authorization server – The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.
4. Resource server – The server hosting the protected resources, is capable of accepting and responding to protected resource requests using access tokens.
How does the whole concept work?
Below given a diagrammatic representation of how the secure authentication works –
1. The client requests authorization from the resource owner.
2. As part of the request, the client receives an authorization grant which is a credential representing the resource owner’s authorization.
3. The client in turn communicates with the Authorization server with the Authorization grant and receives an access token in return.
4. The client then uses this access token to access protected data residing on the server. The resource server validates this request and checks the access token validity and serves the request.
Below given a more detailed representation of the above-mentioned protocol.
While the client communicates with the Authorization server with an authorization grant, the client in turn receives an access token & refresh token.
The refresh token can be used when some token error occurs and a new access token is obtained.
The authorization server code part is configured from the backend side. We do have some configurations and code to be written from the front-end side.
Let’s go through an example that uses Google Authentication to authenticate users. Here we make use of google accounts to authenticate the user and get an access token.
Before we can begin, we’ll need to create an application in the Google API Console in order to get a client ID and client secret and register the redirect URL.
Steps for setting up a project
1. Visit https://console.developers.google.com/ and create a new project. Give the project name and other details and click Create.
2. Go to credentials screen and click on “CREATE CREDENTIALS” => “OAuth client ID”.
3. Next, we’ll have to configure the consent screen. This is the screen that shows whether to allow the application to access users’ information from a google account. You may have seen this type of screen while logging in to some applications.
4. This step consists of a series of inputs by the user. Give the user type “External” and click Create.
5. In the next screen, the “OAuth consent screen” provides the necessary details and goes to the next step.
6. In the next step, “Scopes”, provide the required information regarding which data the application intends to access. The scope denotes the permissions you request users to authorize for your app and allow your project to access specific types of private user data from their Google Account.
7. The next step is “Test Users”, where we can specify which all users can be allowed to access while in the test phase.
8. Next is a summary page, showing the details as of now.
9. Again go to step 2 and “Create OAuth client ID”.
10. Give details such as redirect URI, Application type, name etc. and click “Create”, you will get a popup like the one below.
This client id & client secret can be used for secure authentication with google using a google account.
Implementation in Angular application
We can use an npm package called “angular-oauth2-oidc” OAuth 2 and OpenId Connect (OIDC) in Angular.
More details and sample snippets can be found in the npm package link, https://www.npmjs.com/package/angular-oauth2-oidc
First of all, create a service file that holds all the methods related to secure authentication.
const authConfig: AuthConfig = { // Url of the Identity Provider issuer: "ssoDetails.issuer", // URL of the SPA to redirect the user to after login // redirectUri: window.location.origin + '/index.html', redirectUri: window.location.origin, // The SPA's id. The SPA is registered with this id at the auth-server clientId: "ssoDetails.clientId", responseType: "code", disableAtHashCheck: true, scope: "openid email", strictDiscoveryDocumentValidation: false, showDebugInformation: true, };
This is the main configuration for secure authentication, here “issuer” is URL of the identity provider, in our case “https://accounts.google.com”
Client ID is the one obtained from earlier steps.
public loginFlowStart(): void { this.oauthService.initCodeFlow(); }
While clicking on google authentication, we invoke a method from the npm library. You can place this method inside the service file.
This will in turn start the secure authentication procedure.
Add the following methods. Invoke them in the constructor. initializeSecureOauth() & redirectOnSuccess()
What this method does is that it uses the library and calls certain methods. “configure(authConfig)” method for configuring using the params defined earlier like the client id, redirect Url e.t.c
This will take the user to the google authentication page and once he/she provides a valid login detail, the flow will be redirected back to the redirect URI with the access token.
The events observable is subscribed to check for whether the valid access token is issued and if so a true value is emitted.
We subscribe to this observable and set the token accordingly.
public redirectOnSuccess(): void { this.isAuthenticatedSubject$.subscribe((res) => { if (res && !localStorage.getItem("user")) { const access_token = sessionStorage.getItem("access_token"); localStorage.setItem("user", access_token); this.router.navigateByUrl("app"); } }); } public initializeSecureOauth(): void { this.oauthService.configure(authConfig); this.oauthService.events.subscribe((_) => { if (this.oauthService.hasValidAccessToken()) { this.isAuthenticatedSubject$.next(true); } else { this.isAuthenticatedSubject$.next(false); } }); try { this.oauthService.setupAutomaticSilentRefresh(); } catch (error) { console.log(error) } }
Conclusion
Security concerns should remain paramount whenever implemented in an application. I hope you got an idea of how OAuth works and why it is necessary. Now, it’s time for you to try implementing it in your application and understand how everything works.
For a much detailed reference regarding this protocol check out this documentation – https://www.rfc-editor.org/rfc/rfc6749
Are you looking forward to a hire a professional tech partner?
If yes, then contact us. Perfomatix is one of the top software product development and offshore development company.
To know how we helped our clients from diverse industries, then check out our success stories section.