是否可以从角度获取AAD access_token?

问题描述 投票:0回答:2

我正在尝试从角度获取Azure管理资源端点令牌,尽管我知道它在客户端方面很容易受到攻击。出于某种强有力的原因,我无论如何都在寻求这样做。

因为我可以通过运行此命令来获取access_token。

curl -X GET -H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials&client_id=<client-id>&resource=<management-resource-endpoint>&client_secret=<application-secret>' \
https://login.microsoftonline.com/<tenantid>/oauth2/token

我正在尝试将此命令转换为像这样的http get 请求...

getAADToken() {
    const param = new HttpParams();
    param.append('grant_type', 'client_credentials');
    param.append('client_id', <client-id>);
    param.append('resource', '2ff814a6-3304-4ab8-85cb-cd0e6f879c1d');
    param.append('client_secret', <application-secret>);
    return this.http.get<any>("https://login.microsoftonline.com/<tenantid>/oauth2/token", {
      headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'),
      params:param
    });
  }

但遇到 CORS 问题...

angular azure http azure-active-directory
2个回答
2
投票

您不能这样做,因为 Azure AD 不允许您使用浏览器中的客户端凭据流。 他们需要允许跨域请求,而您无法配置该请求。

有很多安全原因导致您无法执行此操作,您提到的最明显的一个是客户端密钥对访问该页面的任何人都是可见的。 此外,任何可以获得该页面文件的人都可以使用 API 作为应用程序,因此追踪谁实际上做了某事变得相当困难。

通常,当您需要作为应用程序执行某些操作,因为用户无法执行此操作时, 您让用户在前端进行身份验证,以他们的身份调用后端 API,API 对用户进行授权,然后对目标 API 进行仅应用程序的身份验证调用。


0
投票

您可以将此AuthInterceptor添加到模块中 `@Injectable() 导出类 AuthInterceptor 实现 HttpInterceptor { 构造函数(私有对话框:MatDialog){}

intercept(request: Http`enter code here`Request<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.handleAccess(request, next));
}
private async handleAccess(request: HttpRequest<any>, next: HttpHandler):
    Promise<HttpEvent<any>> {
    const token = await this.getToken();
    let changedRequest = request;
    // HttpHeader object immutable - copy values
    const headerSettings: { [name: string]: string | string[]; } = {};

    for (const key of request.headers.keys()) {
        headerSettings[key] = request.headers.getAll(key);
    }
    if (token) {
        headerSettings['Authorization'] = 'Bearer ' + token;
    }
    headerSettings['Content-Type'] = 'application/json';
    const newHeader = new HttpHeaders(headerSettings);

    changedRequest = request.clone({
        headers: newHeader
    });
    return next.handle(changedRequest).toPromise();
}

getToken = async () => {
    try {
        const pca = new PublicClientApplication(msalConfig);
        const accounts = pca.getAllAccounts();
        const silentRequest = {
            scopes: [apiConfig.resourceScope],
            account: accounts[0],
        };
        const response = await pca.acquireTokenSilent(silentRequest);
        return response.accessToken;
    } catch (error) {
        console.error(error);
    }
};

}`

© www.soinside.com 2019 - 2024. All rights reserved.