问题描述
在将项目更新为angular 2 final后,我遇到了使WebApi2授权与IdentityServer3和angular2-jwt一起工作的问题.在angular2-jwt配置中,一切正常之前,标头名称为空,token-getter-method仅返回令牌.
after updating my project to angular 2 final i had a problem getting WebApi2 authoriaztion to work with IdentityServer3 and angular2-jwt. Before everything worked fine when in angular2-jwt configuration the headername was empty and the token-getter-method returned simply the token.
更新空标题名称后,导致javascript错误:
After updating an empty headername caused an javascript-error:
EXCEPTION: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': '' is not a valid HTTP header field name.
推荐答案
所以首先我必须提供一个标头名称,在我的根模块angular2-jwt配置中看起来像这样:
So first i had to provide a headername, in my root-module angular2-jwt config looked like this:
provideAuth({
headerName: 'BearerToken',
headerPrefix: '',
tokenName: '',
tokenGetter: () => {
return JSON.parse(localStorage.getItem('bearerToken'));
},
globalHeaders: [{'Content-Type': 'application/json'}],
noJwtError: true,
noTokenScheme: true
})
仍然无法正常工作.经过一番研究,我发现标题名称应该是"Authorization",tokenName应该是"Bearer".好的,我们可以这样尝试:
Still not working. After some research i found the header name should be 'Authorization' and the tokenName should be 'Bearer'. Ok lets try like this:
provideAuth({
headerName: 'Authorization',
headerPrefix: '',
tokenName: 'Bearer',
tokenGetter: () => {
return JSON.parse(localStorage.getItem('bearerToken'));
},
globalHeaders: [{'Content-Type': 'application/json'}],
noJwtError: true,
noTokenScheme: true
})
仍然没有到达带有Authorize-Tag的ControllerMethod.好的,最后一次尝试,也许当我手动添加"Bearer"时有效:
Still my ControllerMethod with the Authorize-Tag was not reached. Ok, one last try, maybe it works when i add 'Bearer ' manually:
provideAuth({
headerName: 'Authorization',
headerPrefix: '',
tokenName: 'Bearer',
tokenGetter: () => {
var token: string = JSON.parse(localStorage.getItem('bearerToken'));
return 'Bearer ' + token;
},
globalHeaders: [{'Content-Type': 'application/json'}],
noJwtError: true,
noTokenScheme: true
})
然后...轰炸惊喜...奏效了;)多玩了一点,我发现tokenName可以为空或可以包含其他任何内容.
and ... bombe surprise ... it worked ;) Playing around a little bit more i found out that tokenName can be empty or can contain anything else.
这篇关于使用angular2-jwt从WebApi中间件进行IdentityServer BearerAuthentication的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!