源代码和演示:
https://github.com/trungk18/angular-authentication-demo-with-lazy-loading
https://stackblitz.com/edit/angular-authentication-demo-with-lazy-loading
当我们第一次运行时,我将添加该部分以延迟加载所有其他模块。这意味着只有登录页面将首次加载。登录后,将加载下一个模块。它将为我们节省大量带宽。
有一个用户,我在登录成功后将整个对象存储到localStorage中。
流程可能是这样的。
-
打开应用程序
-
AuthGuard 将被触发。如果 localStorage 中有带有令牌的用户对象,则激活路由。如果没有,则返回登录页面。
-
在路由被激活并开始对服务器进行 API 调用后,JWTInterceptor 将被触发,在每个后续请求中发送令牌。
-
ErrorInterceptor 检查是否有 401,然后从 localStorage 中删除用户并重新加载页面。这种处理更多的是针对某人尝试使用不同的令牌或对象手动更新 localStorage 的用例。如果令牌是正确的且没有来自服务器的修饰符,则不应该发生。
型号
export const ConstValue = {
ReturnUrl: "returnUrl",
CurrentUser: "currentUser",
}
export const ConstRoutingValue = {
Login: "login"
}
export interface AICreateUser {
firstName: string;
lastName: string;
email: string;
password: string;
roleIds: string[]
}
export interface PartnerUser extends AICreateUser {
id: string;
createdAt: string;
token: string;
featureSet: string[]
}
export interface AuthDto {
email: string;
password: string;
}
身份验证服务
export class AuthService {
private _currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
public get currentUserVal(): User {
return this._currentUserSubject.value;
}
get currentUserToken() {
return this.currentUserVal.token;
}
constructor(private http: HttpClient) {
this._currentUserSubject = new BehaviorSubject<User>(this.getUserFromLocalStorage());
this.currentUser = this._currentUserSubject.asObservable();
}
login(username, password) {
return this.http.post<any>(`/users/authenticate`, { username, password })
.pipe(map(user => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem(ConstValue.CurrentUser, JSON.stringify(user));
this._currentUserSubject.next(user);
return user;
}));
}
logout() {
// remove user from local storage and set current user to null
localStorage.removeItem(ConstValue.CurrentUser);
this._currentUserSubject.next(null);
}
private getUserFromLocalStorage(): User {
try {
return JSON.parse(localStorage.getItem(ConstValue.CurrentUser)!);
} catch (error) {
return null!;
}
}
}
并且有一个 JwtInterceptor 将令牌附加到每个请求的标头中
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
let currentUser = this.authenticationService.currentUserVal;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
export const JWTInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
};
ErrorInterceptor 检查是否有 401 然后从 localStorage 中删除用户重新加载页面。
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
this.authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
export const ErrorInterceptorProvider = { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
还有一个 AuthGuard 可确保您在激活路由之前拥有令牌。配置Angular路由器时,必须包含在所有路由中,登录页面除外。
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUserToken = this.authenticationService.currentUserToken;
if (currentUserToken) {
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { [ConstValue.ReturnUrl]: state.url }});
return false;
}
}
如果我想使用 User 对象,我将在 AuthService 中获取 currentUser 的 public observable。例如我想在列表中显示用户用户名
export class AppComponent {
currentUser: User;
constructor(
private router: Router,
private authenticationService: AuthService
) {
this.authenticationService.currentUser.subscribe(
x => (this.currentUser = x)
);
}
logout() {
this.authenticationService.logout();
this.router.navigate(["/login"]);
}
}
我希望你能从中得到灵感。