The Token based authentication has received expansion
over last few years due to RESTful Web APIs, SPA and so on. The Token based
authentication is stateless.
Stateless
– every transaction is performed as if it was being done for the very first
time and there is no previously stored information used for the current
transaction.
Token
Based Authentication Steps As -
User enters their login credentials and the server
verifies the entered credentials. Validating to the entered credentials, It’s correct
or not. If the credentials are correct, returns a signed token. This token is
stored local storage in the client side. We can also store in session storage
or cookie.
Example
As –
private
_setSession(authResult,
profile) {
//Save session data and update login status subject
localStorage.setItem('access_token',
authResult.accessToken);
localStorage.setItem('id_token',
authResult.idToken);
localStorage.setItem('userProfile',
JSON.stringify(profile));
this.setLoggedIn(true);
}
Advantages
of Token-Based Authentication -
1. Stateless,
2. Scalable
3. Decoupled
4. JWT
is placed in the browsers local storage
5. Protect
Cross Domain and CORS
6. Store
Data in the JWT
7. Protect
XSS and XSRF Protection
Where
To Store Tokens?
It does depend on you, where you want to store
the JWT. The JWT is placed in your browsers local storage.
Example
- Authentication Service [auth.service.ts]
import
{ Injectable } from
'@angular/core';
import
{ Router } from
'@angular/router';
import
{ BehaviorSubject } from
'rxjs/BehaviorSubject';
import
{ AUTH_CONFIG } from
'./auth0-variables';
import
{ tokenNotExpired } from
'angular2-jwt';
import
{ UserProfile } from
'./profile.model';
// Avoid name not found warnings
declare
var auth0: any;
@Injectable()
export
class AuthService
{
// Create Auth0 web auth instance
// @TODO: Update AUTH_CONFIG and remove .example
extension in src/app/auth/auth0-variables.ts.example
auth0 = new
auth0.WebAuth({
clientID: AUTH_CONFIG.CLIENT_ID,
domain: AUTH_CONFIG.CLIENT_DOMAIN
});
userProfile: UserProfile;
// Create a stream of logged in status to
communicate throughout app
loggedIn: boolean;
loggedIn$ = new
BehaviorSubject<boolean>(this.loggedIn);
constructor(private
router: Router) {
// If authenticated, set local profile property and
update login status subject
if (this.authenticated)
{
this.userProfile
= JSON.parse(localStorage.getItem('profile'));
this.setLoggedIn(true);
}
}
setLoggedIn(value:
boolean) {
// Update login status subject
this.loggedIn$.next(value);
this.loggedIn
= value;
}
login() {
// Auth0 authorize request
// Note: nonce is automatically generated:
https://auth0.com/docs/libraries/auth0js/v8#using-nonce
this.auth0.authorize({
responseType: 'token
id_token',
redirectUri: AUTH_CONFIG.REDIRECT,
audience: AUTH_CONFIG.AUDIENCE,
scope: AUTH_CONFIG.SCOPE
});
}
handleAuth() {
// When Auth0 hash parsed, get profile
this.auth0.parseHash((err,
authResult) => {
if (authResult
&& authResult.accessToken
&& authResult.idToken)
{
window.location.hash
= '';
this._getProfile(authResult);
this.router.navigate(['/']);
} else if
(err) {
this.router.navigate(['/']);
console.error(`Error:
${err.error}`);
}
});
}
private _getProfile(authResult)
{
// Use access token to retrieve user's profile and
set session
this.auth0.client.userInfo(authResult.accessToken,
(err, profile) => {
this._setSession(authResult,
profile);
});
}
private _setSession(authResult,
profile) {
// Save session data and update login status
subject
localStorage.setItem('access_token',
authResult.accessToken);
localStorage.setItem('id_token',
authResult.idToken);
localStorage.setItem('profile',
JSON.stringify(profile));
this.userProfile
= profile;
this.setLoggedIn(true);
}
logout() {
// Remove tokens and profile and update login
status subject
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
this.userProfile
= undefined;
this.setLoggedIn(false);
}
get authenticated()
{
// Check if there's an unexpired access token
return tokenNotExpired('access_token');
}
}
Use
of AuthService in the Component Page –
//Use of AuthService in the Component
Page.
import
{ Component } from
'@angular/core';
import
{ AuthService } from
'./auth/auth.service';
export
class Login
{
constructor(private
authService: AuthService)
{
// Check for authentication and handle, if hash
present.
authService.handleAuth();
}
}
I hope you are
enjoying with this post! Please share with you friends. Thank you!!