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

如何安全存储JWT令牌?Angular网站API授权的安全存储方案咨询

Safer Ways to Store JWT Tokens in Angular

Great question—storing JWTs in localStorage is a common misstep because it leaves you wide open to XSS attacks: any malicious script injected into your app can easily grab the token and misuse it. Let’s walk through the most secure alternatives and how to implement them in Angular:

1. HttpOnly, Secure Cookies (Top Recommendation)

This is the gold standard for JWT storage. HttpOnly cookies are not accessible via JavaScript, which eliminates XSS risks entirely. Here’s how to make this work:

Backend Configuration

First, your API needs to issue the JWT as an HttpOnly cookie with these critical attributes:

  • HttpOnly: Prevents JS from reading the cookie
  • Secure: Ensures the cookie is only sent over HTTPS
  • SameSite: Set to Strict or Lax to block cross-site request forgery (CSRF) attempts
  • Path: Restrict the cookie to your API path (e.g., /api)

Angular Implementation

When making API requests, you just need to tell Angular’s HttpClient to include cookies with the request:

import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class ApiService {
  constructor(private http: HttpClient) {}

  fetchData() {
    return this.http.get('/api/data', { withCredentials: true });
  }
}

CSRF Protection

Since you’re using cookies, you need to guard against CSRF attacks. Angular has built-in support for this:

  • Your backend should include a CSRF token in a cookie (e.g., XSRF-TOKEN)
  • Angular automatically reads this cookie and adds an X-XSRF-TOKEN header to your requests
  • If you need custom configuration, you can override the default XSRFStrategy:
import { NgModule } from '@angular/core';
import { HttpClientModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/common/http';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    {
      provide: XSRFStrategy,
      useValue: new CookieXSRFStrategy('XSRF-TOKEN', 'X-XSRF-TOKEN')
    }
  ]
})
export class AppModule {}

2. In-Memory Storage (For Frontend-Accessible Tokens)

If you need the JWT to be accessible in your Angular app (e.g., to decode user claims), store it in a service-level variable instead of localStorage. This way, the token only lives in memory and is wiped when the page refreshes or the tab closes.

Example Implementation

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class AuthService {
  private _accessToken: string | null = null;

  setAccessToken(token: string) {
    this._accessToken = token;
  }

  getAccessToken(): string | null {
    return this._accessToken;
  }

  clearAuth() {
    this._accessToken = null;
  }
}

Pair with Refresh Tokens

To handle page refreshes, use a short-lived access token stored in memory, and a long-lived refresh token stored in an HttpOnly cookie. When the app loads, call an API endpoint with withCredentials: true to exchange the refresh token for a new access token.

3. Avoid Session Storage (Still Vulnerable to XSS)

While sessionStorage only persists for the current browser session, it’s still accessible via JavaScript—so XSS attacks can still steal the token. Skip this option unless you have a very specific use case and understand the risks.

Additional Security Best Practices

  • Short-Lived Access Tokens: Keep access tokens valid for 15-30 minutes to limit damage if a token is compromised.
  • Use HTTPS Everywhere: Never send tokens over unencrypted HTTP—this exposes them to man-in-the-middle attacks.
  • Enable Angular’s XSS Protection: Use Angular’s built-in sanitization (e.g., avoid innerHTML unless absolutely necessary, use the SafePipe for trusted content) to reduce XSS risks.
  • Validate Token Signatures: Always verify the JWT’s signature on the backend to ensure it hasn’t been tampered with.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:16:47