Skip to end of banner
Go to start of banner

Azure Authentication using OWIN with ASP.NET

Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The EmpowerID Owin Plugin for Azure is an in-process Open Web Interface for .NET (OWIN) component for enabling Azure AD authentication in legacy MVC-based .NET web applications. This Plugin for Azure is a set of classes in the EmpowerID.OwinPlugIn.V47.dll assembly that you reference and use to modernize your legacy MVC web application with Azure AD authentication and authorization.

Step 1: Configure the Owin Plugin

Assembly information of Easy Auth HTTP Module

  • Class: AzDirectoryAuthentication

  • Assembly: EmpowerID.OwinPlugIn.V47.dll

  • Platform: .NET Framework 4.7.2

  1. Add the EmpowerID.OwinPlugIn.V47.dll assembly reference to your MVC project and add the assembly level OwinStartupAttribute to the main web application project.

    [assembly: OwinStartupAttribute(typeof(MyAppOwin.Startup))]

  2. In the Startup.Configuration method uses the AzDirectoryAuthentication.ConfigureAzureADAuth () method to configure the Azure AD authentication for the application. You may need to use the AntiForgeryConfig.UniqueClaimTypeIdentifier to identify the claim type for the user identity claim.

    public void Configuration(IAppBuilder app) {
      AntiForgeryConfig.UniqueClaimTypeIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
    
      AzDirectoryAuthentication.ConfigureAzureADAuth(app, Startup.Config, null,
        delegate(Microsoft.Owin.IOwinContext context, IPrincipal principal) {
          //TODO: Claims transformation code goes here
    
          return new AuthenticationTicket((ClaimsIdentity) principal.Identity, new AuthenticationProperties());
        });
    }


  3. In the Startup class, you can create a static property to return the AuthenticationConfig passed to the AzDirectoryAuthentication.ConfigureAzureADAuth() method. An instance of the AuthenticationConfig class provides the configuration settings for the target Azure AD. These are some important settings to configure,

    1. ClientId: The Client ID or Application ID of the registered application in Azure AD.

    2. ClientSecret: A client secret generated in the registered application in Azure AD.

    3. Authority: The global Azure AD authentication endpoint.

    4. RedirectUri: The default landing URL of the application.

      public static AuthenticationConfig Config
              {
                  get
                  {
                      return new AuthenticationConfig
                      {
                          ClientId = ConfigurationManager.AppSettings["ida:ClientId"],
                          ClientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"],
                          RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"],
                          Authority = ConfigurationManager.AppSettings["ida:Authority"],
                          BasicScope = "openid profile offline_access",
                      };
                  }
              }

      A sample for the configuration in the web config is shown below.

      <appSettings>
          <add key="ida:ClientId" value="ka05f2e5-e52d-446d-l49e-9ac1e9d492hf" />
          <add key="ida:ClientSecret" value="Zju7Q~AFH2OulZ4Pnb_VVJQwnjfS-Tk1YGhvV" />
          <add key="ida:Authority" value="https://login.microsoftonline.com/common/v2.0" />
          <add key="ida:RedirectUri" value="https://localhost:44327/" />
      </appSettings>

Step 2: Implement the Custom Claims Transformer

You implement claims transformation with the Owin Plugin using the delegate passed to the AzDirectoryAuthentication.ConfigureAzureADAuth() method. The delegate must return an instance of AuthenticationTicket with the current identity.

delegate(Microsoft.Owin.IOwinContext context, IPrincipal principal) {
//TODO: Claims transformation code goes here

return new AuthenticationTicket((ClaimsIdentity) principal.Identity, new AuthenticationProperties());
});

Inside the delegate, you can add and remove Claims from the identity attached to the ClaimsPrincipal. Samples of adding, finding & removing claims are provided below,

var claim = new Claim("preferred_username", "michael@hotmail.com");
((ClaimsIdentity)principal.Identity).AddClaim(claim);
System.Security.Claims.Claim claim = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("preferred_username");
(ClaimsIdentity)principal.Identity).RemoveClaim(claim);

Step 3: Implement the Login and Logout Actions

Add a using statement to include EmpowerID.OwinPlugIn.V47 DLL in the controller with login and logout actions for your application.

using EmpowerID.OwinPlugIn.V47;

The MsalAppBuilder class contains extensions for the SignInUser() and SignOutUser() which you can call in the controller for the login and logout actions. An example of the method implementation is shown below.

 [AllowAnonymous]
 public async Task Login() {
   await this.SignInUser();
 }

 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task < ActionResult > LogOff() {
   await this.SignOutUser(Startup.Config);

   return RedirectToAction("Index", "Home");
 }

Step 4: How to Implement Role-based Authorization

The [Authorize] attribute allows you to implement role-based authorization in your application. By default, Azure AD user App Roles assignments are included in the default set of claims issued by Azure AD. These App Roles can be used with the [Authorize] attribute.

    [Authorize]
    public class AccountController: Controller {
      public AccountController() {}
    }

To protect an action with roles, add the [AzAuthorize] attribute and specify the roles the action demands. You can redirect to route by specifying the controller and action you wish to redirect if and when authorization fails.

[AzAuthorize(Roles = "Task.Write", ErrorAction = "NotAuthorized"   ErrorController = "Account")]
public ActionResult Register() {
  return View();
}

If you wish to allow the application to throw an error with the Forbidden HTTP status code, set the EnableForbidden attribute parameter to true.

[AzAuthorize(Roles = " Task.Read,Task.Write", EnableForbidden = true)]
public ActionResult Register() {
  return View();
}

Configuring the Redirect URI in Azure

Add the Redirect URL to your application to the registered application in Azure.

  • No labels