Adding OKTA Authentication with your MVC Application is Easy

By | October 11, 2018

OKTA is an amazing product, it enables authentication to your applications in a very easy manner, not much coding involved just some configuration. I had tried this personally and we are using it more and more in our organization having used Azure Active Directory and On Prem Active Directory this cloud service usability is between both but functionality is way much better.

To let you know how easy it is, I will show you in few steps how to use OKTA Authentication with your MVC Application.

First make sure you have and OKTA Account if not get an Okta Developer Edition Account.

Now let’s create you application.  Go to Application -> Application -> Add Application -> Create New App

Choose Web as the platform, then choose OpenID Connect, click Create

Set up your OpenID Connect

Application Name: YourWebApplication
Base URIs : http://localhost:{port}
Login redirect URIs : http://localhost:{port}/authorization-code/callback
Logout redirect URIs: http://localhost:{port}/Account/PostLogout

Click Save

Now save these and after you have created the application grab the following information and add it into your Web.config, assuming you have a website project already in place.

  • Client ID
  • Client Secret
  • Org URL
  • Login redirect URIs
  • Logout redirect URIs

Using Nuget Add the following references in your Web Project

Now add an OWIN Startup class to your project and name the file Startup.cs.  Click Add

In your Startup.cs add the following lines below to configure your OktaMvc Authentication

using System.Collections.Generic;
using System.Configuration;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Okta.AspNet;
using Owin;
 
[assemblyOwinStartup(typeof(OKTA_Authentication.Startup))]
 
namespace OKTA_Authentication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
 
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
 
            app.UseOktaMvc(new OktaMvcOptions()
            {
                OktaDomain = ConfigurationManager.AppSettings["okta:OktaDomain"],
                ClientId = ConfigurationManager.AppSettings["okta:ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["okta:ClientSecret"],
                RedirectUri = ConfigurationManager.AppSettings["okta:RedirectUri"],
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["okta:PostLogoutRedirectUri"],
                GetClaimsFromUserInfoEndpoint = true,
                Scope = new List<string> { "openid""profile""email" },
            });
        }
    }
}

Note: If you are using .NET framework earlier than 4.6 and get the following error:
The request was aborted: Could not create SSL/TLS secure channel.

Make sure to include the following code in the Application_Start or Startup:

// Enable TLS 1.2
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

Configure your project to use the following port you set up earlier

Now lets create your AccountController to host the Login and Logout Methods.

Choose and Empty MVC Controller, Click Add

Name it AccountController

Now paste this code in your AccountController, it will contain all the methods  you will need for Login and Logout

using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security.Cookies;
using Okta.AspNet;
 
namespace OKTA_Authentication.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Login()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(OktaDefaults.MvcAuthenticationType);
                return new HttpUnauthorizedResult();
            }
 
            return RedirectToAction("Index""Home");
        }
 
        [HttpPost]
        public ActionResult Logout()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType,
                    OktaDefaults.MvcAuthenticationType);
            }
 
            return RedirectToAction("Index""Home");
        }
 
        public ActionResult PostLogout()
        {
            return RedirectToAction("Index""Home");
        }
    }
}

Go to your _Layout.cshtml and add the Login and Logout Links.

@if (Context.User.Identity.IsAuthenticated)
{
    <ul class="nav navbar-nav navbar-right">
        <li>
            <p class="navbar-text">Hello, <b>@Context.User.Identity.Name</b></p>
        </li>
        <li>
            <a onclick="document.getElementById('logout_form').submit();" style="cursorpointer;">Log out</a>
        </li>
    </ul>
    <form action="/Account/Logout" method="post" id="logout_form"></form>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Log in""Login""Account")</li>
    </ul>
}

In this section

And there you go, you have enabled OKTA Authentication in your Web Application, all you need to do is to put [Authorize] attribute on your controllers for those Controllers you want to secure.

Click login and it should send you to the OKTA Login Page

Put the necessary credentials then you’re in.

Things to take note: If you are using this on a live or preview environment you might need to talk to your account executive and let them know you will be using the API as they have to enable it on their end otherwise you will encounter this error

[HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).]
System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() +92828
Microsoft.IdentityModel.Protocols.<GetDocumentAsync>d__8.MoveNext() +375

[IOException: IDX20804: Unable to retrieve document from: '[PII is hidden]'.]
Microsoft.IdentityModel.Protocols.<GetDocumentAsync>d__8.MoveNext() +662
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.IdentityModel.Protocols.OpenIdConnect.<GetAsync>d__3.MoveNext() +291
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
Microsoft.IdentityModel.Protocols.<GetConfigurationAsync>d__24.MoveNext() +1129

This will not solve world problems, but it is an easy way to add an Authentication Mechanism to your website easily, if you want Role Based authentication then follow this post as I will share how to do that on our next article.

Recommended

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.