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;


How to Create a Database on Azure Elastic Pool.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.Azure;
using Microsoft.Azure.Management.Resources.Models;
using System.Web.Mvc;
using saytya.Models;

namespace Satya.Utils
{
    public class DatabaseElaticPoolHelper
    {
        private static string azureActiveDirectoryInstance = "https://login.microsoftonline.com/";
        // private static string tenant = "satya@satyabrata.onmicrosoft.com";
        private static string tenant = "satyabrata.onmicrosoft.com";
        private static string clientId = "dsdsdsdsds-weew-4d46-rewrw-353455";
       
        private static string appKey = "fdsfg4545366546a/657jyj65534fgfn54=";
        private static string resource = "https://management.core.windows.net/";
        private static string resourceGroup = "satyabrata";
        private static string subscriptionId = "42424324-7777-466-hg65-hgh75765756";

        static string authority = azureActiveDirectoryInstance + tenant;
        public  string  CreateDtabase(string dbname)
        {
            // "satya@satyabrata.onmicrosoft.com";
            var client = GetSqlManagementClient();

            // The Db we want to use as template
            var originalDb = client.Databases.Get(resourceGroup, "satyaDB", "SatyaMeta");

            // Create a new database within the same elastic pool
            var parameters = new DatabaseCreateOrUpdateParameters()
            {
                Location = "Central India",
                Properties = new DatabaseCreateOrUpdateProperties()
                {
                    ElasticPoolName = "satyaPOOL",
                    SourceDatabaseId = originalDb.Database.Id
                }
            };
            var response = client.Databases.CreateOrUpdate(
              resourceGroup,
              "Satyabratabege",
              dbname,
              parameters
            );
          var ss= response.Status;
            if(ss.ToString()== "Succeeded")
            {
                return "Yes";
            }
            else
            {
                return "No";
            }
        }

        private static string GetToken()
        {
            var httpClient = new HttpClient();
            var authContext = new AuthenticationContext(authority);
            var clientCredential = new ClientCredential(clientId, appKey);
            var result = authContext.AcquireToken(resource, clientCredential);
            return result.AccessToken;
        }

        private static SqlManagementClient GetSqlManagementClient()
        {
            var token = GetToken();
            var credentials = new Microsoft.Azure.TokenCloudCredentials(subscriptionId, token);
            var client = new SqlManagementClient(credentials);
            return client;
        }
    }
}