Search code examples
c#oauth-2.0postmanmicrosoft-identity-platform

Make OAuth 2 Authorization Code Grant/Flow without user intervention


Trying to access an API resource that requires the Grant Type Authorization code. I can get back a valid Access Code using Postman and it's Authorization tool.

enter image description here

This involves Postman popping up a login window where I enter the username and password.

How can I accomplish this purely problematically without user intervention? This Grant Type seems to be the only one that works with this API as when I just try and use the client_id and client_secret with the Client Credentials flow the Access Token I get back does not allow me into the API (401).

I am looking to do this as code agnostic as possible. That is I would like to be able to do it without relying a library that does things behind the scenes. Ideally everything would be done via HTTP like with cURL.

I have some C# code that does what I am looking for but it makes use of the Microsoft.IdentityModel.Clients.ActiveDirectory library (older version 2.29.0.1078). It seems to be able to get a token by passing in the username and password

string userName = "johndoe";
string password = "mydoghasfleas";
string clientId = "7934579357js487dhj444";
clientBaseUrl = "https://mycompanyname.dynamics.com";
apiEndpointUrl = clientBaseUrl + "/data/resource=XYZ";

UserCredential credential = new UserCredential(userName, password);
AuthenticationContext authContext = new AuthenticationContext(apiEndpointUrl, false);
AuthenticationResult authResult = await authContext.AcquireTokenAsync(clientBaseUrl, clientID, credential);

What I am trying to figure out is how to do it without depending on the Microsoft.IdentityModel.Clients.ActiveDirectory library.


Solution

  • If it was one of your APIs, the correct approach would be to add support for client credentials auth and app permissions in the API. Seeing that it's probably Dynamics, that's probably not possible for you. In that case, you can use authorization code flow to get initial tokens for a user, and then you can use the refresh token to get a new token when needed. In the final case, you can use Resource Owner Password Credentials flow to get tokens. But beware, this flow does not support MFA etc.