java 添加authorization_在Angular 2中设置Authorization标头

本文介绍如何在Angular 2中创建一个自定义的HTTP服务,该服务能够自动添加Authorization标头,结合JWT令牌实现安全请求。通过子类化Angular的HTTP服务并注入SecurityService和CookieService,实现在每次请求时添加必要的认证信息。
摘要由CSDN通过智能技术生成

如果你想要一个更永久的解决方案,我有一个适合你 .

通过子类化angular的http服务,您可以注入子类型,然后总是添加 Headers .

import {

Http,

ConnectionBackend,

Headers,

Request,

RequestOptions,

RequestOptionsArgs,

Response,

RequestMethod,

} from '@angular/http';

import { Observable } from 'rxjs/Observable';

import { ErrorObservable } from 'rxjs/observable/ErrorObservable';

// A service that can get the logged in users jwt token as an observable

import { SecurityService } from './security.service';

// A service that handles cookies (angular2-cookie)

import { CookieService } from '../cookie';

/**

* Custom Http client that handles conversions to json, adds CSRF token, and jwt token and redirects to signin if token is missing

*/

export class SecureHttp extends Http {

constructor(

backend: ConnectionBackend,

defaultOptions: RequestOptions,

private securityService: SecurityService,

private cookieService: CookieService

) {

super(backend, defaultOptions);

}

request(url: string | Request, options?: RequestOptionsArgs): Observable {

if (typeof url === 'string') {

return this.get(url, options); // Recursion: transform url from String to Request

}

return this.sendRequest(url, options);

}

get(url: string, options?: RequestOptionsArgs): Observable {

return this.sendRequest({ method: RequestMethod.Get, url: url, body: '' }, options);

}

post(url: string, body: string, options?: RequestOptionsArgs): Observable {

return this.sendRequest({ method: RequestMethod.Post, url: url, body: body }, options);

}

put(url: string, body: string, options?: RequestOptionsArgs): Observable {

return this.sendRequest({ method: RequestMethod.Put, url: url, body: body }, options);

}

delete(url: string, options?: RequestOptionsArgs): Observable {

return this.sendRequest({ method: RequestMethod.Delete, url: url, body: '' }, options);

}

patch(url: string, body: string, options?: RequestOptionsArgs): Observable {

return this.sendRequest({ method: RequestMethod.Patch, url: url, body: body }, options);

}

head(url: string, options?: RequestOptionsArgs): Observable {

return this.sendRequest({ method: RequestMethod.Head, url: url, body: '' }, options);

}

private sendRequest(requestOptionsArgs: RequestOptionsArgs, options?: RequestOptionsArgs): Observable {

let requestOptions = new RequestOptions(requestOptionsArgs);

// Convert body to stringified json if it's not a string already

if (typeof requestOptions.body !== 'string') {

requestOptions.body = JSON.stringify(requestOptions.body);

}

// Get xsrf token from spring security cookie

// by adding .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

const csrfToken: string = this.cookieService.get('XSRF-TOKEN');

let baseOptions: RequestOptions = new RequestOptions({

headers: new Headers({

'Content-Type': 'application/json',

'X-Requested-With': 'XMLHttpRequest',

'X-XSRF-TOKEN': csrfToken

})

});

return this.securityService.accessToken$.mergeMap(token => {

// If there is a token we add it to the baseOptions

if (token) {

baseOptions.headers.set('Authorization', 'Bearer ' + token);

}

// We create a request from the passed in method, url, body and merge our base options in there

let request = new Request(baseOptions.merge(requestOptions));

return super.request(request, options)

.map(res => res.json())

.catch(this.errorHandler);

});

}

private errorHandler(errorResponse: Response): Observable | ErrorObservable {

if (errorResponse.status === 401) {

console.log('redirecting to login');

window.location.href = '/login';

return Observable.empty();

}

// If it's a serious problem we can log it to a service if we want to

if (errorResponse.status === 500) {

// this.errorReporter.logError(errorResponse);

}

console.error(errorResponse);

return Observable.throw(errorResponse.text().length > 0 ? errorResponse.json() : { status: 'error' });

}

}

然后在你的模块中

export function secureHttpFactory(backend: XHRBackend, defaultOptions: RequestOptions, securityService: SecurityService, cookieService: CookieService) {

return new SecureHttp(backend, defaultOptions, securityService, cookieService);

}

@NgModule({

imports: [

HttpModule,

CookieModule,

StorageModule,

],

declarations: [

...DIRECTIVES,

...COMPONENTS,

],

exports: [

...DIRECTIVES,

]

})

export class SecurityModule {

// Only create on instance of these

static forRoot(): ModuleWithProviders {

return {

ngModule: SecurityModule,

providers: [

SecurityService,

{

provide: SecureHttp,

useFactory: secureHttpFactory,

deps: [XHRBackend, RequestOptions, SecurityService, CookieService]

}

]

};

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值