I'm trying to add JWT-based authentication in an Angular 2 application.
I have received an idToken from Auth0 and stored it in LocalStorage. Now I want to ensure, that all outgoing http calls to my API will have this header setup:
Authorization: Bearer e3rere....
Of course I can manually add it on every http call. But it would be more convenient to configure it once and for all.
What is the right way of doing that in Angular? (Angular 2)
答案 0 :(得分:0)
我在AuthService中添加了一个方法,该方法处理创建标题
@Injectable()
export class AuthenticationService {
//Other stuff your authentication service might do
getHeaderWithAuthorization() {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.Token) {
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + currentUser.Token);
return new RequestOptions({ headers: headers });
}
}
}
@Injectable()
export class UserService {
private baseUrl;
private options: RequestOptions;
constructor(private http: Http, private authService: AuthenticationService)
{
this.baseUrl = "/api/User/";
this.options = authService.getHeaderWithAuthorization();
}
SaveUser(user) {
return this.http.post(this.baseUrl + "SaveUser", user, this.options)
.map((res) => res.json());
}
}
答案 1 :(得分:0)
方法1:
如果您使用的是角度4.3+,那么您可以为此目的创建一个interceptor,它将充当中间人。
注意:为了使用拦截器,您必须使用HttpClient代替Http服务,这是角度4.3的新增功能,可以为您提供{Http} some benefits。
如果用户已登录,您可以添加标题。
@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(UserService.getToken()){
req.headers.set('Authorization', 'Bearer ' + UserService.getToken());
}
return next.handle(req);
}
}
重要提示:不要忘记在您的应用模块中提供拦截器类。
import {HTTP_INTERCEPTORS} from '@angular/common/http';
@NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AddHeaderInterceptor,
multi: true,
}],
})
方法2:
如果您使用的是低于4.3.0的版本,则可以采用不同的方法,例如扩展BaseRequestOptions以向所有请求注入公共标头。
import {BaseRequestOptions} from '@angular/http';
@Injectable()
export class AdddingHeaderOptions extends BaseRequestOptions {
constructor() {
super();
if(UserService.getToken()){
this.headers.append('X-Requested-With', 'XMLHttpRequest');
this.headers.append('Authorization', 'Bearer ' + UserService.getToken());
}
}
}
现在,您可以将其提供给app模块文件。
@NgModule({
providers : [
{provide: RequestOptions, useClass: AdddingHeaderOptions }
]
})
答案 2 :(得分:0)
我不确定这是否会被认为是最佳解决方案,但我发现它非常有用。
我将此功能添加到app.module.ts:
export function authHttpServiceFactory(http: Http, options: RequestOptions, auth: AuthService) {
return new AuthHttp( new AuthConfig(
{
tokenName: 'id_token',
globalHeaders: [{'Content-Type': 'application/json'}],
tokenGetter: (() => localStorage.getItem('id_token'))
}
), http, options);
}
...
providers: [...{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [ Http, RequestOptions, AuthService ]
},...]
然后最后我会确保我的服务依赖于AuthHttp而不是Http。