[web-app,monitor] 提供后台接口保护,打通前端认证登陆

This commit is contained in:
tomsun28
2021-12-03 09:15:53 +08:00
parent 73d7c0cd5b
commit b632114ebd
10 changed files with 211 additions and 27 deletions

View File

@@ -102,8 +102,8 @@ export const USERS = {
'POST /user/avatar': 'ok',
'POST /login/account': (req: MockRequest) => {
const data = req.body;
if (!(data.userName === 'admin' || data.userName === 'user') || data.password !== 'admin@123') {
return { msg: `Invalid username or passwordadmin/admin@123` };
if (!(data.userName === 'admin' || data.userName === 'user') || data.password !== 'admin') {
return { msg: `Invalid username or passwordadmin/admin` };
}
return {
msg: 'ok',

View File

@@ -9,7 +9,6 @@ import {
} from '@angular/common/http';
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { ALAIN_I18N_TOKEN, _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { NzNotificationService } from 'ng-zorro-antd/notification';
@@ -51,10 +50,6 @@ export class DefaultInterceptor implements HttpInterceptor {
return this.injector.get(NzNotificationService);
}
private get tokenSrv(): ITokenService {
return this.injector.get(DA_SERVICE_TOKEN);
}
private get http(): _HttpClient {
return this.injector.get(_HttpClient);
}
@@ -75,15 +70,16 @@ export class DefaultInterceptor implements HttpInterceptor {
* 刷新 Token 请求
*/
private refreshTokenRequest(): Observable<any> {
const model = this.tokenSrv.get();
return this.http.post(`/api/auth/refresh`, null, null, { headers: { refresh_token: model?.refresh_token || '' } });
const refreshToken = this.storageSvc.getRefreshToken();
return this.http.post(`/account/auth/refresh`, null, null,
{ headers: { Authorization: `Bearer ${refreshToken}` }});
}
// #region 刷新Token方式一使用 401 重新刷新 Token
private tryRefreshToken(ev: HttpResponseBase, req: HttpRequest<any>, next: HttpHandler): Observable<any> {
// 1、若请求为刷新Token请求表示来自刷新Token可以直接跳转登录页
if ([`/api/auth/refresh`].some(url => req.url.includes(url))) {
if ([`/account/auth/refresh`].some(url => req.url.includes(url))) {
this.toLogin();
return throwError(ev);
}
@@ -105,8 +101,10 @@ export class DefaultInterceptor implements HttpInterceptor {
this.refreshToking = false;
this.refreshToken$.next(res);
// 重新保存新 token
this.storageSvc.storageAuthorizationToken(res);
this.tokenSrv.set(res);
let token = res.token;
let refreshToken = res.refreshToken;
this.storageSvc.storageAuthorizationToken(token);
this.storageSvc.storageRefreshToken(refreshToken);
// 重新发起请求
return next.handle(this.reAttachToken(req));
}),
@@ -134,7 +132,7 @@ export class DefaultInterceptor implements HttpInterceptor {
private toLogin(): void {
this.notification.error(`未登录或登录已过期,请重新登录。`, ``);
this.goTo(this.tokenSrv.login_url!);
this.goTo('/passport/login');
}
private fillHeaders(headers?: HttpHeaders): { [name: string]: string } {

View File

@@ -12,7 +12,7 @@
<nz-form-item>
<nz-form-control nzErrorTip="Please enter password">
<nz-input-group nzSize="large" nzPrefixIcon="lock">
<input nz-input type="password" formControlName="password" placeholder="password: admin@123" />
<input nz-input type="password" formControlName="password" placeholder="password: admin" />
</nz-input-group>
</nz-form-control>
</nz-form-item>

View File

@@ -8,6 +8,8 @@ import { SettingsService, _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { NzTabChangeEvent } from 'ng-zorro-antd/tabs';
import { finalize } from 'rxjs/operators';
import {Message} from "../../../pojo/Message";
import {LocalStorageService} from "../../../service/local-storage.service";
@Component({
selector: 'passport-login',
@@ -28,11 +30,12 @@ export class UserLoginComponent implements OnDestroy {
@Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
private startupSrv: StartupService,
private http: _HttpClient,
private cdr: ChangeDetectorRef
private cdr: ChangeDetectorRef,
private storageSvc: LocalStorageService
) {
this.form = fb.group({
userName: [null, [Validators.required, Validators.pattern(/^(admin|user)$/)]],
password: [null, [Validators.required, Validators.pattern(/^(admin@123)$/)]],
userName: [null, [Validators.required]],
password: [null, [Validators.required]],
mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
captcha: [null, [Validators.required]],
remember: [true]
@@ -111,29 +114,28 @@ export class UserLoginComponent implements OnDestroy {
this.loading = true;
this.cdr.detectChanges();
this.http
.post('/login/account?_allow_anonymous=true', {
.post<Message<any>>('/account/auth/form', {
type: this.type,
userName: this.userName.value,
identifier: this.userName.value,
password: this.password.value
})
.pipe(
finalize(() => {
this.loading = true;
this.loading = false;
this.cdr.detectChanges();
})
)
.subscribe(res => {
if (res.msg !== 'ok') {
this.error = res.msg;
.subscribe(message => {
if (message.code !== 0) {
this.error = message.msg;
this.cdr.detectChanges();
return;
}
// 清空路由复用信息
this.reuseTabService.clear();
// 设置用户Token信息
// TODO: Mock expired value
res.user.expired = +new Date() + 1000 * 60 * 5;
this.tokenService.set(res.user);
this.storageSvc.storageAuthorizationToken(message.data.token);
this.storageSvc.storageRefreshToken(message.data.refreshToken);
// 重新获取 StartupService 内容,我们始终认为应用信息一般都会受当前用户授权范围而影响
this.startupSrv.load().subscribe(() => {
let url = this.tokenService.referrer!.url || '/';

View File

@@ -19,7 +19,8 @@ const routes: Routes = [
{
path: '',
component: LayoutBasicComponent,
canActivate: [SimpleGuard],
// 路由守卫 在路由之前判断是否有认证或者权限进入此路由
// canActivate: [SimpleGuard],
children: [
// todo 根据路由自动生成面包屑
{ path: '', redirectTo: 'dashboard', pathMatch: 'full'},

View File

@@ -1,6 +1,7 @@
import { Injectable } from '@angular/core';
const Authorization = 'Authorization';
const refreshToken = 'refresh-token';
@Injectable({
providedIn: 'root'
@@ -22,6 +23,14 @@ export class LocalStorageService {
return this.getData(Authorization);
}
public getRefreshToken(): string | null {
return this.getData(refreshToken);
}
public storageRefreshToken(token: string) {
return this.putData(refreshToken, token);
}
public storageAuthorizationToken(token: string) {
return this.putData(Authorization, token);
}