如何在单页应用中实现授权码流?

如何解决如何在单页应用中实现授权码流?

您好,我正在为我的客户端 SPA 应用程序和 .Net 核心后端 API 应用程序实施身份验证和授权。我在 azure 广告中为 SPA 和 API 应用程序注册了两个应用程序。我可以使用 Postman 获取令牌,如下所示。

postman to get token

我能够获取包含所需详细信息的令牌。现在我在前端反应应用程序中尝试同样的事情。我正在使用 react adal 库。

我有以下代码来获取令牌

   /* istanbul ignore file */
import { adalGetToken,AuthenticationContext,UserInfo } from 'react-adal';
import { UserProfile } from '../common/models/userProfile';
class AdalContext {
    private authContext: AuthenticationContext | any;
    private appId: string = '';
    private endpoints: any;

    public initializeAdal(adalConfig: any) {
        debugger;
        this.authContext = new AuthenticationContext(adalConfig);
        this.appId = adalConfig.clientId;
        this.endpoints = adalConfig.endpoints.api;
    }
    get AuthContext() {
        return this.authContext;
    }

    public getToken(): Promise<string | void | null> {
        debugger;
        return adalGetToken(this.authContext,this.appId,this.endpoints).catch((error: any) => {
            if (error.msg === 'login_required' || error.msg === 'interaction_required') {
                this.authContext.login();
            }
        });
    }

    public acquireToken(callback: Function) {
        let user = this.AuthContext.getCachedUser();
        if (user) {
            this.authContext.config.extraQueryParameter = 'login_hint=' + (user.profile.upn || user.userName);
        }

        adalGetToken(this.authContext,this.endpoints).then(
            (token) => {
                callback(token);
            },(error) => {
                if (error) {
                    if (error.msg === 'login_required') this.authContext.login();
                    else {
                        console.log(error);
                        alert(error);
                    }
                }
            }
        );
    }

    public getCachedToken(): string {
        return this.authContext.getCachedToken(this.authContext.config.clientId);
    }
    public getCachedUser(): UserInfo {
        return this.authContext.getCachedUser();
    }

    public getUserProfileData(): UserProfile {
        const user = this.authContext.getCachedUser();
        const userProfileData = new UserProfile();
        if (user) {
            userProfileData.name = user.profile.name;
            userProfileData.firstName = user.profile.given_name;
            userProfileData.surname = user.profile.family_name;
            userProfileData.emailAddress = user.userName;
            userProfileData.userProfileName = user.profile.name || user.userName;
        }
        return userProfileData;
    }

    public logOut() {
        this.authContext.logOut();
    }
}

const adalContext: AdalContext = new AdalContext();
export default adalContext;
export const getToken = () => adalContext.getToken();

我能够生成令牌,但这里的问题是在 Aud 字段中我正在获取 SPA 的客户端 ID,但我的目的是获取后端的客户端 ID,因为我正在为我的后端应用程序生成令牌。所以我正在努力在反应 adal 代码中设置范围。 在邮递员中,我正在进入范围,但在这里不确定如何通过应对。端点在这里是否意味着范围?同样在邮递员中,我正在传递 SPA 应用程序的客户端秘密,但在这里我没有看到任何传递客户端秘密的选项。有人可以帮助我在这里做错什么,或者我是否以错误的方式理解事情。任何帮助,将不胜感激。谢谢

解决方法

你有一个后端api程序,所以如果你需要为里面的api生成一个访问令牌,你需要在azure ad中expose that api然后给一个azure ad应用程序api权限(可以是那个暴露的 api),然后您就可以生成该令牌。

然后我发现了一个带有 react 的 sample of using adal。并添加了如下所示的acquireToken代码,你可以看到范围是图形,因为在这里我想调用图形api。和你的一样,如果你想生成用于调用你自己的api的token,你需要更改acquireToken的参数,并更改ajax调用中的url。

而且 micrsoft 已经升级到 recommend to use msal 来替代 adal,this sample 很有帮助。

