1

I'm developing an angular 7 web app with spring back-end, I implemented security, so spring when you login with the right credentials gives a JSESSIONID cookie. If I try to login with postman I recive the cookie and everything works fine, but in angular it seems it doesn't receive the cookie even if the server responds with 200.

My login.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class LoginService {
    private apiURL = 'http://127.0.0.1:8080';

    constructor(
        private http: HttpClient
    ) { }

    login(credentials) {
        let params = new HttpParams()
            .set('username', credentials['username'])
            .set('password', credentials['password'])

        return this.http.post<any>(`${this.apiURL}/login`, credentials, {
            'headers': {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            'params': params
        })
    }
}

My login method in login.component.ts:

login(){
    this.loginService.login(this.credentials).subscribe((res) => {
      console.log(res)
    })
  }

I'm expecting that the web app stores the cookie and send it in every request so the back-end can check if you are actually loggedin

New contributor
AFlawlessGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
0

You can send data in the router which is what I would look for. But in my main project the JWT info is stored in localStorage:

public saveToken(token: string): void {
    window.localStorage.setItem('jwtToken', token);
}

I'm curious if there is a better "Angular" way.

I read through this: Netbasal's article with you're question in mind but am not sure if it's a solution or just cool.

  • I didn't find nothing useful, thanks anyway – AFlawlessGuy Jun 13 at 12:13
0

In Angular way, you can use typescript with an interface name Storage. In the login service you can @Inject the storage and use it for example:

const LOCAL_STORAGES = new InjectionToken<string>('user-session-local-storage');

@Injectable()
export class UserSessions {

    constructor(
        @Inject(LOCAL_STORAGES) private localStorage: Storage,
    ) {

In the method to save the session you can call:

private setData(resource: string, value: string) {
        if (!value) {
            return;
        }

        return this.localStorage.setItem(resource, value);
}

Hope this helps!

0

The better approach for you to use will be angular interceptors. Because of this, you don't have to set others header everywhere too. In your case setting withCredentials: true must work for you.

import { Injectable } from "@angular/core";
import {HttpInterceptor, HttpRequest,HttpHandler,HttpEvent,   
HttpErrorResponse,HTTP_INTERCEPTORS} from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError } from "rxjs/operators";

    @Injectable()
    export class CustomInterceptor implements HttpInterceptor {

      constructor() {}

      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
       if (!request.headers.has("Content-Type"))
         {
              request = request.clone({
              setHeaders: {ContentType: "application/x-www-form-urlencoded"},
              withCredentials: true,
              observe: 'response' as 'response'
               });         
        }

        return next.handle(request );
      }
    }

Your Answer

AFlawlessGuy is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.