我正在研究Asp.Net Core,Angular 6和jwt身份验证,并且我遇到了警卫服务问题。我已经正确配置了它(我希望如此),但是在浏览组件时它永远不会触发,它直接进入后端,并且出现401错误(及其正确的错误),我花了几个小时解决这个问题。我错过了什么?。
谢谢。
guard-auth.ts
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private router: Router, private aut_srv: AuthService) { console.log("Hi!"); } // <- this console.log never run
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
let valid: boolean = true;
if (!this.aut_srv.isLoggedIn()) {
valid = false;
this.router.navigate(["/login"], { queryParams: { returnUrl: state.url } });
}
return valid;
}
}
app.shared.module.ts(为清晰起见,省略所有导入)
@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
LoginComponent
],
imports: [
CommonModule,
HttpClientModule,
FormsModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full', canActivate: [AuthGuardService] },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent },
{ path: 'configuration', component: ConfigurationComponent },
{ path: 'orders-week', component: OrderWeekComponent },
{ path: '**', redirectTo: 'home' }
])
],
providers: [
AuthGuardService,
AuthService
]
})
export class AppModuleShared {
}
auth.services.ts
@Injectable()
export class AuthService {
authKey: string = "auth";
private base_path = 'api/token/auth';
constructor(private http: HttpClient,
@Inject(PLATFORM_ID) private platformId: any,
@Inject("BASE_URL") private base_url: string) {
this.base_path = `${base_url}${this.base_path}`;
}
login(username: string, password: string): Observable<boolean> {
var data = {
user: username,
password: password,
grant_type: "password"
};
return this.http.post(this.base_path, data)
.pipe(map((res: ITokenResponse) => {
let token = res && res.token;
if (token) {
this.setAuth(res);
return true;
}
return Observable.throw('Unauthorized');
}));
}
logout(): boolean {
this.setAuth(null);
return true;
}
setAuth(auth: ITokenResponse | null): boolean {
if (isPlatformBrowser(this.platformId)) {
if (auth) {
localStorage.setItem(
this.authKey,
JSON.stringify(auth));
}
else {
localStorage.removeItem(this.authKey);
}
}
return true;
}
getAuth(): ITokenResponse | null {
if (isPlatformBrowser(this.platformId)) {
var i = localStorage.getItem(this.authKey);
if (i) {
return JSON.parse(i);
}
}
return null;
}
isLoggedIn(): boolean {
if (isPlatformBrowser(this.platformId)) {
return localStorage.getItem(this.authKey) != null;
}
return false;
}
}
答案 0 :(得分:3)
您需要将canActivate Route Guard配置为有效的路由路径“ home”,而不是空路径。
canActivate:[AuthGuardService]