如何在http请求角度添加令牌
Posted
技术标签:
【中文标题】如何在http请求角度添加令牌【英文标题】:How to add token in http request angular 【发布时间】:2020-11-19 20:40:03 【问题描述】:我正在尝试使用 Angular 和 Spring Boot 进行登录。我使用 JWT 身份验证,在成功进行身份验证后,我得到了令牌作为响应。提交登录后,我将重定向到另一个 url,但我需要将不记名令牌添加到 url 中,否则它会返回匿名用户。我是 Angular 新手,请告诉我如何将令牌添加到请求中。
登录服务
loginUser(data: Student): Observable<any>
const url = '/login';
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/text; charset=utf-8');
return this.httpClient.post(this.serverUrl + url, data, responseType: 'text' as 'json');
getuserInfo(): Observable<any>
const url = '/userinfo';
return this.httpClient.get(this.serverUrl + url);
登录表单提交
登录
submitForm(submission: any): void
console.log(submission);
if (submission && submission.submit)
delete submission.submit;
this.loginService.loginUser(submission)
.subscribe(result =>
console.log(result);
this.userinfo();
, err =>
alert(err);
);
userinfo()
this.loginService.getuserInfo()
.subscribe(result =>
console.log(result);
, err =>
alert(err);
);
如何在用户信息中添加此令牌,请帮助我。
【问题讨论】:
angular.io/api/common/http/HttpInterceptor 感谢 gyz 的帮助。我尝试了 Aarji George 解决方案,几乎没有改变,它对我有用。 【参考方案1】:在userinfo()
函数中将令牌存储在localStorage中
例如localStorage.setItem('token', 'yourToken')
然后在loginUser(data: Student)
中检索类似的值
const token = localStorage.getItem('token')
// Add a header
header.set('Authorization', `Bearer $token`)
如果您在更多请求中使用它,那么最好调查HttpInterceptor。
【讨论】:
【参考方案2】:将您的令牌存储在 localStorage 中:
localStorage.setItem('token', 'yourToken');
并使用拦截器在请求中设置令牌:
@Injectable(
providedIn: 'root'
)
export class UserEmulationInterceptor implements HttpInterceptor
private readonly token: string;
constructor()
this.token = localStorage.getItem('your_sso_token');
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
if (this.token)
const modReq = req.clone(
setHeaders:
'your_sso_token': this.token
);
return next.handle(modReq);
return next.handle(req);
【讨论】:
这是完美的做法。事情集中在这里,而不是在每个服务方法中编写标头【参考方案3】:token = localStorage.getItem('token') // Will return if it is not set
this.token = "Bearer " + this.token
let httpOptions =
headers: new HttpHeaders(
'Authorization': this.Token
)
return this.httpClient.post(yourendpoint + '/path', httpOptions)
【讨论】:
【参考方案4】:试试这个:-
tokenType = 'Bearer ';
loginUser(data: Student): Observable<any>
const url = '/login';
const header = new HttpHeaders().set('Authorization', this.tokenType + this.cookieService.get('token')); // may be localStorage/sessionStorage
const headers = headers: header ;
return this.httpClient.post(this.serverUrl + url, data, headers);
getuserInfo(): Observable<any>
const url = '/userinfo';
const header = new HttpHeaders().set('Authorization', this.tokenType + this.cookieService.get('token')); // may be localStorage/sessionStorage
const headers = headers: header ;
return this.httpClient.get(this.serverUrl + url,headers);
submitForm(submission: any): void
console.log(submission);
if (submission && submission.submit)
delete submission.submit;
this.loginService.loginUser(submission)
.subscribe(result =>
console.log(result);
this.userinfo();
, err =>
alert(err);
);
userinfo()
this.loginService.getuserInfo()
.subscribe(result =>
console.log(result);
, err =>
alert(err);
);
【讨论】:
【参考方案5】:也可以使用追加而不是用“+”连接值
const header = new HttpHeaders()
header.append('Authorization', this.tokenType);
header.append('Authorization', this.cookieService.get('token'));
【讨论】:
【参考方案6】:Angular 为我们提供了HTTP_INTERCEPTOR
策略来处理这种情况,在这种情况下,我们需要将一些公共数据传递给每个 HTTP 调用,从而确保请求模式一致且干净。
以下是您可以使用的东西,具体取决于您正在构建的应用程序的类型。
-
将从登录响应接收到的令牌存储在:
- LocalStorage: if you want the session to be continued even after the user closes the tab.
- Redux/Service: If you want the session to end as soon as the user closes the tab.
-
创建一个新服务并将
HttpInterceptor
扩展到它。最终类应如下所示。
@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor
constructor(
private authService: AuthService
)
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
// This is my helper method to fetch the data from localStorage.
const token: string = this.authService.getToken();
if (request.url.includes(environment.apiURL))
const params = request.params;
let headers = request.headers;
if (token)
// set the accessToken to your header
headers = headers.set('accessToken', token);
request = request.clone(
params,
headers
);
return next.handle(request);
-
在
app.module.ts
上的 Provider 中注册。
@NgModule(
declarations: [
...
],
imports: [
...
],
providers: [
...
provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true ,
],
exports: [
...
],
bootstrap: [AppComponent]
)
export class AppModule
---
就是这样。
快乐编码。 :)
【讨论】:
以上是关于如何在http请求角度添加令牌的主要内容,如果未能解决你的问题,请参考以下文章
如何在角度 http 请求中实现 client_credentials 授权类型?