Azure Active Directory Login with React, with C# or Java Backend

Azure Active Directory Login with React, with C# or Java Backend

Keeping things secure is the important part of any application. As entire internet going to cloud, Azure Active Directory (AD) is one of the best possible among one of two popular options. It helps manage who can use your app and what they can do. Let’s see how to set up Azure AD for a C# and Java Spring Boot backend, and a React frontend to make sure only the right people get in.

First, go to the Azure portal and make a new Azure AD tenant if you don’t have one yet. Then, register your app in Azure AD. This gives you a special ID and secret. Make sure to set up the permissions and where users can go after they log in. These are simple steps to register your app:

  1. Go to Azure Portal and find Azure Active Directory.
  2. Click on “App registrations” and make a new registration for your React app.
  3. Save the Application (client) ID. You will need this in your React app later.
  4. Adjust necessary permissions accordingly

For your React app, you’ll need a package called react-aad-msal. This package helps with Azure AD stuff in React. Install the @azure/msal-browser and @azure/msal-react libraries using npm:

npm install @azure/msal-browser @azure/msal-react

After you install it, set it up with your Azure AD details. Make a login component using MsalAuthenticationTemplate to handle logging in.

import React from 'react';
import { MsalAuthenticationTemplate, useMsal } from 'react-aad-msal';

const Login = () => {
  const { instance, accounts } = useMsal();

  return (
    <MsalAuthenticationTemplate instance={instance} accounts={accounts}>
      <div>
        <h1>Welcome!</h1>
      </div>
    </MsalAuthenticationTemplate>
  );
};

export default Login;

This is the hypothetical component that checks the security:

import React from 'react';
import { useMsal } from 'react-aad-msal';

const ProtectedComponent = () => {
  const { accounts } = useMsal();

  // You can do other sort of changes as well.
  if (!accounts || accounts.length === 0)
    return <div>You are not authorized</div>;
  }

  return (
    <div>
      <h1>You are logged in!</h1>
    </div>
  );
};

export default ProtectedComponent;

Securing Backend with Azure Active Directory

C#.NET

In your C# backend, make sure you have the Microsoft.Identity.Client package installed. Use the ID and secret from Azure AD to set up authentication. Then, make a middleware to check if users are logged in.

With this setup, your C# backend will make sure only the right people can use your React app, thanks to Azure AD.

Here’s the C# part to secure your backend using Azure AD authentication:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace YourNamespace
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "https://login.microsoftonline.com/{tenantId}";
                    options.Audience = "{clientId}";
                });

            services.AddAuthorization();
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Java with Spring Boot

Ensure you have the necessary dependencies in your pom.xml file:

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-active-directory-spring-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

Configure Azure AD properties in your application.properties or application.yml. The variables tenantId, clientId, clientSecret, and YOUR_GROUP_NAME are placeholders that you need to replace with actual values specific to your Azure AD setup.

azure.activedirectory.tenant-id={tenantId}
azure.activedirectory.client-id={clientId}
azure.activedirectory.client-secret={clientSecret}
azure.activedirectory.user-group.allowed-groups=YOUR_GROUP_NAME

Enable security features in your Spring Boot application:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@SpringBootApplication
@EnableWebSecurity
public class YourApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

Configure security settings in a separate class:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .oauth2Login();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }
}

Secure your endpoints based on authorization:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YourController {

    @GetMapping("/secured")
    public String securedEndpoint() {
        return "This is a secured endpoint!";
    }

    @GetMapping("/public")
    public String publicEndpoint() {
        return "This is a public endpoint!";
    }
}

With this setup, your Spring Boot backend will authenticate users using Azure AD. Only authorized users will be able to access secured endpoints. Adjust the group name in azure.activedirectory.user-group.allowed-groups according to your requirements.

This configuration ensures that your Java Spring Boot backend is secure and only allows authenticated users to access the protected endpoints, thanks to Azure AD authentication.

Suleyman Cabir Ataman, PhD

Azure Blob Storage and C# Integration

Azure Blob Storage is one of Microsoft Azure's storage solutions. Think of it as a massive cupboard in the cloud Read more

Architectural Design Patterns 4 – Event-Driven Architecture

Event-Driven Architecture is currently enjoying a lot of attention from businesses around the world due to the enhanced capabilities offered Read more

MongoDB through C# – Using the Official Library

MongoDB is a popular NoSQL database, which means it doesn't use tables like traditional databases. Instead, it saves data as Read more

Redux vs. useContext: Navigating the State Management Maze

Every developer knows that the software engineering isn't just about writing code. It's about creating efficient, maintainable, and scalable systems. Read more

Sharing on social media:

Suleyman Cabir Ataman

Leave a Reply