Swa*_*dge 1 jwt spring-boot angular angular-guards
我正在使用 Spring boot 开发 Angular 应用程序。我开发了一个登录页面,以用户名和密码作为输入。一种 Web 服务,用于从后端对用户进行身份验证并发送成功和失败的响应。以及身份验证成功后显示的主页。
发生的情况是,我也可以在不登录的情况下直接打开主页 URL,但这不是正确的。
我需要的是实现一种机制来检查用户是否登录,并据此显示 URL 页面或登录页面。
在Web应用程序中处理身份验证的最佳实践之一是使用JWT在服务器端 生成和检查Token,并在前端和后端的通信中传递Token。当您实现此操作并在服务器中进行身份验证后,您必须将Token存储在LocalStorage或SessionStorage或cockies中以供将来交互。
要在 Angular 应用程序中创建受保护的路由,您必须实现这些:
这是给您的示例代码:
应用程序AuthGuard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '@app/_services';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// check if route is restricted by role
if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
// role not authorised so redirect to home page
this.router.navigate(['/']);
return false;
}
// authorised so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '@environments/environment';
import { User } from '@app/_models';
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) { }
getAll() {
return this.http.get<User[]>(`${environment.apiUrl}/users`);
}
getById(id: number) {
return this.http.get<User>(`${environment.apiUrl}/users/${id}`);
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序路由模块.ts
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home';
import { AdminComponent } from './admin';
import { LoginComponent } from './login';
import { AuthGuard } from './_helpers';
import { Role } from './_models';
const routes: Routes = [
{
path: '',
component: HomeComponent,
canActivate: [AuthGuard]
},
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
data: { roles: [Role.Admin] }
},
{
path: 'login',
component: LoginComponent
},
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
export const appRoutingModule = RouterModule.forRoot(routes);
Run Code Online (Sandbox Code Playgroud)
有关更多信息和完整示例,请阅读本文: Angular 8 - 基于角色的授权教程及示例