Migrate Authentication/Authorization Functionality from ASP.NET 4.8 to ASP.NET Core 6

csharpdev

I am migrating an application from ASP.NET 4.8 to ASP.NET Core 6.

It is hosted in Azure, it uses Azure App Service, App Registration, App Roles, Enterprise Application.

The following is used in the ASP.NET 4.8 project:

App_Start/Startup.Auth.cs:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        var clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        var aADInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        var tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
        var postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
        var authority = string.Format(CultureInfo.InvariantCulture, aADInstance, tenantId);

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies",
            CookieManager = new SystemWebChunkingCookieManager()
        });

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = ClaimTypes.Name,
                    RoleClaimType = ClaimTypes.Role
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.OwinContext.Response.Redirect("/");
                        return Task.FromResult(0);
                    }
                }
            }
        );
    }
}

Startup.cs:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(App.Startup))]
namespace App
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

CustomAuthorizeAttribute.cs:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    private readonly string[] _roles;

    public CustomAuthorizeAttribute(params string[] roles)
    {
        _roles = roles;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return Authorize(httpContext);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);
    }

    public bool GetAuthorization(HttpContextBase httpContext)
    {
        return Authorize(httpContext);
    }

    protected bool Authorize(HttpContextBase httpContext)
    {
        var authorize = false;

        var coreDb = new CoreDbContext();

        foreach (var role in _roles)
        {
            var adGroups = coreDb.GetAdGroupsFromRole(role);

            foreach (var adGroup in adGroups.ResultSet1)
            {
                if (httpContext.User.IsInRole(adGroup.ActiveDirectoryGroup))
                {
                    authorize = true;
                    break;
                }
            }

            if (authorize)
                break;
        }

        return authorize;
    }
}

AccountController.cs:

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

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

CustomAuthorizeAttribute in use:

[CustomAuthorize("SomeAzureAppRole")]

_Login.cshtml:

@if (Request.IsAuthenticated)
{
    <text>
        Hello, @User.Identity.Name <a href="/Account/SignOut"> Sign Out</a>
    </text>
}

Web.config/appSettings:

<appSettings>
    <add key="ida:ClientId" value="SomeGuidValue" />
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
    <add key="ida:TenantId" value="SomeGuidValue" />
    <add key="ida:PostLogoutRedirectUri" value="https://localhost:SomePortNumber/" />
</appSettings>

Examples that provide similar functionality in ASP.NET Core 6?

Harshitha

Thanks @NaveenBaliga for the comment.

The links provided by @NaveenBaliga will help you to understand the Structure and the available files in .NET Core.

You can get the Authentication/Authorization Functionality directly by adding the Authentication mode as Microsoft Identity Platform.

Check the below Workaround to get the Sample Code

  • Create a .NET Core 6 Application. Select the Authentication Type as Microsoft Identity Platform.

enter image description here

  • Once we click on create Project, the Project will be created, and the below screen is shown.

enter image description here

  • Continue with the next steps.

It is hosted in Azure, it uses Azure App Service, App Registration, App Roles, Enterprise Application.

  • Select the correct tenant.

As the shown example works only for Owned Applications, if you want the application and code format follow the steps with some sample Owned Application.

  • Once the Code is configured, you can change the Configuration settings in appsettings.json file with your Enterprise application.

  • Select the registered app, create one if you don't have and click on Next.

enter image description here

  • Select the required permissions (Skip if not required), Continue with Next steps. enter image description here

  • Registered app will be updated with the required Redirect URI and all the required packages, code gets updated in the Application.

enter image description here

Application folder Structure:

enter image description here

My _LoginPartial.cshtml

@using System.Security.Principal

<ul class="navbar-nav">
@if (User.Identity?.IsAuthenticated == true)
{
        <span class="navbar-text text-dark">Hello @User.Identity?.Name!</span>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
        </li>
}
else
{
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
        </li>
}
</ul>

My appsettings.json file:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "****.onmicrosoft.com",
    "TenantId": "****",
    "ClientId": "****",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Output:

enter image description here

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related