Microsoft-graph-docs: Authentication without user interaction (grant_type = password) not working

Created on 17 May 2018  路  17Comments  路  Source: microsoftgraph/microsoft-graph-docs

Hi,
I am working on a Onedrive CoAuthoring Application. In which users can Co-Author the document and Sync their changes. The application flow is the First user initiates the CoAuthoring, the document will be moved from Source to Onedrive. For the subsequent users, Permission will be added for those users and they open the document directly from OneDrive so everybody can work on the same document and the final user will sync back it from OneDrive to Source. In my server end, I am using service account which talks to Onedrive on behalf of a user and adds permission to another user whenever its necessary.

I have implemented a PoC by creating office 365 trial accounts.
I have created the app here - https://apps.dev.microsoft.com with necessary Graph permissions.
I have hardcoded the Admin account User credentials, and the admin account will talk to Onedrive on behalf of the user using Microsoft Graph and Coauthoring works perfectly.
I am getting the Access Token using the following Code and talking to Onedrive API using GraphClient and everything works well.

 private static async Task<string> GetAccessTokenAsync(OneDriveSettings oneDriveSettings)
        {
            using (var client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(new[]
                {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("resource", "https://graph.microsoft.com"),
                new KeyValuePair<string, string>("username", oneDriveSettings.ServiceAccountUserName),
                new KeyValuePair<string, string>("password", oneDriveSettings.ServiceAccountPassword),
                new KeyValuePair<string, string>("client_id", oneDriveSettings.ClientId)

                var result = await client.PostAsync("https://login.microsoftonline.com/xxx.onmicrosoft.com/oauth2/token", content);
                string resultContent = await result.Content.ReadAsStringAsync();
                var jsonResult = JObject.Parse(resultContent);
                return jsonResult["access_token"].ToString();
            }
        }

I have followed the same pattern for the real app. I have service account credentials. and created app under https://apps.dev.microsoft.com but I am getting the following exception:

AADSTS65001: The user or administrator has not consented to use the application with ID

authentication by design stack overflow

Most helpful comment

This isn't supported by Azure AD's v2 Endpoint. From the documentation:

The OAuth 2.0 Resource Owner Password Credentials Grant is not supported by the v2.0 endpoint.

All 17 comments

This isn't supported by Azure AD's v2 Endpoint. From the documentation:

The OAuth 2.0 Resource Owner Password Credentials Grant is not supported by the v2.0 endpoint.

Thanks for your reply.
But how come the same endpoints are working for the trial accounts.

if i want to use the admin consent what is the privilege I need to give it to the user in Azure AD.

Thanks,
Subbiah K

The v2 Endpoint doesn't support this OAuth grant. The error text you're getting is simply misleading. It isn't possible to add support for the Password Grant using Admin Consent (or any other mechanism).

My question is how its working for the trial account I have created. The only differnce between the trial account and service account is, for Trail account Directory Role is Global Administrator where as for the service account is User.

Based on the code sample, you're attempting to authenticate a v2 App against the v1 Endpoint. This won't work regardless of your grant. I suspect the account you have that worked was using an v1 App registered in the Azure Portal, not a v2 App registered at apps.dev.microsoft.com

i dint register it in Azure portal. I have registered the app in https://apps.dev.microsoft.com . I dnit see this app in Azure portal.

Sorry i am new to Azure,

If you've registered in apps.dev.microsoft.com then you're using the v2 Endpoint and you need to use a different set of parameters and URIs to authenticate. Take a look at https://massivescale.com/microsoft-v2-endpoint-primer/ for an overview of how this works.

Hi,

Following this thread, it stopped working our grant_type=password integration (it was working last Friday 18/05/2018).
Now he have done some tests and we have checked that is working for some users, and not working for others (I can confirm the credentials are ok)

Not Working example:

POST https://login.microsoftonline.com/organizations/oauth2/v2.0/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
cache-control: no-cache
Postman-Token: bba7d3b5-bed7-4f5e-b442-83567cc5686e
User-Agent: PostmanRuntime/7.1.1
Accept: */*
Host: login.microsoftonline.com
cookie: MSCC=1518509850; wlidperf=FR=L&ST=1518513695441; x-ms-gateway-slice=019; stsservicecookie=ests; esctx=AQABAAAAAABHh4kmS_aKT5XrjzxRAtHzdeGgdSM2r48fIWmZaK34rjw0_3BWMO0KI-OSqApSw-iL22nnzxbX6IFOzTXO-XgNM4uE3NAFbOyNBrC9ce9NmH1_e6nsicYR3oGVj2hcSM7bgDBjR8TnFO7wvfUgIRJ37V_tMt9TMWpHdU5afsX0fuQ8Uiez0wMeAeiY38OWOKEgAA
accept-encoding: gzip, deflate
content-length: 213
Connection: close

grant_type=password&password=xxx&client_id=fd6036fc-b82b-4e19-87b3-4b1bd1557213&scope=files.readwrite.all&client_secret=yyy&username=jaume3%40ws102.party
HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: 1e5ac71a-6529-49b1-98d1-498502aa2600
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: x-ms-gateway-slice=002; path=/; secure; HttpOnly
Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly
X-Powered-By: ASP.NET
Date: Tue, 22 May 2018 13:40:04 GMT
Connection: close
Content-Length: 442

{"error":"invalid_grant","error_description":"AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password\r\nTrace ID: 1e5ac71a-6529-49b1-98d1-498502aa2600\r\nCorrelation ID: 1ffb3033-1a97-45d6-9196-47efcd898426\r\nTimestamp: 2018-05-22 13:40:04Z","error_codes":[70002,50126],"timestamp":"2018-05-22 13:40:04Z","trace_id":"1e5ac71a-6529-49b1-98d1-498502aa2600","correlation_id":"1ffb3033-1a97-45d6-9196-47efcd898426"}

Working Example:

POST https://login.microsoftonline.com/organizations/oauth2/v2.0/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
cache-control: no-cache
Postman-Token: 3e1bbf04-1ca4-4645-ae87-a0e140a302c7
User-Agent: PostmanRuntime/7.1.1
Accept: */*
Host: login.microsoftonline.com
cookie: MSCC=1518509850; wlidperf=FR=L&ST=1518513695441; x-ms-gateway-slice=002; stsservicecookie=ests; esctx=AQABAAAAAABHh4kmS_aKT5XrjzxRAtHzdeGgdSM2r48fIWmZaK34rjw0_3BWMO0KI-OSqApSw-iL22nnzxbX6IFOzTXO-XgNM4uE3NAFbOyNBrC9ce9NmH1_e6nsicYR3oGVj2hcSM7bgDBjR8TnFO7wvfUgIRJ37V_tMt9TMWpHdU5afsX0fuQ8Uiez0wMeAeiY38OWOKEgAA
accept-encoding: gzip, deflate
content-length: 230
Connection: close

grant_type=password&username=api%40ws102enablement.onmicrosoft.com&password=xxx&client_id=fd6036fc-b82b-4e19-87b3-4b1bd1557213&scope=files.readwrite.all&client_secret=yyy
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: 5bd7b2dc-8581-407a-9971-2614bb233800
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: x-ms-gateway-slice=019; path=/; secure; HttpOnly
Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly
X-Powered-By: ASP.NET
Date: Tue, 22 May 2018 13:41:25 GMT
Connection: close
Content-Length: 1991

{"token_type":"Bearer","scope":"Calendars.ReadWrite Contacts.Read Files.ReadWrite.All Mail.ReadWrite Mail.Send Sites.ReadWrite.All User.Read","expires_in":3599,"ext_expires_in":0,"access_token":"eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFEWDhHQ2k2SnM2U0s4MlRzRDJQYjdyMzZoOUZlWU03RXlieWRDeGxONkl5NGx1R3JHVE4xbzRhblNMUmhvTS04cUdhYkJnTVlkdzAtU0FsMXJVREhhZFdhNWFmRzhEQWNuT1hPM0RzaS00NmlBQSIsImFsZyI6IlJTMjU2IiwieDV0IjoiaUJqTDFSY3F6aGl5NGZweEl4ZFpxb2hNMllrIiwia2lkIjoiaUJqTDFSY3F6aGl5NGZweEl4ZFpxb2hNMllrIn0.eyJhdWQiOiJodHRwczovL2dyYXBoLm1pY3Jvc29mdC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9mNDQzZmEyZi1mMzg1LTQyZDMtYTI0MC0xYWMyOWU3MzJiMDIvIiwiaWF0IjoxNTI2OTk2MTg2LCJuYmYiOjE1MjY5OTYxODYsImV4cCI6MTUyNzAwMDA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a-gcthcFRfEfePtznqxbgAhYynExxel19pgwgLADpzQd46_Hev7kqYg-SnrWlT0libgET0ctZfA_COfRZ4cttaS1lcJpzGVV3gb0hy5EMVrP8S9DISQnhcIxI6NrTQbQdHFstsEolrhqVdO2O_5ZFnUJs4RNX1EgjgxUlGe_yp3aVgc7t2RtMa9AeZFKtrBTVzlWw_LbGUMe-RMwCw6M6IVVUc2qFDvRxLvPnftxMOCg"}

NOTE: All users working are from domain ws102enablement.onmicrosoft.com and the not working ones from ws102.party

Do you know if something has changed in the API the lasts days?

Regards,
Jaume

I'm not aware of any changes but, based on the documentation, the "working example" would be the outlier:

The OAuth 2.0 Resource Owner Password Credentials Grant is not supported by the v2.0 endpoint.

In general, using the Resource Own Password Credentials Grant is a bad habit to get into. Unless your application is requesting the password at runtime, it is highly at risk of being compromised. The canonical use case for this grant is an interactive console application where redirecting to a URL isn't a viable option. It was never intended, and should never be used for, daemon/service applications that run unintended in the background. For service-to-service/daemon scenarios, you should use Client Credentials which can be secured by a certificate.

Hi, thanks for the answer

Yes, we are aware about the risk of the grant_type=password. And that it is not documented for the v2.0 endpoint.

In any case, in our scenario it is a server to server call, but we want to get an access token valid for the context of the user that is logged into our application. So we can't use the Client Credentials type (if I well understood is like a master or admin token for perform all actions)

The issue, is that it was working 2 weeks ago, and it has stopped working for some users last week.

Do you think is there any other option we can use in order to not prompt the user for authorization?

Regards,
Jaume

The scenario you are describing can be done using an Authorization Code grant and Refresh Tokens. The user would need to authenticate once. Your service then stores the Refresh Token and exchanges it for a live token as needed.

Event with the Password grant, you still need to prompt the user for a password. The key difference being who owns the responsibility for protecting the credentials, and the liability if those credentials get compromised. Using Auth Code ensures you are only responsible for protecting a Refresh Token and your Client Secret (without which the Refresh Token is worthless).

Hi,

We already have the authorization code grant integrated with the product, but we wanted to offer our customers to avoid the authorization page (the first time it is used).

In fact, we have our environments federated with Office365, and we are using our Idp in order to login into Office365, so we don't really require the user/password to the users for interact with Office365 (they just need to be logged into our product).

Then, with the password grant, the user doesn't need to authorize, even in the first time, as the permissions are already granted previously by an administrator. We did some tests in the past and (even without being documented) they worked for us. Now they have stop working

Regards,
Jaume

I'm sorry to have to do this to you. We have a new triage process that our customer experience team are monitoring on our official channel for questions. This is StackOverflow with 'microsoft-graph' tag.
I was trying not to close these off here in the documentation GitHub issues repo and get them answered. This issues lists is specifically for documentation issues, not the underlying service, sdks or samples.
It's proving too hard for me to be single point of failure here in assigning the correct engineers to answer questions. It is best for questions to go on StackOverflow where they'll be monitored by a dedicated team and escalated internally to PMs through a defined process.

This isn't supported by Azure AD's v2 Endpoint. From the documentation:

The OAuth 2.0 Resource Owner Password Credentials Grant is not supported by the v2.0 endpoint.

Hi @mlafleur , Is this feature still not supported by v2.0 endpoint ? Can I use Azure AD endpoint with this grant type ?

Hi @subbiahkk , Were you able to solve this issue ? I need a slient backend approach to fetch access token too. Haven't found a way to do this.

Hi @subbiahkk , Were you able to solve this issue ? I need a slient backend approach to fetch access token too. Haven't found a way to do this.

Yes its working, did not change anything all of a sudden It works. Happy Coding Microsoft Rocks :)

@subbiahkk are you able to shed any light no what your issue was caused by? seeing the same issue and using the Microsoft.Graph samples; all I can think is that the application or tenant is incorrectly configuration or the endpoint is wrong? any help would be great.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

GregSpyra picture GregSpyra  路  4Comments

abhatt29 picture abhatt29  路  4Comments

bijithbalan picture bijithbalan  路  4Comments

andrewfabrizi picture andrewfabrizi  路  3Comments

r3dh0t picture r3dh0t  路  4Comments