Angular 7-是否可以存储JSESSIONID并在每个请求中发送它?

时间:2019-06-12 13:00:59

标签: angular spring

我正在开发具有Spring后端的angular 7 Web应用程序,我实现了安全性,因此spring在您使用正确的凭据登录时会提供JSESSIONID cookie。如果我尝试用邮递员登录,我会收到cookie,并且一切正常,但是角度看来,即使服务器响应为200,它也不会收到cookie。

我的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
        })
    }
}

我在login.component.ts中的登录方法:

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

我希望Web应用程序存储cookie并在每个请求中发送它,以便后端可以检查您是否真正登录

3 个答案:

答案 0 :(得分:0)

您可以在路由器中发送数据,这正是我想要的。但是在我的主要项目中,JWT信息存储在localStorage中:

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

我很好奇是否有更好的“角度”方式。

我仔细阅读了这篇文章:Netbasal's article着眼于您的问题,但不确定是解决方案还是不错的解决方案。

答案 1 :(得分:0)

以Angular方式,您可以将打字稿与接口名称isAccessibilityFocused()一起使用。在登录服务中,您可以Storage存储并使用它,例如:

@Inject

在保存会话的方法中,您可以调用:

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

@Injectable()
export class UserSessions {

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

希望这会有所帮助!

答案 2 :(得分:0)

您可以使用更好的方法是interceptors。因此,您也不必在任何地方都设置其他标题。在您的情况下,设置withCredentials:true必须对您有用。

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 );
      }
    }