如何在HTTP请求角度中添加令牌

时间:2020-07-30 06:34:44

标签: angular spring jwt

我正准备使用angluar和spring boot登录。我使用JWT身份验证,并且在成功进行身份认证之后,我得到了令牌作为响应。提交登录名后,我将重定向到另一个URL,但是我需要将承载令牌添加到URL中,否则它将返回anonymousUser。我是新手,请告诉我如何将令牌添加到请求中。

LoginService

loginUser(data: Student): Observable<any> {
    const url = '/login';
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/text; charset=utf-8');
    return this.httpClient.post(this.serverUrl + url, data, {responseType: 'text' as 'json'});
}

getuserInfo(): Observable<any> {
    const url = '/userinfo';
    return this.httpClient.get(this.serverUrl + url);
}

登录表单提交

登录信息

submitForm(submission: any): void {
    console.log(submission);
    if (submission && submission.submit) {
        delete submission.submit;
    }
    this.loginService.loginUser(submission)
        .subscribe(result => {
            console.log(result);
            this.userinfo();
        }, err => {
            alert(err);
        });
}

userinfo() {
    this.loginService.getuserInfo()
    .subscribe(result => {
        console.log(result);
    }, err => {
        alert(err);
    });
}

Response

如何在用户信息中添加此令牌,请帮助我。

6 个答案:

答案 0 :(得分:4)

将令牌存储在localStorage中

localStorage.setItem('token', 'yourToken');

并使用拦截器在请求中设置令牌:

@Injectable({
    providedIn: 'root'
})
export class UserEmulationInterceptor implements HttpInterceptor {

    private readonly token: string;

    constructor() {
        this.token = localStorage.getItem('your_sso_token');
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.token) {
            const modReq = req.clone({
                setHeaders: {
                    'your_sso_token': this.token
                }
            });
            return next.handle(modReq);
        }
        return next.handle(req);
    }
}

答案 1 :(得分:3)

userinfo()函数中,将令牌存储在localStorage中

例如localStorage.setItem('token', 'yourToken'),然后在loginUser(data: Student)中检索类似的值

const token = localStorage.getItem('token')

// Add a header
header.set('Authorization', `Bearer ${token}`)

如果您在更多要求下使用此功能,则最好调查HttpInterceptor

答案 2 :(得分:1)

Angular为我们提供了HTTP_INTERCEPTOR的策略来处理这种情况,在这种情况下,我们需要向每个HTTP调用传递一些公共数据,并确保请求模式是一致且干净的。

以下是您可以使用的东西,具体取决于您所构建的应用程序的类型。

  1. 将从登录名收到的令牌存储为响应:
- LocalStorage: if you want the session to be continued even after the user closes the tab.
- Redux/Service: If you want the session to end as soon as the user closes the tab.
  1. 创建一个新服务,并将HttpInterceptor扩展到该服务。结束类应该看起来像这样。
@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {

  constructor(
    private authService: AuthService
  ) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

     // This is my helper method to fetch the data from localStorage.
      const token: string = this.authService.getToken(); 
      if (request.url.includes(environment.apiURL)) {

          const params = request.params;
          let headers = request.headers;

          if (token) {
            // set the accessToken to your header
            headers = headers.set('accessToken', token);
          }

          request = request.clone({
            params,
            headers
          });
        }

      return next.handle(request);
    }
}

  1. 通过app.module.ts在您的提供商中注册。
@NgModule({
  declarations: [
   ...
 ],
  imports: [
   ...
  ],
  providers: [
    ...
    { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true },
  ],
  exports: [
   ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
 ---
}

就是这样。

快乐编码。 :)

答案 3 :(得分:0)

token = localStorage.getItem('token') // Will return if it is not set 

this.token = "Bearer " + this.token
let httpOptions = {
  headers: new HttpHeaders({
    'Authorization': this.Token
  })
}
return this.httpClient.post(yourendpoint + '/path', httpOptions)

答案 4 :(得分:0)

尝试一下:-

      tokenType  = 'Bearer ';
      loginUser(data: Student): Observable<any> {
            const url = '/login';
            const header = new HttpHeaders().set('Authorization', this.tokenType + this.cookieService.get('token')); // may be localStorage/sessionStorage
            const headers = { headers: header };
            return this.httpClient.post(this.serverUrl + url, data, headers);
        }
        
        getuserInfo(): Observable<any> {
            const url = '/userinfo';
            const header = new HttpHeaders().set('Authorization', this.tokenType + this.cookieService.get('token')); // may be localStorage/sessionStorage
            const headers = { headers: header };
            return this.httpClient.get(this.serverUrl + url,headers);
        }
        
        submitForm(submission: any): void {
            console.log(submission);
            if (submission && submission.submit) {
                delete submission.submit;
            }
            this.loginService.loginUser(submission)
                .subscribe(result => {
                    console.log(result);
                    this.userinfo();
                }, err => {
                    alert(err);
                });
        }
        
        userinfo() {
            this.loginService.getuserInfo()
            .subscribe(result => {
                console.log(result);
            }, err => {
                alert(err);
            });
        }

答案 5 :(得分:0)

也可以使用append代替用“ +”代替值

const header = new HttpHeaders()
  header.append('Authorization', this.tokenType); 
  header.append('Authorization', this.cookieService.get('token'));