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:
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:
On each call 'jsessionid' is changing as shown in ''
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});
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";
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With