Azure Active Directory Implementation

Step1:


Go to the Azure portal.
Create an Active Directory and generate a Tenant name and client Id.


Step2:

Add these parameters to the web config of the solution

    <add key="ida:ClientId" value="b5a****c-f76f-452f-9571-25****cc3f4d" />
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
    <add key="ida:Tenant" value="v****p.onmicrosoft.com" />
    <add key="ida:PostLogoutRedirectUri" value="https://localhost:44394/" />


Step3:

Replace the code in the login partial

Code:
@if (Request.IsAuthenticated)
{

    <ul class="nav navbar-nav navbar-right">
    <li class="navbar-text">  Hello, @User.Identity.Name  </li>
        <li> @Html.ActionLink("Sign out","SignOut","Account")</li>
    </ul>
}
else
{

    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Sign in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>

        }



Step4:

Replace the Accounts Controller code with -

 public void SignIn()
        {
            if (!Request.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri="/"}, OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

        public void SignOut()
        {
            HttpContext.GetOwinContext().Authentication.SignOut(
                OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);


        }

Note: Dont forget to import the Owin Namespace.

Step5:


You are good to go :) Users in the AD can access the application now. Don't forget to include the Authorize attribute where ever necessary.



Happy Coding !!!!!



Comments