Search code examples
asp.netazureaccess-tokenazure-authentication

Fetching user based access token using grant type as password


I am trying to retrieve access token by using user credential.

I am using AcquireTokenAsync method for retrieving the token where I am using constructor with resource, client id and user credential as parameter.

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;
        }
    }

I am expecting access token to be returned but I am getting an exception while acquiring token. Below is the error message I am getting.

AdalException: {"error":"invalid_client","error_description":"AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.\r\nTrace ID: 674f29fe-73c6-49a3-9c3f-24df4ea16000\r\nCorrelation ID: b14cb535-9df5-48fa-b911-7e8b927fceb7\r\nTimestamp: 2019-11-08 06:21:57Z","error_codes":[7000218],"timestamp":"2019-11-08 06:21:57Z","trace_id":"674f29fe-73c6-49a3-9c3f-24df4ea16000","correlation_id":"b14cb535-9df5-48fa-b911-7e8b927fceb7","error_uri":"https://login.microsoftonline.com/error?code=7000218"}: Unknown error

Solution

  • This is the code i am using to fetch token. This is what i wanted to retrieve the access token.

            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),
            new KeyValuePair<string, string>("password", password),
            new KeyValuePair<string, string>("client_id", authmodel.ClientId),
            new KeyValuePair<string, string>("client_secret", authmodel.ClientSecret),
            new KeyValuePair<string, 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();
    
                }
    

    I am getting access token in json variable with other details. If you want to fetch the token value, then you can deserialize it to .net Object and get the value.