Wednesday, 22 August 2018

Azure Active Directory Token With Create User and Login


#region

using System;
using System.Threading.Tasks;
using System.Web.WebPages;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Web;
using satya.Models;

#endregion

namespace satyya.Utils
{
    internal class AuthenticationHelper
    {
        public static string TokenForUser;


        /// <summary>
        /// Get Token for Application.
        /// </summary>
        /// <returns>Token for application.</returns>
        public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication(HttpSessionStateBase session)
        {
            Uri servicePointUri = new Uri(Constants.ResourceUrl);
            Uri serviceRoot = new Uri(servicePointUri, Constants.TenantId);
            ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
                async () => await AcquireTokenAsyncForApplication(session));
            return activeDirectoryClient;
        }

        public static async Task<string> AcquireTokenAsyncForApplication(HttpSessionStateBase session)
        {
            AuthenticationResult token = null;
            if (session != null && session["token"] != null)
            {
                token = session["token"] as AuthenticationResult;
            }

            AuthenticationResult authenticationResult = null;

            var futureTime = DateTimeOffset.UtcNow.AddMinutes(2);
            // Fetch a token if it has not been fetched earlier or if the token is about to expire in 2 mins
            if (token == null || (futureTime.UtcDateTime > token.ExpiresOn.UtcDateTime))
            {
                AuthenticationContext authenticationContext = new AuthenticationContext(Constants.AuthString, false);
                // Config for OAuth client credentials
                ClientCredential clientCred = new ClientCredential(Constants.ClientId, Constants.ClientSecret);
                authenticationResult = await authenticationContext.AcquireTokenAsync(Constants.ResourceUrl,
                   clientCred);
                token = authenticationResult;
                if (session != null)
                {
                    session["token"] = authenticationResult;
                }
            }
            if (token == null)
            {
                return null;
            }

            // Configure a AADJWTToken using the ADAL token
            var aadToken = new AADJWTToken();
            aadToken.AdalToken = token;
            aadToken.AccessToken = token.AccessToken;
            aadToken.TokenType = token.AccessTokenType;

            return token.AccessToken;
        }


        /// <summary>
        /// Async task to acquire token for User.
        /// </summary>
        /// <returns>Token for user.</returns>
        public static async Task<string> AcquireTokenAsyncForUser()
        {
            return GetTokenForUser();
        }

        /// <summary>
        /// Get Token for User.
        /// </summary>
        /// <returns>Token for user.</returns>
        public static string GetTokenForUser()
        {
            if (TokenForUser == null)
            {
                var redirectUri = new Uri("https://localhost");
                AuthenticationContext authenticationContext = new AuthenticationContext(Constants.AuthString, false);
                AuthenticationResult userAuthnResult = authenticationContext.AcquireToken(Constants.ResourceUrl,
                    Constants.ClientId, redirectUri, PromptBehavior.Always);
                TokenForUser = userAuthnResult.AccessToken;
                Console.WriteLine("\n Welcome " + userAuthnResult.UserInfo.GivenName + " " +
                                  userAuthnResult.UserInfo.FamilyName);
            }
            return TokenForUser;
        }


        /// <summary>
        /// Get Active Directory Client for User.
        /// </summary>
        /// <returns>ActiveDirectoryClient for User.</returns>
        public static ActiveDirectoryClient GetActiveDirectoryClientAsUser()
        {
            Uri servicePointUri = new Uri(Constants.ResourceUrl);
            Uri serviceRoot = new Uri(servicePointUri, Constants.TenantId);
            ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
                async () => await AcquireTokenAsyncForUser());
            return activeDirectoryClient;
        }
    }
}
Next got to Controller
#region Azure AD
// Create New User
            ActiveDirectoryClient activeDirectoryClient;
            activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication(this.HttpContext.Session);

            IUser userToBeAdded = new User();

            Session["DomainNames"] = "satya.co";
            userToBeAdded.DisplayName = registerlogin.User_First_Name;
            userToBeAdded.UserPrincipalName = registerlogin.User_EmailId.Replace("@", "_") + "@" + Session["DomainNames"].ToString();
            //userToBeAdded.UserPrincipalName = mail1.Replace("@", "_") + "@" + Session["DomainNames"].ToString();

            userToBeAdded.AccountEnabled = true;

            userToBeAdded.MailNickname = registerlogin.User_Last_Name;
            userToBeAdded.Country = registerlogin.User_CountryName;
            userToBeAdded.State = registerlogin.User_StateName;

            userToBeAdded.PasswordProfile = new PasswordProfile

            {

                Password = registerlogin.User_Password,

                ForceChangePasswordNextLogin = true

            };

            userToBeAdded.UsageLocation = "US";

            await activeDirectoryClient.Users.AddUserAsync(userToBeAdded);
            if (userToBeAdded.DisplayName != "")
            {
                if (userToBeAdded.ObjectId != null)
                {
}
}

For Login
  activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication(this.HttpContext.Session);

                IUser users = activeDirectoryClient.Users.Where(d => d.UserPrincipalName == Convert.ToString(principalName)).ExecuteSingleAsync().Result;
                User user = (User)users;


No comments:

Post a Comment