DEV Community

Ginto P
Ginto P

Posted on • Originally published at blog.gintophilip.com

1

Spring Security Basics: Implementing Authentication and Authorization-PART 3

Configuring security of the API end points

In this section, to configure the security of the API end points a custom security configuration needs to be created. To achieve this let's go through the following steps.

  1. Create the security configuration class

  2. Make all APIs to be accessed only by logged in users

  3. Allow /api/hello to be accessed by anyone

  4. Restrict access to /api/admin to user with ADMIN role only

Access to the end points will be configured as follows.

API Who can access
api/hello anyone
api/protected authenticated users
api/admin admin user

Create the security configuration class

To implement a custom security configuration by overriding the default one we need to create a configuration class. This can be done with the help of @Configuration annotation.

package com.gintophilip.springauth.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity securityConfig) throws Exception {
        return securityConfig
                .authorizeHttpRequests(auth->
                        auth.anyRequest().authenticated()
                ).formLogin(Customizer.withDefaults())
                .build();

    }
}
Enter fullscreen mode Exit fullscreen mode

This will serve as our initial configuration. Here, we have mandated that every request must be authenticated. In the coming steps, we will configure the security settings as required.

For logging in use the default user created by the Spring Security.

Make all APIs to be accessed only by logged in users

There is nothing to do. Because the initial configuration we created satisfied the requirement. Hence we don't need to specify any special configuration for the API endpoint /api/protected

Allow /api/hello to be accessed by anyone

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity securityConfig) throws Exception {
        return securityConfig
                .authorizeHttpRequests(auth->
                        auth.requestMatchers("/api/hello").permitAll().
                        anyRequest().authenticated()
                ).formLogin(Customizer.withDefaults())
                .build();
    }
Enter fullscreen mode Exit fullscreen mode

Now run the application and attempt to access the APIs. The endpoint /api/hello is now accessible to everyone, while all other endpoints still require users to log in.

Restrict access to /api/admin to user with the ADMIN role only.

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity securityConfig) throws Exception {
        return securityConfig
                .authorizeHttpRequests(auth->
                        auth.requestMatchers("/api/hello")
                                .permitAll()
                                .requestMatchers("/api/admin").hasRole("ADMIN")
                                .anyRequest().authenticated()
                ).formLogin(Customizer.withDefaults())
                .build();
    }
Enter fullscreen mode Exit fullscreen mode

At this point, the only API endpoint accessible to users is /api/hello. All other endpoints are restricted by a login screen.

https://blog.gintophilip.com/series/spring-security-authentication-and-authorization

Image of Bright Data

Maximize Data Efficiency – Store and process vast amounts efficiently.

Optimize your infrastructure with our solutions designed for high-volume data processing and storage.

Optimize Now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay