I’ve been working in the last weeks in an integration service for a complex system based on Azure.
I was trying to find a way to authenticate in the Azure Directory, basically getting the access token for the future requests to the system without the login popup window from Microsoft, very usual to see in similar cases, like integrations with Facebook or other services.
Microsoft Azure Active Directory (AD) has already an authentication library (ADAL), but unfortunately nothing for the language I was using at the moment, GoLang. Faced with this situation, I was forced to find a solution.
OAuth 2 is an protocol for authorization that enables applications to obtain limited access to the users accounts on an HTTP service.
I will not explain here the all protocol, you can check it here, just the authorization grant types.
OAuth 2 has four grant types.
- Client credentials
- Authorization Code
With this information and to solve my problem I choose the Password Grant.
For similar scenarios, when you have trusted first party or third party clients both on web and in native applications this offers to the final user the best experience.
For more information about OAuth2.0 you can read here.
Microsoft Azure Active Directory and OAuth 2
At this point I start to look on how to use this Password grant type in Azure AD and the documentation from Microsoft it’s not useful. They only focus on the others grant flows used in different scenarios, for example:
- Authorization Code for Web Server application
- Implicit Grant for native application
- Client Credentials for Service application
But Resource Owner Password Credentials Grant type is also supported since version 1.1 in Azure AD.
This is also based on http request but without URL redirection, for more information about this flow you can read here.
So for this specific case, when we have an integration service, ex. a windows service, to get information from a trust target application, this is the best option.
How to use
To use this method to get the token in Azure AD OAuth 2, we need to use the following web service request:
- Content-Type: application/x-www-form-urlencoded
- Host: login.microsoftonline.com
- TenantId: <MY_HOST> (for example “mywebsite.com”)
- WS: /oauth2/token
Parameters to use in Body request:
- grant_type: password
- client_id: The Client Id value from Azure AD
- resource: The app id value of the application you want an access token to
- client_secret: The Client Secret value from Azure AD
- username: The user name of a user account in the Azure AD instance
- password: The password of the user account
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Finally you have your token to use in your application.
Have you ever had this need in something similar, have another approach? Please let me know.
I hope this information will be useful for any future development.