Aspnet Web api integrate with azureAD and graph api

nuget packages needed:
Microsoft.Azure.ActiveDirectory.GraphClient
Microsoft.IdentityModel.Clients.ActiveDirectory

this C# sample including :
1. login with username/password to get accesstoken和idtoken
2. refresh token using idtoken
3. call graphapi to get more information of user

<br />internal class AzureADGlobalConstants
{
public const string AuthString = "https://login.microsoftonline.com/";
public const string ResourceUrl = "https://graph.windows.net";
public const string GraphServiceObjectId = "00000002-0000-0000-c000-000000000000";
}

public class CertisAdLoginController : ApiController
{
public class LoginResult
{
public bool IsSuccess { get; set; }
public string ErrorMessage { get; set; }
public object Data { get; set; }
public IUser UserDetail { get; set; }
}
internal class AzureADAppConstants
{
/// <summary>
/// The application id ,you can login to azure portal ->
/// Azure Active Directory ->
/// Registered Apps -> click the app
/// </summary>
public const string ClientId = "your_app_id";

/// <summary>
/// Login to your azure portal ->
/// Azure Active Directory ->
/// Registered Apps -> click the app
/// keys -> add new
/// </summary>
public const string ClientSecret = "your_app_key";

/// <summary>
/// this is used to construct the login user name:
/// e.g. someone@xxx.onmicrosoft.com
/// </summary>
public const string TenantName = "yourdomain@onmicrosoft.com";

/// <summary>
/// you can get this value form below steps :
/// Login to your azure portal ->
/// Azure Active Directory ->
/// Properties -> DirectoryId
/// </summary>
public const string TenantId = "your_tenant_id";
}

/// <summary>
/// Login with idToken
/// </summary>
/// <param name="idToken"></param>
/// <returns></returns>
[HttpPost]
public IHttpActionResult Login(string idToken)
{
try
{
string directoryName = AzureADAppConstants.TenantName;
string clientId = AzureADAppConstants.ClientId;
var credentials = new UserAssertion(idToken);
var authenticationContext = new AuthenticationContext(AzureADGlobalConstants.AuthString + directoryName);
var result = authenticationContext.AcquireTokenAsync(AzureADGlobalConstants.ResourceUrl, clientId, credentials).Result;
var tokenGetter = Task.Run(() => { return result.AccessToken; });
// get more details
var userDetail = GetUserDetailById(tokenGetter, result.UserInfo.UniqueId);

return Ok(new LoginResult()
{
IsSuccess = true,
Data = result,
ErrorMessage = "",
UserDetail = userDetail
});
}
catch (Exception ex)
{
return Ok(new LoginResult()
{
IsSuccess = false,
ErrorMessage = ex.Message
});
}
}

/// <summary>
/// Login with username/password
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
[HttpPost]
public IHttpActionResult Login(string username, string password)
{
try
{
string directoryName = AzureADAppConstants.TenantName;
string clientId = AzureADAppConstants.ClientId;
var credentials = new UserPasswordCredential(string.Format("{0}@{1}", username, directoryName), password);
var authenticationContext = new AuthenticationContext(AzureADGlobalConstants.AuthString + directoryName);
var result = authenticationContext.AcquireTokenAsync(AzureADGlobalConstants.ResourceUrl, clientId, credentials).Result;
var tokenGetter = Task.Run(() => { return result.AccessToken; });
// get more details
var userDetail = GetUserDetailById(tokenGetter, result.UserInfo.UniqueId);

return Ok(new LoginResult()
{
IsSuccess = true,
Data = result,
ErrorMessage = "",
UserDetail = userDetail
});
}
catch (Exception ex)
{
return Ok(new LoginResult()
{
IsSuccess = false,
ErrorMessage = ex.Message
});
}
}

 

private IUser GetUserDetailById(Task<string> accessToken, string userid)
{
Uri servicePointUri = new Uri(AzureADGlobalConstants.ResourceUrl);
Uri serviceRoot = new Uri(servicePointUri, CertisAdLoginController.AzureADAppConstants.TenantId);
ActiveDirectoryClient client = new ActiveDirectoryClient(serviceRoot, () =>
{
return accessToken;
});

 

IUser firstMatch = null;
try
{
IUserCollection userCollection = client.Users;
firstMatch = userCollection.Where(user =>
user.ObjectId == userid)
.Take(10).ExecuteAsync().
Result.CurrentPage.First();

return firstMatch;
}
catch (Exception e)
{
return null;
}
}

 

}

full sample:
github sample

 

Author: lanliang

Programmer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s