我正在尝试创建一个角度应用程序,它将使用 JWT 令牌向 ASP NET CORE WEB API 发出请求,我设置了一个 httpinterceptor,但它似乎不起作用 - 它不会向请求添加标头,并且拦截器本身不会出现在浏览器源代码中。它没有任何作用。
下面的代码应该发送带有包含令牌的授权标头的请求。不行,我什至尝试在里面写console.log,但没有成功。
auth.interceptor.ts
@Injectable({
providedIn: 'root'
})
export class AuthInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = localStorage.getItem('authToken');
if (token) {
req = req.clone({
headers: req.headers.append('Authorization', `Bearer ${token}`),
});
}
return next.handle(req);
}
}
我的问题是 getMe() 方法 - 它应该根据令牌返回当前用户的名称。它在 swagger 中工作得很好,所以它不是后端,注册和登录方法也工作得很好,所以它不是 cors。
AuthService.ts
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) {}
public Register(user: User): Observable<any> {
return this.http.post<any>(
'https://localhost:7272/api/Auth/register',
user
);
}
public Login(user: User): Observable<string> {
return this.http.post('https://localhost:7272/api/Auth/login', user, {
responseType: 'text',
});
}
public getMe(): Observable<string> {
return this.http.get('https://localhost:7272/api/Auth', {
responseType: 'text',
withCredentials: true
});
}
}
我像这样导入每个组件:
app.module.ts
@NgModule({
declarations: [
],
imports: [
HttpClientModule,
FormsModule,
BrowserModule,
AppRoutingModule,
NgxMaskDirective,
NgxMaskPipe,
],
bootstrap: [AppComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
provideHttpClient(),
provideNgxMask(),
]
})
export class AppModule{}
我尝试在后端和前端都允许凭据,但它根本不起作用。
您的应用程序中似乎有两个 Angular HttpClient 实例(假设
provideHttpClient
也提供了它):
@NgModule({
...
imports: [
HttpClientModule, // <-- 1 here
...
],
...
providers: [
...
provideHttpClient(), , // <-- 2 here
]
})
export class AppModule{}
为了使拦截器发挥作用,您需要指定哪一个,或者更好的是,只有一个。
尝试删除
provideHttpClient()
,拦截器应该开始工作。