Ads

OKTA SSO Authentication for .Net Core MVC application

In today's interconnected digital landscape, secure and efficient authentication methods are crucial for safeguarding user data and enhancing user experience. Single Sign-On (SSO) is a popular authentication mechanism that allows users to log in once and gain access to multiple applications without needing to re-enter credentials. OKTA, a leading identity and access management service, provides robust SSO capabilities. This article will guide you through integrating OKTA SSO authentication into your ASP.NET MVC application.

Prerequisites

Before diving into the integration process, ensure you have the following:

  1. An OKTA developer account (sign up here).
  2. Visual Studio installed.
  3. Basic knowledge of ASP.NET MVC and authentication mechanisms.

Step 1: Set Up Your OKTA Application

Login to your account

Create New Applicatioon


Enter Appllication name and select technology ASP.Net Core MVC then continue


Application created successfully.



Next, Step will be continue after ASP.Net Core MVC application creation and configuration set up.

Step 2: Configure Your ASP.NET MVC Application

Lets Create MVC application


Select Framework and Create


Awesome, we have create ASP .Net Core MVC application successfully.


Lets Add the dependency first from NuGet or package manager console

Install-Package Auth0.AspNetCore.Authentication

Lets Add the dependency script in Program.cs

builder.Services.AddAuth0WebAppAuthentication(options =>
{
    options.Domain = builder.Configuration["Auth0:Domain"];
    options.ClientId = builder.Configuration["Auth0:ClientId"];
});

Make sure you have enabled authentication and authorization in your Program.cs file:

app.UseAuthentication();
app.UseAuthorization();

Finally Our Program.cs looks like below

using Auth0.AspNetCore.Authentication;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddAuth0WebAppAuthentication(options =>
{
    options.Domain = builder.Configuration["Auth0:Domain"];
    options.ClientId = builder.Configuration["Auth0:ClientId"];
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Lets add the fields value in appsettings.json

"Auth0": {
  "Domain": "OKTA DOMAIN",
  "ClientId": "CLIENT ID"
}

Lets get the values in below screen in Okta


Finally our appsettings.json will be

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Auth0": {
    "Domain": "OKTA DOMAIN",
    "ClientId": "CLIENT ID"
  }
}

Next, Create the controller called AccountController.cs and then add following end points in it

using Auth0.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Okta_Auth_Learning_App.Models;

namespace Okta_Auth_Learning_App.Controllers
{
    public class AccountController : Controller
    {
        [Route("login")]
        public async Task Login(string returnUrl = "/")
        {
            var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                // Indicate here where Auth0 should redirect the user after a login.
                // Note that the resulting absolute Uri must be added to the
                // **Allowed Callback URLs** settings for the app.
                .WithRedirectUri(returnUrl)
                .Build();

            await HttpContext.ChallengeAsync(Auth0Constants
.AuthenticationScheme, authenticationProperties);
        }

        [Route("callback")]
        public IActionResult CallBack()
        {
            return RedirectToAction("Home/Index");
        }

        [Route("profile")]
        [Authorize]
        public IActionResult Profile()
        {
            var model = new ProfileViewModel
            {
                Name = User.Identity.Name,
                EmailAddress = User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value,
                ProfileImage = User.Claims
.FirstOrDefault(c => c.Type == "picture")?.Value
            };
            return View(model);
        }

        [Route("logout")]
        [Authorize]
        public async Task Logout()
        {
            var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                // Indicate here where Auth0 should redirect the user after a logout.
                // Note that the resulting absolute Uri must be added to the
                // **Allowed Logout URLs** settings for the app.
                .WithRedirectUri(Url.Action("logouts", "account"))
                .Build();

            await HttpContext
.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
            await HttpContext
.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }

        [Route("logouts")]
        public IActionResult Logouts()
        {
            return View();
        }
    }
}


Lets add the ProfileViewModel model under Model folder

public class ProfileViewModel
{
    public string Name { get; set; }
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; }
    [Display(Name = "Profile Image")]
    public string ProfileImage { get; set; }
}

Then create the profile.cshtml and logouts.cshtml view in Views --> Account folder.


Profile.cshtml

@model Okta_Auth_Learning_App.Models.ProfileViewModel

@{
    ViewData["Title"] = "Profile";
}

<h2>@ViewData["Title"]</h2>

<div>
    <h3>@Model.Name</h3>
    <p>@Model.EmailAddress</p>
    @if (!string.IsNullOrEmpty(@Model.ProfileImage))
    {
        <img src="@Model.ProfileImage" alt="Profile Image" />
    }
</div>

Logouts.cshtml

@{
    ViewData["Title"] = "Logout";
}

<h2>@ViewData["Title"]</h2>

<div>
    <h5 style="color:red">Log out success! <a href="/login">
Click here to re login.</a></h5>
</div>

Almost complete, only few more steps to run our application

Next add the links in _Layout.cshtml

After Privacy Link add below given code

 @{
     if (!User.Identity.IsAuthenticated)
     {
         <li class="nav-item">
             <a class="nav-link text-dark" asp-area="" 
asp-controller="account" asp-action="login">Login</a>
         </li>
     }
     else
     {
         <li class="nav-item">
             <a class="nav-link text-dark" asp-area="" 
asp-controller="account" asp-action="profile">Profile</a>
         </li>
         <li class="nav-item">
             <a class="nav-link text-dark" asp-area="" 
asp-controller="account" asp-action="logout">Logout</a>
         </li>
     }
 }

Thats it from application perspective.

Run the application and collect the below mentioned URL

  • https://<<APPLICATION URL>>/ ==> BASE URL
  • https://<<APPLICATION URL>>/callback ==> After Successful Login it will come here
  • https://<<APPLICATION URL>>/logouts ==> After Successful logout it will come here

Now we will continue from Step 1.

Go to OKTA web(https://manage.auth0.com/dashboard)

Go to Applications

Select application Okta_Auth_Learning_App

Go to Settings

Go to Application URIs section


In my case Base URL is https://localhost:7005/, Hence i have updated the detail in below mentioned places


Finally Save the changes and run the application.



Click on Login, You will be redirected to OKTA SSO Login page


Enter the Credentials, after successful login you will be redirected to callback action in account controller.


Here is the screen


Click on Profile Link


On Click Logout


Integrating OKTA SSO authentication into your ASP.NET MVC application enhances security and provides a seamless user experience by leveraging a centralized authentication service. By following this guide, you can efficiently set up and configure OKTA SSO, ensuring your application is secure and user-friendly.

For further customization and advanced features, refer to the OKTA Developer Documentation. Happy coding!

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !