Thursday, June 8, 2017

Angular2 session management local storage | Create local session storage | Using localstorage | Angular Session handling with SpringBoot REST API

Angular2 JS session management | Create local session storage | Using localstorage | Angular Session handling with SpringBoot REST API ... thumbnail 1 summary

Angular2 JS session management | Create local session storage | Using localstorage | Angular Session handling with SpringBoot REST API


Through Angular2 login page , REST API returns the unique token if the credentials are validated. We can send this token to all REST API call. We need to store this token in database with encrypted format.
From now on, your AngularJS app will use this token to authenticate to all REST Api exposed.
Temporarily store the token in localStorage ; basically, when the server verifies the credentials, it sends back a new auth-token Ex. </>
app-token : FERTHDFG54GDGDG7KTYRTYRTYRTY
Successive requests will presents the custom header with this value, without the need to manage it and store it with javascript; at every request, server invalidates the token and generates a new one and sends it back to the client --> prevent replay-attacks with a single token.

When the client receives an HTTP status 401 unauthorized response from any REST Api, the angular controller clean all localStorage and redirect the user to the login page.

The server may send HTTP status 401 unauthorized response when the server has not received the app-token for some time (ex 30 minutes). Lets create few sample codes,

1.Creating session.update.service.ts

This will contains methods to set the auth-token.


import {Injectable} from '@angular/core';
import { Http, Headers, RequestOptions, URLSearchParams , Response } from '@angular/http';

@Injectable()
export class SessionUpdateService {
    setSessionUser(data) {
        localStorage.setItem('user',data.user);
    }
    updateAppTocken(header:Headers) {
        localStorage.setItem('app-awt-token', header.get('app-awt-token'));
    }
}

2.Creating session.service.ts

This will contains methods to get the auth-token, authorized user details. We need to inject this component as globally in our case it will be in AppComponent.

import {Injectable} from '@angular/core';
import { Http, Headers, RequestOptions, URLSearchParams, Response } from '@angular/http';

@Injectable()
export class SessionService {
  private _status:boolean;
  private _sessionUser:any;
  private _sessionId:string;
  private _apptoken:string;

  constructor () {
    console.log("New Session Service");
  }

getSessionUser() {
         //ToDo :: call REST service to get user
        return this._sessionUser;
}
getCurrentSessionId() {
     //ToDo actual logic
    return this._sessionId;
}
  isLoggedIn() {
      let currentUser = localStorage.getItem('authUser');
      let user = JSON.parse(currentUser);
      let authLogin = localStorage.setItem('authLogin', user.login);
      if (authLogin !== null ) {
        this._status = true;
    }
    return this._status;
  }

  logOut() {
    //ToDo :: call REST service
    this._status = !this._status;
  }
  getAppTocken() {
        this._apptoken = localStorage.getItem('app-awt-token');
        return this._apptoken;
    }


}


3.Creating login.service.ts

This will call our actual REST API to get the auth-token.

import { SessionUpdateService } from '../../../_services/session.update.service';
import { SessionService } from '../../../_services/session.service';
....
....
@Injectable()
export class LoginService {
    constructor(private http: Http , private sessionService:SessionService,  private sessionUpdateService:SessionUpdateService ) { }
token:string;
login(email:string, password:string) {
    let params: URLSearchParams = new URLSearchParams();
    params.set('login', email); 
    params.set('password', password);
    let requestOptions = new RequestOptions({
                        headers: this.sessionService.jsonHeaders(),
                        method: 'POST'
                    });
    this.token = this.sessionService.getAppTocken();
    requestOptions.search = params;
    return this.http.get('store/login', requestOptions)
            .map((response: Response) => {
                console.log('response ::' + response);
                this.sessionUpdateService.updateAppTocken(response.headers);
                // login successful if there's a jwt token in the respons
            });
    // return true;
}
}



4.Creating AppComponent.ts

Add these services to main app component.

import {Component, OnInit} from "@angular/core";
import {SessionService} from './_services/session.service';

@Component({
    selector: "app",
    templateUrl: "./app/app.html",
    providers:[ SessionService ]
})
export class AppComponent implements OnInit {
    ngOnInit() {
        console.log("Application component initialized ...");
    }
    constructor( sessionService: SessionService) {}
}

Services will look this.

@RequestMapping("/estore/login")
 @ResponseBody
 public User login(String login,String password,HttpServletResponse response) {
 
 
 response.addHeader("app-awt-token", RequestContextHolder.currentRequestAttributes().getSessionId()+ "-" +EStoreUtils.genRandomToken());
 
 User user = null;
 try {
  System.out.println("login" + login);
 
  user = userDao.findByEmail(login);
  }
   return user;
 } catch (Exception ex) {
  ex.printStackTrace();
 }
 return null;

}

Hope this helps


6 comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. I am interested in such topics so I will address page where it is cool described. session replay

    ReplyDelete
  3. This is exciting, nevertheless it is vital for you to visit this specific url: https://www.pageview.com/

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!! Produits écologiques

    ReplyDelete