Sunday, May 30, 2021

Implementation of Windows Azure Authentication in Asp.net MVC

Windows Azure Authentication in Asp.net

How we implement windows azure authentication in asp.net web applications?




















Code in Home View


@{
    /**/

    ViewBag.Title = "Windows Azure Athentications";
}

<h2>Index</h2>
@if (Session["UniqueName"] != null)
{<text>
        Windows Azure Authentication -  Given Name:   @Session["UniqueName"].ToString() </text>
}

@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
    <input type="submit" value="Login" />
    
}


Code in Home Controller

        private static string clientId = WebConfigurationManager.AppSettings["ClientId"];
        private static string appKey = WebConfigurationManager.AppSettings["AppKey"];
        private static string aadInstance = WebConfigurationManager.AppSettings["AADInstance"];
        private static string tenant = WebConfigurationManager.AppSettings["Tenant"];
        private static string redirectUri = WebConfigurationManager.AppSettings["RedirectUri"];


        public static readonly string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

        // GET: AADAuth
        public ActionResult Index()
        {

            return View();
        }
        public ActionResult Login()
        {
            AuthenticationContext authContext = new AuthenticationContext(Authority);
            AuthenticationResult result = null;
            Uri uri = new Uri(redirectUri);
            result = authContext.AcquireTokenAsync("https://graph.windows.net", clientId, uri, new PlatformParameters(PromptBehavior.SelectAccount)).Result;
            Session["UniqueName"] = result.UserInfo.GivenName;
            return RedirectToAction("Index", "Home");
        }

       

        public void GetAuthorizationCode()
        {
            JObject response = new JObject();

            var parameters = new Dictionary<string, string>
                {
                    { "response_type", "code" },
                    { "client_id", clientId },
                    { "redirect_uri", redirectUri },
                    { "prompt", "login"},
                    { "scope", "openid"}
                };

            var requestUrl = string.Format("{0}/authorize?{1}", EndPointUrl, BuildQueryString(parameters));

            Response.Redirect(requestUrl);

        }


        public string AcquireTokenWithResource(string resource)
        {
            var code = Request.Params["code"];
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ac = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenant
                                  ));
            ClientCredential clcred =
                new ClientCredential(clientId, appKey);
            var token =
                ac.AcquireTokenByAuthorizationCodeAsync(code,
                           new Uri(redirectUri), clcred, resource).Result.AccessToken;

            return token;
        }


        private string BuildQueryString(IDictionary<string, string> parameters)
        {
            var list = new List<string>();

            foreach (var parameter in parameters)
            {
                list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)));
            }

            return string.Join("&", list);
        }

        protected string EndPointUrl
        {
            get
            {
                return string.Format("{0}/{1}/{2}", "https://login.microsoftonline.com", tenant, @"oauth2/");
            }
        }

    }

 This is code for the implementation of  Azure authentication.