使用Adal Angle获取Azure AD的刷新令牌

时间:2018-11-13 14:14:21

标签: angular azure-active-directory azure-ad-graph-api

我正在使用“ adal-angular6”:“ 1.0.68”版本。

这是我的配置::

private config = {
    tenant: environment.appId,     // tenantId.
    clientId: environment.clientId,
    redirectUri: environment.origin + '/auth-callback', // callback URI.
    postLogoutRedirectUri: environment.origin,
    cacheLocation: 'localStorage',
};

我致电adalService.acquireToken('https://graph.microsoft.com')时没有得到刷新令牌。我在误配置吗?

2 个答案:

答案 0 :(得分:0)

No, you cannot get refresh tokens in the front-end.

You need a client secret to exchange refresh tokens for new access tokens, and you can't put a secret in front-end Javascript code, as it is visible to everyone.

答案 1 :(得分:0)

我将尝试给出有效的代码,但不使用包装程序adal-angular6,而是使用AzureAD的官方adal-angular

这是我的angular.json部分,用于加载库:

{
  ...
  "projects": {
    "my-app": {
      ...
      "architect": {
        "build": {
          ...
          "options": {
            ...
            "scripts": [
              "node_modules/adal-angular/dist/adal.min.js"
            ]

这是我的身份验证服务的一部分,用于初始化库:

declare var AuthenticationContext;
@Injectable(...)
export class AuthService {
  adalConfig = {
    tenant: '*******.com',
    clientId: '12345678-9abc-def0-1234-56789abcdef0',
    redirectUri: environment.redirectPath,
    postLogoutRedirectUri: environment.redirectPath,
    cacheLocation: 'localStorage',
  };

  authContext;

  constructor(http: HttpClient) {
    this.authContext = new AuthenticationContext(this.adalConfig);
  }

  acquireToken(): Observable<string> {
    const func: (a: string, c: (error, token: string) => void) => void = (a, c) => {
      (this.authContext.acquireToken.bind(this.authContext))(a, c);
    };
    const bound = bindCallback(func);
    return bound(this.authContext.config.clientId).pipe(map(([e, r]) => r));
  }
  ...
}

这是在每次Ajax调用之前我的拦截器中发生的事情:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(auth: AuthService, route: Router) { }

  intercept(request: HttpRequest<any>, next: HttpHandler):
    Observable<HttpSentEvent
    | HttpHeaderResponse
    | HttpProgressEvent
    | HttpResponse<any>
    | HttpUserEvent<any>> {
    const tokenGetter = this.auth.acquireToken();
    const rc = tokenGetter.pipe(
      take(1),
      switchMap(r => {
        const req2 = r && request.clone({
          setHeaders: {
            Authorization: `Bearer ${r}`
          }
        }) || request;
        return next.handle(req2).pipe(
          tap(null, (err: HttpErrorResponse) => {
            if (err.status === 401) {
              ... // handle auth errors, auth again, save url and remake call, etc...
            }
          }),
          catchError((e, c) => { ... })
        );
      }));
    return rc;
  }

关于上述内容的唯一奇怪的事情是该库的acquireToken接受了一个回调函数,而我正在使用rxjs的{​​{1}}将其转换为可观察的函数,但除此之外,它只是有效。

请注意,bindCallback方法不接受任何参数(与我在对该问题的评论中所说的相反)。