我正在 Spring 中从事 Restful 服务工作,并且已经实现了 Json Web Token (JWT) 来进行身份验证和授权。登录后,正确的身份验证 token 将返回给请求用户。对于每个请求,我都会检查请求 header 中的 token 并验证 token 。过滤器代码如下。
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String authToken = request.getHeader(this.tokenHeader);
System.out.println(authToken + " ##########################");
String username = flTokenUtil.getUsernameFromToken(authToken);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (flTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
我使用 Angular 2 作为前端框架。现在,当获得身份验证 token 后,我使用“POSTMAN”请求安全资源时,它工作正常,并且在过滤器中收到 token ,一切顺利。我正在“授权” header 中设置 token 。 现在的问题是,当我使用 Angular 2 token 做同样的事情时,过滤器中的 token 将变为空,但 Firebug 显示“授权” header 已设置并成功发送。我正在做这个
let token = "";
if (undefined != this._tokenService.getToken()) {
token = this._tokenService.getToken().getToken()
}
let header: Headers = new Headers();
header.append('Content-Type', 'application/json');
header.append('Authorization', token);
let options = new RequestOptions({headers: header});
return this.http.get(url, options)
.map(res => {
console.log(res.status)
if (res.status == 200) {
return res.json();
} else if (res.status == 401) {
return null;
} else {
throw new Error('This request has failed ' + res.status);
}
});
我做错了什么?在 Angular 2 中设置标题的正确方法是什么。我该如何解决这个问题?
最佳答案
如果您想要更永久的解决方案,我可以为您提供一个。
通过子类化 Angular 的 http 服务,您可以注入(inject)子类化的版本,然后您总是会添加 header 。
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<any> {
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<any> {
return this.sendRequest({ method: RequestMethod.Get, url: url, body: '' }, options);
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {
return this.sendRequest({ method: RequestMethod.Post, url: url, body: body }, options);
}
put(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {
return this.sendRequest({ method: RequestMethod.Put, url: url, body: body }, options);
}
delete(url: string, options?: RequestOptionsArgs): Observable<any> {
return this.sendRequest({ method: RequestMethod.Delete, url: url, body: '' }, options);
}
patch(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {
return this.sendRequest({ method: RequestMethod.Patch, url: url, body: body }, options);
}
head(url: string, options?: RequestOptionsArgs): Observable<any> {
return this.sendRequest({ method: RequestMethod.Head, url: url, body: '' }, options);
}
private sendRequest(requestOptionsArgs: RequestOptionsArgs, options?: RequestOptionsArgs): Observable<any> {
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<any> | 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]
}
]
};
}
}
关于java - 在 Angular 2 中设置授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40529579/