我正在尝试通过定义路径防护并将canActivate分配给每个希望安全的路径来保护我的应用程序免受未经授权的用户的侵害。这些路由的一切都很好,例如,当某人想要从url访问路由时,它将自动重定向到登录页面,除非他/她已登录,则该应用程序将重定向到特定路由。但是只有一种途径,当用户登录时,它总是返回登录页面。此问题发生在路线'/verify/:idC'
上,该怎么办?
routing.ts:
{ path: 'verify/:idC', component: VerifyRoleComponent, canActivate: [AuthGuard] },
auth-guard.ts:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../auth/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
auth.service.ts:
@Injectable()
export class AuthService {
isLoggedIn = false;
constructor() { }
// store the URL so we can redirect after logging in
redirectUrl: string;
login(): Observable<boolean> {
return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
}
logout(): void {
this.isLoggedIn = false;
}
}
verify-component.ts:
@Component({
selector: 'app-verify-role',
templateUrl: './verify-role.component.html',
styleUrls: ['./verify-role.component.scss']
})
export class VerifyRoleComponent implements OnInit {
auth: Auth;
constructor(private credService: CredentialService, private authService: AuthService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
const id = this.route.snapshot.paramMap.get('idC');
console.log(id) ;
this.route.paramMap
.switchMap((params: ParamMap) =>
this.credService.getAccountId(params.get('idC')))
.subscribe(res => {
this.auth = res;
console.log(this.auth);
if (res.role.toString() == "User"){
let idC = res.account;
this.loginUser(idC);
} else {}
}, err => {
console.log(err);
});
}
loginUser(idC:string) {
this.authService.login().subscribe(() => {
if (this.authService.isLoggedIn) {
let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/profile/'+idC;
this.router.navigate([redirect]);
}
});
}
}
答案 0 :(得分:0)
我认为您必须在cities.Values.Where(c => c.Name.IndexOf("yor", StringComparison.OrdinalIgnoreCase) >= 0)