Application authentication

Azure Active Directory is a Microsoft identity manager and is used to create intelligence-driven access policies that are used to secure Azure resources.  Every Tenant created in Azure is backed by an Azure Active Directory, which assists in the Role-Based Access Control, or RBAC, which is the identity model that Azure resource leverage for security.  It is shared between both SaaS based solutions such as Office 365 and IaaS/PaaS based solutions such as App Services/VMs in Azure.  Here, you can see the basic flow of a user authenticating:

Basic Login Flow
You need to remember all applications need to be registered with AAD.  AAD supports OAuth 2.0 and OpenID Connection standards.

If you would like to dive a bit deeper into AAD and learn more about it, I would suggest you use the 2.0 endpoint documentation at https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-appmodel-v2-overview.  Now, let’s see how we add it to your application.

First, add your Application Registration to AAD within the Azure portal, as you can see here:

Add Application Registration

Make sure to note the Application ID, as you can see here. You will need this for your configuration within your application:

Application Registration Screen

To add security to your application, let's take a quick look at adding it to an ASP.NET MVC (Model-View-Controller) application. For the ASP.NET web application, make sure to add the following package with the package manager:

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb
Sometimes, your application may not include a Startup.cs, so you just need to right-click on the project folder and say Add > New Item > OWIN Startup class, then name it Startup.cs.

The examples are in C# and you will need to add the following in the Startup.cs.

Update the references to include the OWIN Authentication; we will be using OpenConnectID in this example:

using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;

Then, in the Startup class, add these variables:

// This is the ApplicationID to Azure AD.
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
// RedirectUri where the user will be redirected to after they sign in.
string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];
// Your Tenant ID
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
// Authority is the URL for authority, https://login.microsoftonline.com/<Tenant>/v2.0
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

Add this to the Configuration method:

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Scope = OpenIdConnectScope.OpenIdProfile,
ResponseType = OpenIdConnectResponseType.IdToken,
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed
}
}
);

Then, add the following method for what to do on authentication failure:

private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
context.Response.Redirect("/?errormessage=" + context.Exception.Message);
return Task.FromResult(0);
}

Then, in the Home Controller, all you have to do is add the following.

Add resources for OWIN:

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;

Then, add two actions. Sign in as follows:

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

Sign out as follows:

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

Add the following HTML to the Home View:

@if (!Request.IsAuthenticated)
{
<a href="@Url.Action("SignIn", "Home")" style="text-decoration: none;">
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="300px" height="50px" viewBox="0 0 3278 522" class="SignInButton">
<style type="text/css">.fil0:hover {fill: #4B4B4B;} .fnt0 {font-size: 260px;font-family: 'Segoe UI Semibold', 'Segoe UI'; text-decoration: none;}</style>
<rect class="fil0" x="2" y="2" width="3174" height="517" fill="black" />
<rect x="150" y="129" width="122" height="122" fill="#F35325" />
<rect x="284" y="129" width="122" height="122" fill="#81BC06" />
<rect x="150" y="263" width="122" height="122" fill="#05A6F0" />
<rect x="284" y="263" width="122" height="122" fill="#FFBA08" />
<text x="470" y="357" fill="white" class="fnt0">Sign in with Microsoft</text>
</svg>
</a>
}
else
{
<span><br/>Hello @System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value;</span>
<br /><br />
@Html.ActionLink("See Your Claims", "Index", "Claims")
<br /><br />
@Html.ActionLink("Sign out", "SignOut", "Home")
}
@if (!string.IsNullOrWhiteSpace(Request.QueryString["errormessage"]))
{
<div style="background-color:red;color:white;font-weight: bold;">Error: @Request.QueryString["errormessage"]</div>
}

And bingo, you now are using AAD to authenticate your user, but wait, people can still get to things without logging in.  Well, now that you have created a way for people to log in, you have not yet secured your site. To do this, we want to lock it down, which can be done globally by a Controller or Action.  I always recommend globally, because it is easier to loosen up security than remember to tighten it down, but let’s look at how to do each way first.

To add authentication globally, add the following to global.asa. In the app_start section, add the following:

GlobalFilters.Filters.Add(new AuthorizeAttribute());

Now you will be challenging any route/action you choose from a security/logged perspective.  Now, if you want to allow access to an Action, you will need to add the [AllowAnonymous] attribute to the Action.  In this case, go to your Home Controller and the Index action, then add the [AllowAnonymous] attribute.  You will now be able to browse to the default homepage without logging in.

This is basically how you will integrate any application into AAD. Now, B2C functions in the same way, as you will need to register the application; however, you will need to also generate a key, as you can see here:

Generating a key for an Application Registration

But before we can do this, we will need to create the B2C Tenant. Remember I said that an instance of Azure Active Directory was connected to a Tenant?  Well, we will need to create a new Tenant that we will use to secure our applications. To create a new B2C Tenant, click + Create a resource then type Azure Active Directory B2C and hit Enter, as you can see here:

Search for Azure B2C Tenant to create

Then click Create, as you can see here:

Create a B2C Tenant

At this point, you can create a new B2C Tenant or link to an existing one, as you can see here. For the purposes of this discussion, we will create a new one, so click on Create a new Azure AD B2C Tenant:

Create or Link to a B2C Tenant

Then, enter you Organization name, Initial domain name, and Country or region, as you can see here:

Enter new B2C Tenant information

To navigate to your new Tenant, you will need to switch over to it, as you can see here. This will function like AAD, with a few exceptions. You will need to create policies to leverage in your development, along with assigning permissions to your app service principle:

Switch to new B2C Tenant

Now, the configuration of B2C is subjective, according to the policies you want to leverage, which I wasn’t looking to fully cover in this book.  You can do a deeper dive into B2C at https://docs.microsoft.com/en-us/azure/active-directory-b2c/. I would, however, like to share some things I learned that aren’t documented very well, and I would also recommend you fully research the resource you want to use in Azure to gain more knowledge about the pros and cons.  We ran into an issue where the graph had issues with password changing and resetting, that drove me crazy but here is how I fixed it.  Here are the PowerShell commands I ran on the B2C Tenant:

Connect-MsolService
$applicationId = "App ID from app you are needing to elevate permission"
$sp = Get-MsolServicePrincipal -AppPrincipalId $applicationId
# Directory Read
Add-MsolRoleMember -RoleObjectId 88d8e3e3-8f55-4a1e-953a-9b9898b8876b -RoleMemberObjectId $sp.ObjectId -RoleMemberType servicePrincipal
# Directory Write
Add-MsolRoleMember -RoleObjectId 9360feb5-f418-4baa-8175-e2a00bac4301 -RoleMemberObjectId $sp.ObjectId -RoleMemberType servicePrincipal
# User Account Admin – for deletes
Add-MsolRoleMember -RoleObjectId fe930be7-5e62-47db-91af-98c3a49a38b1 -RoleMemberObjectId $sp.ObjectId -RoleMemberType servicePrincipal

But as you can see, security gets a bit easier in Azure and there is less to worry about once you get things set up. Now, one thing I added to my development work is Inversion of Control (IoC), commonly called Dependency Injection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.35.122