Spring Custom Security Example

Spring Custom Security Example :

Step 1: Create Spring Boot Starter Project :

The sample main class will be like this :

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

}

Step 2 : Write Rest Controller class :

package com.example.demo.controllers;

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

@RestController
public class BankController {	
	@GetMapping("/fetch-balance")
	public String getBalance() {
		return "Balance Fetched Successfully";
	}

	@GetMapping("/view-alerts")
	public String getAlerts() {
		return "Sample Alerts for you";
	}
}

Step 3 : Write Security Configuration class as below :

package com.example.demo.security;
import java.util.Arrays;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class WebSecurity {
	
	@Bean
	PasswordEncoder passwordEncoder() {
		return new  BCryptPasswordEncoder();
	}
	
	@Bean
	UserDetailsService UserDetailsService() {
		
		InMemoryUserDetailsManager inMemoryUserDetailsManager =new InMemoryUserDetailsManager();
		UserDetails userDetails = User.withUsername("crtr4u").password(passwordEncoder().encode("crtr4u")).authorities(Arrays.asList()).build();
		inMemoryUserDetailsManager.createUser(userDetails);
		return inMemoryUserDetailsManager;
	}
	
	@Bean
	SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http.httpBasic(Customizer.withDefaults());
		http.authorizeHttpRequests(request->request.requestMatchers("/fetch-balance").authenticated()
				.requestMatchers("/view-alerts").permitAll()
		);	
		return http.build();
	}	
}

Leave a Reply

Your email address will not be published. Required fields are marked *