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

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

问题描述

我创建了示例反应登录应用程序,用户可以通过引用此

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

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

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

这是我的登录代码

 从"msal"导入{UserAgentApplication}类Login扩展了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上遇到问题}});this.state = {错误:null,isAuthenticated:否,用户:{}};}登录=异步()=>{尝试 {//通过弹出窗口登录等待this.userAgentApplication.loginPopup({范围:config.scopes,提示:"select_account"});//登录后,获取用户的个人资料等待this.getUserProfile();var user = this.userAgentApplication.getAccount();}抓(err){console.log("errror",err.message)this.setState({isAuthenticated:否,用户:{},错误:err.message});}}注销=()=>{this.userAgentApplication.logout();}getUserProfile = async()=>{尝试 {const data =等待this.userAgentApplication.acquireTokenSilent({范围:config.scopes});如果(data.accessToken){console.log(令牌",data.accessToken);this.token = data.accessToken;this.expiresOn = data.expiresOn;}}抓(err){console.log("err",err.message);}}使成为() {const {isLogin} = this.props;const buttonTitle = isLogin吗?注册":登录";返回 (< form className ="login-form">{!isLogin&&< IconButton backgroundColor =#0A66C2";font ="14px"width = '35%'padding ='8px'microsoftLoginHandler = {this.login}/>}</form>);}} 

当我尝试从邮递员访问hit api时获得访问令牌.它显示了一些错误.任何人都可以指导我解决此错误,因为我是Azure广告和Keyvault的新手

预先感谢

解决方案

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

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

 <!DOCTYPE html>< html>< head><元字符集="utf-8";/>< title></title>< script src =" js/jquery-1.10.2.min.js"</script>< script type ="文本/javascript"src =" https://alcdn.msftauth.net/lib/1.2.1/js/msal.js"完整性="sha384-9TV1245fz + BaI + VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP"crossorigin =匿名"</script></head><身体>< button id ="btn">单击</button>< div>userName:<输入类型=文本";id ="userName";/></div>< div id ="accessToken">//div< script type =文本/javascript">$(#btn").click(function(){showWelcome();})const msalConfig = {身份验证:{clientId:<您的azure广告应用程序ID>",//请使用azure密钥库添加api权限授权:"https://login.microsoftonline.com/<您的租户>",redirectUri:"http://localhost:8848/msalTest/index.html",},缓存:{cacheLocation:"sessionStorage",//这将配置缓存的存储位置storeAuthStateInCookie:否,//将其设置为"true";如果您在IE11或Edge上遇到问题}};const myMSALObj =新的Msal.UserAgentApplication(msalConfig);//首先,我使用了[[openid],"profile","User.Read","https://vault.azure.net/user_impersonation"]这样的范围//但是有了这个访问令牌,我遇到了与您相同的错误//并且我尝试使用下面的范围,它起作用了//我用jwt解码令牌,当出现错误时,令牌没有包含正确的作用域const loginRequest = {范围:["openid",个人资料","https://vault.azure.net/user_impersonation"],};函数showWelcome(){myMSALObj.loginPopup(loginRequest).then((loginResponse)=> {console.info(loginResponse);console.log("========= myMSALObj.getAccount()======="));console.log(myMSALObj.getAccount());$(#userName").val(myMSALObj.getAccount().name);getAccessToken();//在这里登录成功回调代码}).catch(函数(错误){console.log(错误);});}函数getAccessToken(){getTokenPopup(loginRequest).then(response => {$(#accessToken").text(response.accessToken);}).catch(错误=> {console.log(错误);});}函数getTokenPopup(request){返回myMSALObj.acquireTokenSilent(request).catch(错误=> {console.log(错误);console.log(静默令牌获取失败.使用弹出窗口获取令牌");//静音呼叫失败时回退到交互返回myMSALObj.acquireTokenPopup(request).then(tokenResponse => {返回tokenResponse;}).catch(错误=> {console.log(错误);});});}</script></body></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>

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

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