Securing Your React Project with Windows Authentication: A Step-by-Step Guide

Securing Your React Project with Windows Authentication: A Step-by-Step Guide

Securing Your React Project with Windows Authentication using .NET 7: A Step-by-Step Guide

Introduction

Papatia had an app that worked on-premise, and the decision was made to update its UI. To accomplish this, the Papatia team set up the React project. However, a challenge arose due to the existing use of LDAP authentication, which blocked the direct sending of inner requests.

As the Papatia team, the focus is on applying best practices. Extensive research was conducted to find a solution for React with Windows Authentication.

Ensuring the security of your web application is of utmost importance when it comes to safeguarding sensitive data and guaranteeing authorized access. Within this comprehensive guide, the proficient Papatia team will elucidate how to incorporate Windows Authentication into your ASP.NET Core WebAPI project, utilizing the powerful .NET 7 framework. This guide will explore how to configure Cross-Origin Resource Sharing (CORS) for smooth communication between your React server and Web API while maintaining high-security standards.

Part 1: How to implement Windows Authentication in your ASP.NET Core WebAPI project

When it comes to user authentication, Windows Authentication provides a robust and dependable mechanism that leverages Windows credentials. By enabling Windows Authentication in your ASP.NET Core WebAPI, you can ascertain that only duly authenticated users, possessing the necessary permissions, can gain access to your API endpoints.

To successfully implement Windows Authentication in your project, carefully follow the outlined steps below: Commence by creating an ASP.NET Core WebAPI project.

Open the Program.cs file and add the following code to enable Windows Authentication:


using Microsoft.AspNetCore.Authentication.Negotiate;

// ...

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
    .AddNegotiate();
builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

Update your appsettings.json file to enable Windows Authentication:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:27193",
      "sslPort": 44311
    }
  }

Ensure you handle HTTPS redirection and configure the necessary middleware for authorization.

Part 2: Configuring CORS for React Server Integration

Cross-Origin Resource Sharing (CORS) allows you to control access to your API endpoints from different origins. By configuring CORS policies, you can define which domains are allowed to make requests to your API. Our goal is to facilitate requests from our React server.

If you're looking to establish CORS for your ASP.NET Core WebAPI, here's what you should do:

Begin by opening the Program.cs file and insert the code below to configure CORS:

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddCors(options =>
{
    options.AddPolicy("MyAllowSpecificOrigins",
        policy =>
        {
            policy.WithOrigins("http://localhost:3000")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
        });
});

app.UseCors();

Replace "http://localhost:3000" with the appropriate URL for your React server.

Part 3: Implementing Windows Authentication and CORS in your React Project

Secure your ASP.NET Core WebAPI requests in React by adding authentication and CORS headers. Here's an example of how to integrate them easily.

import { handleResponse, requestBase } from "../_helpers";

const apiBase = "https://localhost:7091/WeatherForecast";

class WeatherForecastService {
  getWeatherForecast() {
    let request = Object.assign({}, requestBase, { mode: "no-cors", method: "GET" });
    let url = `${apiBase}`;

    return fetch(url, request).then(handleResponse);
  }
}

const instance = Object.freeze(new WeatherForecastService());
export { instance as WeatherForecastService };

Conclusion

By following this step-by-step guide and implementing Windows Authentication in your ASP.NET Core WebAPI project, and configuring CORS in your React project, you have taken important steps towards enhancing the security of your application.

Windows Authentication secures API endpoints by restricting access to authorized users with necessary permissions, adding an extra layer of protection. Configuring CORS allows you to control which domains are permitted to request your API. By specifying the allowed origins, headers, and methods, you can restrict access to your API endpoints and prevent unauthorized requests. In our case, we allowed requests only from our React server running on "http://localhost:3000".

In your React project, you incorporated the necessary authentication and CORS headers while making requests to your ASP.NET Core WebAPI. By setting the mode to "no-cors" and including the Authorization header, you ensured that the requests are properly authenticated and authorized using Windows Authentication.

Remember to customize the code snippets provided to match your specific project configurations, such as the API endpoint URL and React server URL.

By implementing Windows Authentication and configuring CORS, you have established a secure communication channel between your React front end and Core WebAPI backend. Stay proactive in protecting your application by consistently updating your security measures to prevent potential threats.

Regularly reviewing and updating acronyms and abbreviations is essential for effective communication and avoiding misunderstandings in any context.

From our blog

Join us on a journey of digital discovery.
Web, mobile, cybersecurity, cloud, and beyond

Incident Report: Docker Service Degradation Due to Disk Exhaustion
Incident Report: Docker Service Degradation Due to Disk Exhaustion

Detailed incident report describing Docker service degradation caused by disk exhaustion in Docker Desktop’s WSL2 virtual disk (ext4.vhdx), including impact,...

DOCKER
February 4th, 20264 mins to read
Creating High-Performing Landing Pages:Best Practices for Conversions
Creating High-Performing Landing Pages:Best Practices for Conversions

Boost your online marketing efforts with expert tips for creating high-performing landing pages. Learn how to increase your conversion rates effectively.

LANDING PAGES
October 26th, 20232 mins to read
The Power of Video Marketing:Engaging Your Audience
The Power of Video Marketing:Engaging Your Audience

Explore the Impact of Video Marketing on Audience Engagement

VIDEO MARKETING
October 24th, 20231 mins to read
AI Chatbots:Enhancing Customer Support and User Experience
AI Chatbots:Enhancing Customer Support and User Experience

In today's business landscape, customer satisfaction and providing swift responses have never been more critical. Explore how AI-powered chatbots, like those...

AI
October 19th, 20232 mins to read
Newsletter

Subcribe our newsletter

Do not miss the information from us about the trending in the market. By clicking the button, you are agreeing with our Term & Conditions