我正在Angular客户端中编写我的第一个HTTPInterceptor
。我搜索了一些教程并将代码复制到我的项目中。在我的Web API中,我在类声明之前添加了以下内容:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
我在方法之前添加了以下内容:
[Route("api/Account/GetUsersAsync")]
[HttpGet]
[Authorize(Roles = "admin")]
public async Task<IActionResult> GetUsersAsync()
在Angular代码中,我添加了以下拦截器类:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpUserEvent, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { LoginService } from "../services/login.service";
import 'rxjs/add/operator/do';
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
public userToken: string;
constructor(private router: Router, public login: LoginService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.userToken = this.login.getToken();
if (req.headers.get('No-Auth') == "True")
return next.handle(req.clone());
if (localStorage.getItem('userToken') != null) {
const clonedreq = req.clone({
headers: req.headers.set("Authorization", "Bearer " + localStorage.getItem('userToken'))
});
console.log('clonedreq-------------------> ' + clonedreq.headers);
return next.handle(clonedreq)
.do(
succ => { },
err => {
if (err.status === 401)
this.router.navigateByUrl('/home');
}
);
}
else {
this.router.navigateByUrl('/home');
}
}
}
我正在通过组件进行此调用:
getUsers() {
this.userService.getUsers()
.subscribe(( data: any[] )=> {
this.users = data;
(error) => {
this.statusMessage = 'Problem with the service. Please try again later.';
console.error('getUsers ==========> ' + error);
}
;
this.chRef.detectChanges();
const table: any = $('table');
this.dataTable = table.DataTable();
});
}
在我的服务中,我正在拨打此电话:
getUsers() {
return this.http.get('http://localhost:8888/api/account/GetUsersAsync')
.map(response => response.json())
.catch(this.handleError);
}
在调试时,当我尝试通过Web api登录并验证用户身份时会遇到断点。但是,当我单击“用户路线/菜单”链接时,没有看到再次触发断点。在提供程序中,我添加了UserService
,但仍然无法正常工作。任何帮助表示赞赏。
providers: [LoginService,AuthGuard, UserService,
{
provide : HTTP_INTERCEPTORS,
useClass : AuthInterceptor,
multi : true
}],