Search code examples
reactjsapi.net-coreauthorizationreactjs.net

windows Authorization in ReactJS and .NET Core API


We have a new application which is having ReactJS as front end and back end is .NET Core API.

A requirement is to authorize the windows logon user with respect to Active Directory.

The .NET Core API will be doing the Authorization part.

We have used the following code in .NET Core API but it is returning the ID under which the App-Pool of .NET Core API is running. We tried setting the API on Windows Authentication enabled but it did not work as well.

            dynamic userIdentity = WindowsIdentity.GetCurrent();
            dynamic userPrincipal = new WindowsPrincipal(userIdentity);
            string Admin = _configuration["AppUserRoles:Admin"];
            result = userPrincipal.IsInRole(Admin);

I have changed the code to the following:

            dynamic userIdentity = WindowsIdentity("UserID");
            dynamic userPrincipal = new WindowsPrincipal(userIdentity);
            string Admin = _configuration["AppUserRoles:Admin"];
            result = userPrincipal.IsInRole(Admin);

We need to pass the the UserID from ReactJS to the API Layer.

In ReactJS I have tried the following:

            var path = require('path');
            var userName = process.env['USERPROFILE'].split(path.sep)[2];
            var loginId = path.join("domainName",userName);

But this is not working in ReactJS.

Is there a way we can fetch the Windows Logon ID in React JS and pass it to the API layer for authorization?


Solution

  • We were able to get this done by the following approach:

    under IIS we hosted the website as follows:

    1. Added a website ReactJSWeb.

      i. Added .NETCore virtual directory under the ReactJS website.

    Both Main website and Virtual directory had Authentication set as Windows Authentication Enabled.

    In .NET Core API - authentication module we added a Attribute [Authorize] on the class and added the following code in the method:

    using Microsoft.AspNetCore.Authorization;

            dynamic userIdentity = WindowsIdentity(**User.Identity.Name**);
            dynamic userPrincipal = new WindowsPrincipal(userIdentity);
            string Admin = _configuration["AppUserRoles:Admin"];
            result = userPrincipal.IsInRole(Admin);
    

    This worked and we are now able to do the Authorization properly based on the Active Directory security group the user is part of.