如何从 keyvault 访问秘密? [英] How access a secret from keyvault?

查看:16
本文介绍了如何从 keyvault 访问秘密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了示例反应登录应用程序,其中用户可以通过 azure ad 隐含 oauth2 登录通过参考此

我还通过在 config.js 文件中添加额外的 keyvault 范围来更新我的代码中的范围.

module.exports ={appId:6c90510c-82fd-4113-8aa5-6abdac107839",范围:[user.read",https://vault.azure.net/user_impersonation"]};

我还在 Azure 门户的应用注册中添加了 Keyvault Api 权限..

这是我的登录代码

从msal"导入 { UserAgentApplication }类登录扩展 React.Component {构造函数(道具){超级(道具);this.submitHandler = this.submitHandler.bind(this);this.email = React.createRef();this.password = React.createRef();this.token = "";this.expiresOn = 0;this.userAgentApplication = new UserAgentApplication({授权:{clientId: config.appId,clientSecret: "W~~4iZ.uKv~eoAd-hKKU35WJVv.---83Gm",redirectUri:http://localhost:3000/events"},缓存:{cacheLocation: "localStorage",//这配置了缓存的存储位置storeAuthStateInCookie: true,//将此设置为true"如果您在 IE11 或 Edge 上遇到问题}});这个.state = {错误:空,已验证:假,用户:{}};}登录=异步()=>;{尝试 {//通过弹窗登录等待 this.userAgentApplication.loginPopup({范围:config.scopes,提示:select_account"});//登录后,获取用户的个人资料等待 this.getUserProfile();var user = this.userAgentApplication.getAccount();}抓住(错误){console.log(错误", err.message)这个.setState({已验证:假,用户:{},错误:err.message});}}注销 = () =>{this.userAgentApplication.logout();}getUserProfile = async () =>{尝试 {常量数据 = 等待 this.userAgentApplication.acquireTokenSilent({范围:config.scopes});如果(data.accessToken){console.log(令牌", data.accessToken);this.token = data.accessToken;this.expiresOn = data.expiresOn;}}抓住(错误){console.log("err", err.message);}}使成为() {常量 { isLogin } = this.props;常量按钮标题 = isLogin ?注册":登录";返回 (<form className="login-form">{ !isLogin &&<IconButton backgroundColor="#0A66C2";字体=14px"宽度='35%' 填充='8px' microsoftLoginHandler={this.login}/>}</表格>);}}

当我尝试邮递员的命中 api 时获得访问令牌后.它显示了一些错误.谁能指导我解决此错误,因为我是 Azure Ad 和 Keyvault 的新手

提前致谢

解决方案

考虑到我的代码,它提供了获取访问令牌的功能,该令牌可用于调用api访问密钥库:

请注意,起初我在 [openid"、profile"、User.Read"、https://vault"中使用访问令牌调用 api 时收到与您相同的错误消息.azure.net/user_impersonation"],然后我对令牌进行解码,发现它在声明sub"中不包含user_impersonation",所以我更改了代码中的范围,然后它就起作用了.

<!DOCTYPE html><html><头><元字符集=utf-8";/><标题></标题><script src="js/jquery-1.10.2.min.js"></script><脚本类型=文本/javascript"src=https://alcdn.msftauth.net/lib/1.2.1/js/msal.js"完整性=sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP"crossorigin=匿名"></script></头><身体><button id="btn">点击</button>

用户名:<输入类型=文本";id=用户名"/></div><div id=accessToken"></div><脚本类型=文本/javascript">$("#btn").click(function(){显示欢迎();})常量 msalConfig = {授权:{clientId: "<your azure ad app id>>>,//请使用 azure key vault 添加 api 权限授权:https://login.microsoftonline.com/<your-tenant>",redirectUri: "http://localhost:8848/msalTest/index.html",},缓存:{cacheLocation: "sessionStorage",//这配置了缓存的存储位置storeAuthStateInCookie: false,//将此设置为true"如果您在 IE11 或 Edge 上遇到问题}};const myMSALObj = new Msal.UserAgentApplication(msalConfig);//起初,我使用的范围像 [openid"、profile"、User.Read"、https://vault.azure.net/user_impersonation"]//但是有了这个访问令牌,我得到了和你一样的错误//我尝试使用下面的范围,它工作//我用jwt解码令牌,当我得到错误时,令牌不包含正确的范围常量登录请求 = {范围:[openid"、配置文件"、https://vault.azure.net/user_impersonation"]、};函数显示欢迎(){myMSALObj.loginPopup(loginRequest).then((loginResponse) => {控制台信息(登录响应);console.log("========= myMSALObj.getAccount() =======");console.log(myMSALObj.getAccount());$("#userName").val(myMSALObj.getAccount().name);获取访问令牌();//这里登录成功回调代码}).catch(函数(错误){控制台日志(错误);});}函数 getAccessToken(){getTokenPopup(loginRequest).then(响应 => {$("#accessToken").text(response.accessToken);}).catch(错误 => {控制台日志(错误);});}函数getTokenPopup(请求){返回 myMSALObj.acquireTokenSilent(请求).catch(错误 => {控制台日志(错误);console.log(静默令牌获取失败.使用弹出获取令牌");//当静默呼叫失败时回退到交互返回 myMSALObj.acquireTokenPopup(请求).then(tokenResponse => {返回令牌响应;}).catch(错误 => {控制台日志(错误);});});}</脚本></身体></html>

I created sample react login application where user can login by implict oauth2 login via azure ad by refering to this documentation.

After successful login I am not able to access keyvault secrets by using microsoft graph api with the help of access token.

This is the error I am getting while I am trying to access secrets from keyvault

I also updated the scopes in my code by adding additional keyvault scope in config.js file.

module.exports ={
  appId: "6c90510c-82fd-4113-8aa5-6abdac107839",
  scopes: [
    "user.read",
    "https://vault.azure.net/user_impersonation"
  ]
};

I also added Keyvault Api permissions in app registration from azure portal. .

Here is my login code

import { UserAgentApplication } from 'msal'
class Login extends React.Component {

  constructor(props) {
    super(props);
    this.submitHandler = this.submitHandler.bind(this);
    this.email = React.createRef();
    this.password = React.createRef();
    this.token = "";
    this.expiresOn = 0;
    this.userAgentApplication = new UserAgentApplication({
      auth: {
        clientId: config.appId,
        clientSecret: "W~~4iZ.uKv~eoAd-hKKU35WJVv.---83Gm",
        redirectUri: "http://localhost:3000/events"
      },
      cache: {
        cacheLocation: "localStorage", // This configures where your cache will be stored
        storeAuthStateInCookie: true, // Set this to "true" if you are having issues on IE11 or Edge
      }
    });

    this.state = {
      error: null,
      isAuthenticated: false,
      user: {}
    };
  }

  login = async () => {
    try {
      // Login via popup
      await this.userAgentApplication.loginPopup(
        {
          scopes: config.scopes,
          prompt: "select_account"
        });

      // After login, get the user's profile
      await this.getUserProfile();
      var user = this.userAgentApplication.getAccount();
    }
    catch (err) {
      console.log("errror", err.message)
      this.setState({
        isAuthenticated: false,
        user: {},
        error: err.message
      });
    }
  }

  logout = () => {
    this.userAgentApplication.logout();
  }

  getUserProfile = async () => {
    try {
      const data = await this.userAgentApplication.acquireTokenSilent({
        scopes: config.scopes
      });

      if (data.accessToken) {
        console.log("Token", data.accessToken);
        this.token = data.accessToken;
        this.expiresOn = data.expiresOn;
      }
    }
    catch (err) {
      console.log("err", err.message);
    }
  }

  render() {
    const { isLogin } = this.props;
    const buttonTitle = isLogin ? "Sign Up" : "Login";
    return (
      <form className="login-form">
        { !isLogin && <IconButton backgroundColor="#0A66C2" font="14px" width='35%' padding='8px' microsoftLoginHandler={this.login} />}
      </form>
    );
  }
}

After getting access token when I tried the hit api from postman. It is showing some error. Can anyone please guide me to resolve this error as I am new to Azure Ad and Keyvault

Thanks in advance

解决方案

Take my code into consideration, it offers function to get access token which can used to call api to access key vault:

And pls note, at first I got the same error message as yours when I call api with access token in ["openid", "profile", "User.Read", "https://vault.azure.net/user_impersonation"], then I decode the token and found it didn't contain 'user_impersonation' in claim 'sub', so I changed the scope in the code and then it worked.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="https://alcdn.msftauth.net/lib/1.2.1/js/msal.js" integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>
    </head>
    <body>
        <button id="btn">click</button>
        <div>
            userName:<input type="text" id="userName" />
        </div>
        <div id="accessToken"></div>
        
        <script type="text/javascript">
            $("#btn").click(function(){
                showWelcome();
            })
            
            const msalConfig = {
                auth: {
                  clientId: "<your azure ad app id>", // pls add api permission with azure key vault
                  authority: "https://login.microsoftonline.com/<your-tenant>",
                  redirectUri: "http://localhost:8848/msalTest/index.html",
                },
                cache: {
                  cacheLocation: "sessionStorage", // This configures where your cache will be stored
                  storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
                }
              };
            
            const myMSALObj = new Msal.UserAgentApplication(msalConfig);
            
            //at first, I used scope like ["openid", "profile", "User.Read", "https://vault.azure.net/user_impersonation"]
            //but with this accesstoken, I got the same error as yours
            //and I try to use the scope below, and it worked 
            //I decode the token with jwt, when I get error, the token didn't contains correct scope
            const loginRequest = {
                scopes: ["openid", "profile", "https://vault.azure.net/user_impersonation"],
            };
            
            function showWelcome(){
                myMSALObj.loginPopup(loginRequest)
                    .then((loginResponse) => {
                        console.info(loginResponse);
                        console.log("========= myMSALObj.getAccount() =======");
                        console.log(myMSALObj.getAccount());
                        $("#userName").val(myMSALObj.getAccount().name);
                        getAccessToken();
                    //Login Success callback code here
                }).catch(function (error) {
                    console.log(error);
                });
            }
            
            function getAccessToken(){
                getTokenPopup(loginRequest)
                      .then(response => {
                        $("#accessToken").text(response.accessToken);
                      }).catch(error => {
                        console.log(error);
                      });
            }
            
            function getTokenPopup(request) {
              return myMSALObj.acquireTokenSilent(request)
                .catch(error => {
                  console.log(error);
                  console.log("silent token acquisition fails. acquiring token using popup");
            
                  // fallback to interaction when silent call fails
                    return myMSALObj.acquireTokenPopup(request)
                      .then(tokenResponse => {
                        return tokenResponse;
                      }).catch(error => {
                        console.log(error);
                      });
                });
            }
            
        </script>
    </body>
</html>

这篇关于如何从 keyvault 访问秘密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