Set-Cookie JWT in chrome with Angular

27 Views Asked by At

I tried to get token from back-end in host 127.0.0.1:800. I make it with success when i'm using postmen and Firefox browser, but it dosn't work on chrome browser. Browser dosn't want to save cookie. Please Help me. Belowe i wrote request, response and also angular code.

This is request:

POST /core/login/ HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101     Firefox/122.0
Accept: application/json, text/plain, */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: text/plain
Content-Length: 43
Origin: http://localhost:4200
Connection: keep-alive
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site

This is response:

HTTP/1.1 200 OK
Date: Thu, 25 Jan 2024 22:17:19 GMT
Server: WSGIServer/0.2 CPython/3.10.8
Content-Type: application/json
Vary: Accept, origin, Cookie
Allow: POST, OPTIONS
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:4200
X-Frame-Options: DENY
Content-Length: 14
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
Set-Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiZXhwIjoxNzA2MjY0MjM5LCJpYXQiOjE3MDYyMjEwMzl9.kZEwI8PlO5A3vjlRy3uXdywrr_JJACR4ZHy65evWeWA; HttpOnly; Path=/

This is my Angular code: api.service.ts:

  constructor(
    private httpClient: HttpClient,
  ) { }

  loginUser(loginData:FormGroup){
    const json = JSON.stringify(loginData);
    return this.httpClient.post<any>(`${this.mainURL}core/login/`, json, {withCredentials: true})
  }

This is my login.component.ts:

  constructor(
    private formBuilder: FormBuilder,
    private apiService:ApiService,
    private guard:AuthGuard,
    private router:Router,
    private loadingService:LoadingService,
    private apiErrorService: ApiErrorService
  ) {}

  ngOnInit(): void {

  }
  sendLoginForm(){
    if(this.loginForm.invalid) return;
    var formData: any = new FormData();
    formData.append("username", this.loginForm.get('username')!.value)
    formData.append("password", this.loginForm.get('password')!.value)

    this.apiService.loginUser(this.loginForm.value).pipe(take(1)).subscribe(
      (result) => {
        if(result.is_ok == false){
          this.apiErrorService.sendNewApiErrorInfo(result.message)
        }
        else {
          sessionStorage.setItem('login', this.loginForm.value.username);
          this.guard.canActivate();
          this.loginForm.reset();
          this.router.navigate(["/panel"]);
           ;
        }
      },
      error => {
        this.apiErrorService.sendNewApiErrorInfo("Niepoprawne dane uwierzytelniające.")
         ;
        this.isLoginError = true;
      }
    )
  }

0

There are 0 best solutions below