@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);
}
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的http服务,您可以注入子类化的版本,然后始终添加头。
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]
}
]
};
}
}
问题内容: 我一直在尝试使用axios向National Park Service API发出GET请求,并尝试了几种方法将请求标头中的API密钥设置为无效。任何帮助将不胜感激。 我努力了: 和 都返回401。当我在Postman中发送GET请求时工作,我在密钥字段中输入Authorization,在值字段中输入我的API密钥。 谢谢。 问题答案: 此问题是由浏览器中的CORS OPTIONS请求
我们正在尝试使用Apache Camel Restlet组件启动REST Web服务调用,并且成功了。 但是我们无法从我们在Apache Camel Exchange Header中设置的请求对象中检索授权标头属性值。 实际上我们是通过Camel的动态路由器进行这个REST调用的。有人能建议如何在Apache Camel Exchange中设置授权标头吗?
问题内容: 一个简单的问题:如何在html中设置作用域值,以供控制器读取? JSFiddle:http : //jsfiddle.net/ncapito/YdQcX/ 问题答案: 在循环内分配变量时不起作用。用 尾随会停止对任何文本求值的Angular表达式。 然后,您只需调用即可输出变量值。 我发现在迭代多个嵌套数组时这非常有用,我想将当前的迭代信息保留在一个变量中,而不是多次查询。
我有一个用于REST API的HttpClient。然而,我在设置授权头时遇到了麻烦。我需要将头设置为我在执行OAuth请求时收到的令牌。我看到了一些.NET的代码, 但是,WinRT中不存在凭据类。有人知道如何设置授权头吗?
我使用中的此选项在服务器中运行: 我得到这个错误: 分析INI配置文件时出错:未知的选项安全性。
Using a delegation key The collaborator can now push to the repository using Docker Content Trust. Docker will automatically choose and pick the right key for the targets/release role. Edit the file o