Angular 7,.netcore应用程序上的401(未经授权)请求

时间:2019-05-31 09:57:11

标签: .net angular asp.net-core

我在授权用户使用.net Core和angular 7应用程序上的api时收到401未经授权的错误。

我的角度服务具有功能:-

getUserProfile() {
   var tokenHeader = new HttpHeaders({'Authorization':'Bearer ' + localStorage.getItem('token')});
   console.log(tokenHeader)
   return this.http.get('/api/ApplicationUser/UserProfile', { headers: tokenHeader});
}

tokenHeader上,我正在向用户发送jwt令牌。

我的api是

[HttpGet]
[Authorize]
[Route("UserProfile")]
//'api/userProfile'
public async Task<Object> GetUserProfile()
{
    string userId = User.Claims.First(c => c.Type == "UserID").Value;
    var user = await _userManager.FindByIdAsync(userId);
    return new { user.fullName, user.Email, user.UserName };
}

我尝试了其他问题的一些答案,但没有帮助。

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

您的代码应该是这样

const httpOptions = {
  headers: new HttpHeaders({
    'Authorization': `Bearer ${localStorage.getItem('token')}`
  })
};

return this.http.get('/api/ApplicationUser/UserProfile', httpOptions);

还要确保您的控制器中有此行

[Authorize(AuthenticationSchemes = "Bearer")]

答案 1 :(得分:-1)

您可以通过“网络”标签共享您的请求吗? 我也建议使用拦截器使其成为全局

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

 private isRefreshing = false;
 private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);

 constructor(public authService: AuthService) { }

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   if (this.authService.getJwtToken()) {
     request = this.addToken(request, this.authService.getJwtToken());
   }

   return next.handle(request).pipe(catchError(error => {
     if (error instanceof HttpErrorResponse && error.status === 401) {
       return this.handle401Error(request, next);
     } else {
       return throwError(error);
     }
   }));
 }

 private addToken(request: HttpRequest<any>, token: string) {
   return request.clone({
     setHeaders: {
       'Authorization': `Bearer ${token}`
     }
   });
 }

 private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
   if (!this.isRefreshing) {
     this.isRefreshing = true;
     this.refreshTokenSubject.next(null);

     return this.authService.refreshToken().pipe(
       switchMap((token: any) => {
         this.isRefreshing = false;
         this.refreshTokenSubject.next(token.jwt);
         return next.handle(this.addToken(request, token.jwt));
       }));

   } else {
     return this.refreshTokenSubject.pipe(
       filter(token => token != null),
       take(1),
       switchMap(jwt => {
         return next.handle(this.addToken(request, jwt));
       }));
   }
 }
}

完整示例https://github.com/bartosz-io/jwt-auth-angular/blob/master/src/app/auth/token.interceptor.ts