Jif
Jif

Reputation: 843

Unable to authenticate web api with Bearer Token

I'm currently working on a project where I have a Web API that uses the Graph API to create accounts in my Azure AD and put them in the correct group as well.

Next to that I have several API calls exposed that will be called by a native iOS app as well as an angularJS web app. The client has concocted some weird way of doing the authentication because he firmly believes his users to be utter morons.

The client is handing custom prepped iOS devices to certain people. The device has an Azure AD User(principal) and password. Once they are handed out, some process on the angularJS web app does this, the app will then call my token controller that looks like this:

    public async Task<string> GetTokenForUserAsync(string userPrincipalName, string password)
    {
        var uri = string.Format("{0}/oauth2/token", AuthString);
        using (var httpClient = new HttpClient
        {
            DefaultRequestHeaders = { Accept = { new MediaTypeWithQualityHeaderValue("application/json") } }
        })
        {
            var values = new Dictionary<string, string>
            {
                {"resource", GraphUrl },
                {"client_id", ClientId },
                {"client_secret", ClientSecret },
                {"grant_type", "password" },
                {"username", userPrincipalName },
                {"password", password },
                {"scope", "openid" }
            };

            var content = new FormUrlEncodedContent(values);
            var response = await httpClient.PostAsync(uri, content);

            var responseContent = await response.Content.ReadAsStringAsync();

            return responseContent;
        }

The passed parameters are, not 100% exact, but very alike:

So this call actually provides me with an access_token. The problem that I'm having is that the tokens I get are never authorized. I've tried several Startup setups, but none are working.

Currently I've got the following code in my Startup.Auth.cs

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudience = ConfigurationManager.AppSettings["ida:ClientId"]
            }

        });
        //app.UseWindowsAzureActiveDirectoryBearerAuthentication(
        //    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        //    {
        //        TokenValidationParameters = new TokenValidationParameters
        //        {
        //            ValidAudience = ConfigurationManager.AppSettings["ida:ClientId"]
        //        },
        //        Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
        //    });
    }

It's the first time that I'm working with Azure and Active Directory. So I'm probable doing something really stupid. At this moment in time I don't care much about styling and 'the right way'. I just want this thing to work :,/

Hope I described my problem correctly and documented my question accordingly. If you have any questions, please don't hesitate to ask!

Thanks a bunch in advance

Upvotes: 0

Views: 958

Answers (1)

Lily_user4045
Lily_user4045

Reputation: 793

I dont think you can get accesstoken from var values = new Dictionary { {"resource", GraphUrl }, {"client_id", ClientId }, {"client_secret", ClientSecret }, {"grant_type", "password" }, {"username", userPrincipalName }, {"password", password }, {"scope", "openid" } }; so you could try other methods:

       AuthenticationContext aContext =
                new AuthenticationContext("https://login.microsoftonline.com/tenantid");
            AuthenticationResult aResult =
                aContext.AcquireToken("https://graph.windows.net",
                                "1950a258-227b-4e31-a9cf-717495945fc2",
                                new UserCredential(UserId, PasswordId));

            string result = string.Empty;
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", aResult.AccessToken);
            HttpResponseMessage response =
                httpClient.GetAsync("https://graph.windows.net/tenantid/users/userid?api-version=1.6").Result;

            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;
            }
            Console.WriteLine(result);
            Console.ReadLine();

Upvotes: 0

Related Questions