Angular 4中如何保存LDAP认证返回的Bearer Token与userId到Cookie?
No worries, let's get this sorted out. Angular 4 doesn't come with built-in cookie manipulation tools, but we can use a trusted third-party package that's compatible with older Angular versions. Here's a step-by-step guide:
Step 1: Install a compatible cookie service package
Since newer versions of ngx-cookie-service don't support Angular 4, we'll use a version that works specifically with Angular 4.x. Run this command in your project root:
npm install ngx-cookie-service@1.0.10 --save
Step 2: Configure the CookieService in your AppModule
You need to import and provide the service so it's available across your app. Open app.module.ts and update it like this:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; // Required for HTTP calls import { CookieService } from 'ngx-cookie-service'; import { AppComponent } from './app.component'; // Import your auth component here @NgModule({ declarations: [ AppComponent, // Add your auth component ], imports: [ BrowserModule, HttpClientModule ], providers: [CookieService], // Register the cookie service bootstrap: [AppComponent] }) export class AppModule { }
Step 3: Save Token and UserId to Cookies after successful authentication
In your authentication component (where you handle the LDAP login request), inject the CookieService and use it to store the values from the JSON response. Here's an example:
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { CookieService } from 'ngx-cookie-service'; @Component({ selector: 'app-login', templateUrl: './login.component.html' }) export class LoginComponent { constructor( private http: HttpClient, private cookieService: CookieService ) { } handleLogin(username: string, password: string) { // Send credentials to your LDAP auth endpoint this.http.post('/your-ldap-auth-endpoint', { username, password }) .subscribe( (response: any) => { // Extract token and userId from the JSON response const bearerToken = response.BearerToken; // Adjust to match your response's key name const userId = response.userId; // Adjust to match your response's key name // Save to cookies - adjust expiration days and path as needed // Syntax: set(name, value, expires?, path?, domain?, secure?, sameSite?) this.cookieService.set('BearerToken', bearerToken, 7, '/'); // 7-day expiration, root path this.cookieService.set('UserId', userId, 7, '/'); // Redirect or handle post-login logic here }, (error) => { console.error('Login failed:', error); // Show error message to user } ); } }
Step 4: Retrieve the values from cookies later
When you need to access the token or userId in other components, just inject the CookieService and use these methods:
// Get the stored token const storedToken = this.cookieService.get('BearerToken'); // Get the stored userId const storedUserId = this.cookieService.get('UserId'); // Check if a cookie exists const hasToken = this.cookieService.check('BearerToken');
Important Security Notes
- If your app uses HTTPS, add the
secureflag to your cookie settings to ensure it's only sent over secure connections:this.cookieService.set('BearerToken', bearerToken, 7, '/', '', true); - HttpOnly Cookies: If you want to set the
HttpOnlyflag (which prevents XSS attacks from accessing the cookie), you can't do this via frontend code. You'll need to adjust your LDAP auth endpoint to return aSet-Cookieheader with the token instead of sending it in the JSON response. This is a more secure approach for authentication tokens.
内容的提问来源于stack exchange,提问作者user9040429

