16
votes

I have a REST API written in C# and I need to authenticate with an existing Azure AD service. I currently have the username and password of the user wishing to authenticate. I need to authenticate with Azure AD and receive an access token from the server.

Can someone please point me in the direction of some articles/tutorials that explain how to do this?

2
You mean how to use OAuth 2.0 with Azure AD? The call-by-call process is described here. The Azure AD Authentication Library simplifies this processPanagiotis Kanavos
Thanks - this is exactly what I neededCOBOL
The fact that you mention having the users credentials makes me nervous. Could you add a bit more detail to your question. Is the scenario: native app -> your REST API -> Azure AD Rest API. Or is it: Web App -> your REST API -> Azure AD Rest API. Or something else. Depending on the exact scenario I can point you at samples that will prevent you from ever needing to handle the users credentials, which would be much safer from a security standpoint.Rich Randall

2 Answers

17
votes

You should avoid handling the users credentials. There are serious security implications when collecting a users credentials that are mitigated by using OAuth 2.0 or OpenID Connect to get a token without directly handling the credentials. Also, if you have your own credential collection UI then you may find that sign in fails in the future if multi-factor authentication is turned on. In that case, more information may be necessary to authenticate the user than you are collecting, a one time password for instance. If you allow Azure AD to present the authentication experience via OAuth 2.0 or OpenID Connect, then you are insulated from the specific authentication method being employed. Collecting the users Azure AD credentials is a bad practice to be avoided if at all possible.

I don't have enough detail on the exact scenario to be confident that the following sample applies, but it will at least provide a good starting point. This sample shows how to create a native app that calls a REST API that can then call an Azure resource in the safest way possible.

https://github.com/AzureADSamples/WebAPI-OnBehalfOf-DotNet

You can find lots of other samples here that can be used to construct a solution for your particular scenario.

https://github.com/AzureADSamples

If you provide some more detail I can give more specific guidance.

4
votes

See: http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/

Summary: Create a UserCredential

UserCredential uc = new UserCredential(user, password);

Call one of the AcquireToken() functions with the UserCredential

public AuthenticationResult AcquireToken(string resource, string clientId, UserCredential userCredential);
public Task<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, UserCredential userCredential);