Friday, July 22, 2022

Authenticate .Net core web app using Azure AD

 In this tutorial you will see how to implement azure ad authentication/sso in .Net core app.

So lets start , I have tried to keep as simple as possible so basic things can be understood easily.

Steps.

Setting your App in Azure AD

1. Login to azure portal -> search for Azure Active Directory and click .


2. From Left Menu select App Registration and click on New Registrations


in the app name enter "AzureADSignOn" (you can enter your app name ) , keep default selected value in Supported Account types

Redirect Url - select web from dropdown and enter your redirect url where you want to redirect after successful login. in my case its "https://localhost:44319/index"

3. Click Authentication from Left Menu and check on ID Token and click on Save.




4. Go to overview menu and copy paste below in your local notepad as per below screen shot 
 1. Client Id 
2. TenantId
3. domain Name : you can find in your active directory overview



We are done with azure ad configuration. Let's see how to implement in .Net core web app.

Creating ASP.NET Core 5.0 web application

1.Open Visual Studio and create .Net core web app named "AzureADSignOn" click next and create.

2. Open appsetting.json and replace with below json

{
  "AzureAdConfig": {
    "Instance": "https://login.microsoftonline.com",
    "TenantId": "<<your tenantId>>",
    "ClientId": "<<your application Id/client Id>>",
    "Domain": "<<domain name>>",
    "CallbackPath": "/index"  <--this should be exact
same what u have enter in redirect url while registering app and starting with / always
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

3. Add below two NuGet Packages 

  • Microsoft.Identity.Web
  • Microsoft.AspNetCore.Authentication.AzureAD.UI

Choose based on your .Net Core version.

4. Open Startup.cs and add below  code which is highlighted in orange color.

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
 
namespace AzureADSignOn
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        public IConfiguration Configuration { get; }
 
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
 //add this code
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdConfig"));
 

            services.AddControllersWithViews();
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
 
            app.UseRouting();
//add this code
            app.UseAuthentication();
            app.UseAuthorization();
 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

 5. Go to HomeController and add below highlighted code in orange color


using AzureADSignOn.Models;
using
Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Logging;
using System.Diagnostics;
 

namespace AzureADSignOn.Controllers

{

    [Authorize]
    
public class HomeController : Controller
    {

        
private readonly ILogger<HomeController> _logger;
        
public HomeController(ILogger<HomeController> logger)
        {
            
_logger = logger;
        } 
        public IActionResult Index()
        
{
            if (User.Identity.IsAuthenticated) // you can ignore this if dont need
            
{
               // you can capture claim and user details and do whatever need


            }
            return View(); 
        
}
 



        
public IActionResult Privacy()
        {



            
return View();
        }



 

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]



        
public IActionResult Error()
        {



            
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ??               HttpContext.TraceIdentifier });
        }


    }

}

6. open Index.cshtml view and replace with below code


@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome To azure ad authentication sample</h1>

</div>

@if (Context.User.Identity.IsAuthenticated)
{
    var user = Context.User;
    <h2>User Name : @user.Identity.Name</h2>

    @foreach (var claim in user.Claims)
    {
        <li>
            @claim.Type : @claim.Value
        </li>
    }
}

 

1. Once you run it redirect to Microsoft login page 


 Enter your user name and click next ,in next screen enter password

Note : first time it ask acceptance for access . accept that and continue.




After successful login it redirects to your app where you can see below output. I have shown few logged in user details.


And That's it. We have completed Azure Ad Authentication. 

Thanks . 

 


No comments:

Post a Comment

Thanks for your valuable comments

Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...