[英]How to get bearer token from auth0 Angular
How Should I get the Auth0 bearer token in Angular. I am currently using Auth0 SDK and AuthModule to set it up.我应该如何在 Angular 中获取 Auth0 承载令牌。我目前正在使用 Auth0 SDK 和 AuthModule 来设置它。
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headers = new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Authorization': 'Bearer ***TOKEN***',
'Content-Type': 'application/json'
});
request = request.clone({
setHeaders: {
headers
}
});
return next.handle(request);
}
}
and app.module.ts和 app.module.ts
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
]
})
export class AppModule {}
I just want to get a way to get bearer token from auth0, I tried implementing getTokenSilently(), didn't work maybe I implemented wrong but I am not sure.我只是想获得一种从 auth0 获取承载令牌的方法,我尝试实现 getTokenSilently(),但没有用,也许我实现错误但我不确定。
Thank you for the help.感谢您的帮助。
You can refer this example and source code while dealing with Authorization headers and Tokens.在处理授权标头和令牌时,您可以参考此示例和源代码。
// src/app/auth/secure-interceptor.service.ts
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable, throwError } from 'rxjs';
import { filter, mergeMap, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class SecureInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (req.url.indexOf('/secure/') > -1) {
return this.auth.accessToken$.pipe(
filter(token => typeof token === 'string'),
mergeMap(token => {
const tokenReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next.handle(tokenReq);
}),
catchError(err => throwError(err))
);
}
return next.handle(req);
}
}
Source - https://kmaida.gitbooks.io/auth0-angular-workshop/content/token-interceptor-service.html来源 - https://kmaida.gitbooks.io/auth0-angular-workshop/content/token-interceptor-service.html
The best way to use auth0 in an angular application where you are calling api from a backend, I have tried my best to explain it.在从后端调用 api 的 angular 应用程序中使用 auth0 的最佳方法,我已尽力解释它。
This is a service I created to use http requests to the backend, service basically helps to make all the API call through 1 file.这是我创建的服务,用于向后端发出 http 请求,服务基本上帮助通过 1 个文件进行所有 API 调用。
Admin.service.ts管理服务.ts
@Injectable({ providedIn: 'root' })
export class AdminService {
equipment= []
constructor(
private http: HttpClient,
) {
}
equipmentlist(){
this.equipment.length = 0;
this.http.get(`${environment.apiUrl}/admin/equipmentlist`).toPromise().then(data => {
for(let key in data)
if(data.hasOwnProperty(key))
this.equipment.push(data[key]);
});
return this.equipment;
}
}
and app.module.ts和 app.module.ts
enum CacheStorage {
LocalStorage = "localStorage",
SessionStorage = "sessionStorage"
}
@NgModule({
bootstrap: [AppComponent],
imports: [
AuthModule.forRoot({
...env.auth,
cacheLocation: 'localstorage',
// The AuthHttpInterceptor configuration
...env.authapi,
}),
],
providers: [
AuthGuard,
Validators,
{ provide: HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor, multi: true }
]
})
export class AppModule {}
Dont forget to configure your enviornment.ts file so the entire thing works compelete.不要忘记配置你的 enviornment.ts 文件,这样整个事情就可以完成了。
export const environment = {
production: false,
apiUrl: "https://localhost:7004",
auth:{
domain: ,
clientId: ,
scope:,
redirectUri: ,
apiUrl:"https://localhost:7004/",
audience: ,
useRefreshTokens: true,
},
authapi:{
httpInterceptor: {
allowedList: [
// YOUR backend API - specifically the protected ones
'https://localhost:7004/admin/*'
],
}
},
You can find more related article on Auth0's Docs I personally didn't find it very useful but they are extensive and gradually it does start making sense.您可以在 Auth0 的文档上找到更多相关文章,我个人认为它不是很有用,但它们内容广泛,并且逐渐开始变得有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.