authContext.acquireToken('https://graph.microsoft.com',function (error,token) {
        console.log("the token is:" + token);
        $.ajax({
          url: 'https://graph.microsoft.com/v1.0/me',headers:{'authorization':'Bearer '+ token},type:'GET',dataType:'json'
        }).done(function(res) {
          console.log(res);
        });
      })

==================================更新============ ================

是的,我会提供更多细节,如果我误解了,请原谅。

我之前提到过“公开 api”。例如,您已经注册了一个名为“backendAPP”的 azure 广告应用程序,您可以按照上面的教程转到该应用程序并公开一个 api,接下来,也是这个应用程序,转到 api 权限面板并单击添加权限->选择我的apis->选择'backendAPP'->选择权限并点击底部的添加权限。现在你已经完成了配置。

enter image description here enter image description here enter image description here

如果你是第一次暴露一个api,你可能会看到这个,api就是你需要在代码中使用的。

enter image description here

================================ 更新 2============== ========================

我发现 react-adal.js 中的 adalgetToken 如下所示,我的意思是只有 2 个参数,但在您的代码中似乎有 3 个参数。

/**
 * Return user token
 * @param authContext Authentication context
 * @param resource Resource GUID ot URI identifying the target resource.
 */
export function adalGetToken(authContext: AuthenticationContext,resourceUrl: string): Promise<string | null>;

您已经定义了“this.authContext”,我认为您可以直接在代码中使用 this.authContext.acquireToken('resource',callback)

我的adalConfig.js,这里我使用spa appid作为'clientId',当然我已经添加了'api://xx/accses_user'的api权限。我做这个设置只是为了与客户端应用程序和服务器应用程序不同。

import { AuthenticationContext,adalFetch,withAdalLogin,adalGetToken } from 'react-adal';

export const adalConfig = {
tenant: 'e4c-----57fb',clientId: '2c0e---f157',endpoints: {
    api: 'api://33a01---aebfe202/user_access' // <-- The Azure AD-protected API
},cacheLocation: 'localStorage',};

export const authContext = new AuthenticationContext(adalConfig);

export const adalApiFetch = (fetch,url,options) =>
    adalFetch(authContext,adalConfig.endpoints.api,fetch,options);

export const withAdalLoginApi = withAdalLogin(authContext,adalConfig.endpoints.api);

export const adalGetToken2 = () =>
    adalGetToken(authContext,adalConfig.endpoints.api);

我的 app.js

import React,{ Component } from 'react';
import { authContext,adalConfig,adalGetToken2} from './adalConfig';
import { runWithAdal } from 'react-adal';

const DO_NOT_LOGIN = false;

class App extends Component {

  state = {
    username: ''
  };

  componentDidMount() {

    runWithAdal(authContext,() => {
      // TODO : continue your process
      var user = authContext.getCachedUser();
      if (user) {        
        console.log(user);
        console.log(user.userName);
        this.setState({ username: user.userName });        
      }
      else {
          // Initiate login
          // authContext.login();        
        console.log('getCachedUser() error');
      }
  
      var token = authContext.getCachedToken(adalConfig.clientId)
      if (token) {        
        console.log(token);
      }
      else {        
        console.log('getCachedToken() error');       
      }

      authContext.acquireToken('api://33a01fed-253f-43e5-a0bb-0fffaebfe202/',token) {
        console.log("the token is:" + token);
      })

      // adalGetToken2().then(
      //   (token) => {
      //     console.log("the token2 is : "+token);
      //   },//   (error) => {
      //       if (error) {
      //           if (error.msg === 'login_required') this.authContext.login();
      //           else {
      //               console.log("the error is : "+error);
      //           }
      //       }
      //   }
      // );
     },DO_NOT_LOGIN);
  }

  render() {
    return (
      <div>
        <p>username:</p>
        <pre>{ this.state.username }</pre>
      </div>
    );
  }
}

export default App;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-