You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何从Authorization头获取JWT并存储到LocalStorage?

Solution: Store JWT from Authorization Header to LocalStorage

Got it, let's get this sorted! When your backend sends back the JWT in the Authorization response header, you can access this header directly from the HttpResponse object in your subscribe handler. Here's the modified version of your saveStudentDetails method with the required logic:

saveStudentDetails(values) { 
  const studentData = {}; 
  studentData['id'] = values.id; 
  studentData['password'] = values.password; 
  this.crudService.loginstudent(studentData).subscribe(
    (result: HttpResponse<any>) => { 
      // Get the Authorization header from the response
      const authHeader = result.headers.get('Authorization');
      
      if (authHeader) {
        // Usually the header is in format "Bearer <token>", so extract just the token
        const jwtToken = authHeader.split(' ')[1];
        // Store the token in localStorage
        localStorage.setItem('studentJwtToken', jwtToken);
      }

      this.toastr.success('You are logged in', 'Success !', { positionClass: 'toast-bottom-right' }); 
      this.router.navigate(['/address']); 
    }, 
    err => { 
      console.log('status code ->' + err.status); 
      this.toastr.error('Please try again', 'Error !', { positionClass: 'toast-bottom-right' }); 
    }
  ); 
}

Key Details:

  • Access the Response Headers: The result parameter in the success callback is an HttpResponse object, which has a headers property. Use result.headers.get('Authorization') to fetch the specific header value.
  • Extract the Token: Most APIs format the Authorization header as Bearer <your-jwt-token>, so we split the string to get just the token part (index 1 of the split array). If your backend returns the token directly without the Bearer prefix, you can skip this split step and store authHeader directly.
  • Persist to LocalStorage: localStorage.setItem('studentJwtToken', jwtToken) saves the token in the browser's local storage, making it accessible across different routes and sessions (until the user clears their browser data).

Bonus Tip for Future Use:

To automatically include this JWT in subsequent API requests, you can create an Angular HTTP interceptor that fetches the token from localStorage and adds it to the Authorization header of every outgoing request. This saves you from manually adding the token to each service call.

内容的提问来源于stack exchange,提问作者Dory

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:42:42