Vinu
Vinu

Reputation: 139

How to handle User Session in angular 5

For the backend, I am using Spring Framework with 'Shiro' for authentication,

And for the frontend, I am using Angular 5.

If I am calling my login API from postman than I am getting same user session until I use logout API. (Which is correct)

Postman UI image: enter image description here

But when I am calling my login API from my angular 5 than I am getting different user session on every call. (Which is wrong.)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class LoginService {
  private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
  private _url:string = "v1/login";

  constructor(private http: HttpClient) { }

  login(){
    const data = {userName:"root", password:"root"};
    return this.http.post(this._url,{headers: this.headers},{params : data})
    .subscribe(data => {sessionStorage.setItem("jsessionid",JSON.parse(JSON.stringify(data)).jsessionid)});
  }
}

Angular UI image: enter image description here

On each call 'jsessionid' is changing as shown in ''

Upvotes: 10

Views: 31764

Answers (3)

user2419999
user2419999

Reputation: 11

Having the proxy has nothing to do with your issue... at least not what you described

Just add

this.http.{{requestverb}}({{endpoint}}, {withCredentials: true})

eg

this.http.get("/posts",{withCredentials:true});

Upvotes: 1

Vinu
Vinu

Reputation: 139

Session management will happen automatically.

If we have client on one server and backend on another server at that time we just need to add 'proxy.conf.json' file. And need to add that file entry in 'package.json' file.

Important:- Add server url upto the port number in 'proxy.conf.json'. (Server url entry till port number)

{
    "/": {
      "target": "https://localhost:30443",
      "secure": false
    }
 }

In my case, I was using one extra parameter /mainlayer in server URL. (Which was wrong.)

{
   "/": {
     "target": "https://localhost:30443/mainlayer",
     "secure": false
   }
}

And in LoginService class just add that extra parameter.

private _url:string = "mainlayer/v1/login";

Upvotes: 3

Kliment Ru
Kliment Ru

Reputation: 2137

You need to check "jsessionid" in session storage before sending auth reques.

login(){
 const data = {userName:"root", password:"root"};
 if(this.isLoggedIn()){
  return Observable.of(JSON.parse(sessionStorage.getItem('jsessionid')))
 }

 return this.http.post(this._url,{headers: this.headers},{params : data});
}

private isLoggedIn(): boolean {
 const result = !!(sessionStorage.getItem('jsessionid'));
 return result;
}

Also you need to create auth interceptor https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

Upvotes: 3

Related Questions