使用授予类型作为密码获取基于用户的访问令牌

我正在尝试通过使用用户凭证来检索访问令牌。

我正在使用AcquireTokenAsync方法来检索令牌,而我正在使用以资源,客户端ID和用户凭据作为参数的构造函数。

pl_id=MDR_PLZ
ln_id=01N
dt_concluded=20191106115958796600
tx_seq_nr=122586
ts_seq_nr=1078
us_id=c0507387

我期望返回访问令牌,但是获取令牌时出现异常。以下是我收到的错误消息。

public async Task<IHttpactionResult> GetToken()
    {
        AuthenticationResult authenticationResult = null;
        try
        {
            string authority = "https://login.microsoftonline.com/tenant";
            string resource ="2424-234-234234-234-23-32423";
            string username = "yxyzzz";
            string password = "password";
           string clientId="2424-234-234234-234-23-32423";
            var useridpassword = new UserPasswordCredential(username,password);
            AuthenticationContext context = new AuthenticationContext(authority);
            context.TokenCache.Clear();
            authenticationResult = await context.AcquireTokenAsync(resource,clientId,useridpassword);
            return authenticationResult.accessToken;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
heiseseo 回答:使用授予类型作为密码获取基于用户的访问令牌

要使用资源所有者密码凭证,您需要将应用程序视为公共客户端。

转到Azure门户->应用程序注册->查找应用程序->检查高级设置

enter image description here

,

这是我用来获取令牌的代码。这就是我想要检索访问令牌的方法。

        string authority = "https://login.microsoftonline.com/tenant";
        string resource ="2424-234-234234-234-23-32423";
        string username = "yxyzzz";
        string password = "password";
       string clientId="2424-234-234234-234-23-32423";
            string tokenEndpointUri = authority + "/oauth2/token";
            var content = new FormUrlEncodedContent(new[]
                {
        new KeyValuePair<string,string>("grant_type","password"),new KeyValuePair<string,string>("username",username),string>("password",password),string>("client_id",authmodel.ClientId),string>("client_secret",authmodel.ClientSecret),string>("resource",resource)
    }
            );
            using (var client = new HttpClient())
            {
                HttpResponseMessage res = null;
                    client.PostAsync(tokenEndpointUri,content).
                    ContinueWith(t =>
                    {
                        try
                        {
                            res = t.Result;
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    })
                    .Wait();

                string json = await res.Content.ReadAsStringAsync();

            }

我正在json变量中获取访问令牌以及其他详细信息。如果要获取令牌值,则可以将其反序列化为.net Object并获取该值。

本文链接:https://www.f2er.com/3139845.html

大家都在问