在Angular 8中检查会话通常涉及到验证用户的登录状态和会话信息。这通常通过以下几种方式实现:
以下是一个简单的示例,展示如何在Angular 8中使用JWT进行会话检查:
首先,安装angular-jwt
库来处理JWT:
npm install angular-jwt
创建一个HTTP拦截器来在每个请求中添加Token,并在响应中检查Token的有效性。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
jwtHelper = new JwtHelperService();
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('token');
if (token) {
const clonedReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(clonedReq);
}
return next.handle(req);
}
}
在app.module.ts
中注册这个拦截器:
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
export class AppModule { }
在需要检查会话的地方,可以使用JwtHelperService
来验证Token的有效性:
import { Component } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private jwtHelper: JwtHelperService) {
const token = localStorage.getItem('token');
if (token && !this.jwtHelper.isTokenExpired(token)) {
console.log('Session is valid');
} else {
console.log('Session expired or invalid');
}
}
}
如果Token过期,服务器会返回一个错误响应。可以在拦截器中捕获这个错误并重定向到登录页面:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('token');
if (token) {
const clonedReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(cloned.Request).pipe(
catchError(error => {
if (error.status === 401) {
// Redirect to login page
}
return Observable.throw(error);
})
);
}
return next.handle(req);
}
确保Token存储在localStorage
或sessionStorage
中时是安全的,避免XSS攻击。可以使用HttpOnly
Cookie来存储Token。
通过以上步骤,你可以在Angular 8中实现基本的会话检查功能。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云