stock market

How to Change Default Behavior in Spring Security

Spread the love
1. What Spring Security Does ?.

Spring Security helps you control who can access your application and what they can do.

1. Authentication (Who are you?)

  • Verifies a user’s identity.
  • Supports multiple methods like:
    • Form login
    • HTTP Basic authentication
    • Social login (Google, GitHub, etc.)

2. Authorization (What can you do?)

  • Determines permissions after authentication.

3. Protection Against Attacks

Spring Security includes built-in defenses for:

  • CSRF (Cross-Site Request Forgery)
  • Session fixation
  • Clickjacking
  • XSS (Cross-Site Scripting)

if you want to learn the default behavior of spring security , default spring security.

2. What is anyRequest()

anyRequest() is a matcher that applies to all remaining HTTP requests that have not been matched by previous rules.

http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
);
3.What is permitAll()

permitAll() allows unrestricted access to a resource , no authentication required — anyone can access . we can permit all the requests coming towards our web applications APIs. Paths using Spring Security framework like shown below .

package com.rkdigitalschool.security.test.config;
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.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
        @Bean
        SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {                        
             http.csrf(csrf -> csrf.disable())
             .authorizeHttpRequests(requests -> requests
             .requestMatchers("/myAccount", "/myBalance", "/myCards").authenticated()
            .requestMatchers("/notices", "/contact").permitAll()
            .anyRequest().authenticated());
          return http.build();

          }
}

4. What is denyAll() ?

denyAll() is an authorization rule that blocks access completely to a specific request or endpoint. No one is allowed to access the resource not even authenticated users .

http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/secret").denyAll()
.anyRequest().authenticated()
);

5. What requestMatchers() ? .

 Spring Security, requestMatchers() is used to define which HTTP requests a security rule applies to. It is a core part of configuring authorization rules. You typically use it inside the authorizeHttpRequests() configuration .

1. requestMatchers(“/public/**”)

  • Matches all requests under /public/
  • permitAll() → no authentication needed

2. requestMatchers(“/admin/**”)

  • Matches /admin/ paths
  • Requires ADMIN role

3. requestMatchers(“/user/**”)

  • Matches /user/ paths
  • Requires USER or ADMIN

Example

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
.formLogin();
return http.build();
}
}
What is the purpose of formLogin()

formLogin() in Spring Security is used to enable a login page for users to enter username and password through a browser.

formLogin() tells Spring to create a login page (HTML form) so the user can log in using a browser.” What happens when you use formLogin(), Spring Security will automatically Show a default login page when you request any endpoint .

http://localhost:8080/myAccount , it will automatically redirect to login page  http://localhost:8080/login

Allow user to enter:

  • Username
  • Password

Authenticate the user and Redirect to requested page after login

Without formLogin()

If you don’t use formLogin():

  • No login page
  • Browser won’t show login form
  • Only API authentication (like Basic Auth) works
7. What is the purpose of httpBasic()

httpBasic() in Spring Security is used to enable Basic Authentication, where the username and password are sent with every request. httpBasic() tells Spring to Authenticate user using username + password in HTTP request headers not a with login page .

Where it is used

Mostly used in:

✔REST APIs
✔Postman / API testing
✔Backend services

http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
8. What is authorizeHttpRequests()

authorizeHttpRequests() in Spring Security is used to control who can access which URLs (endpoints) in your application.authorizeHttpRequests() tells Spring to Define access rules — which user can access which API .

What it does

  • Allow public access
  • Require login
  • Restrict based on roles/permissions
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public").permitAll()
.requestMatchers("/admin").authenticated()
);

 Common Methods used inside authorizeHttpRequests()

🔹 1. permitAll()

.requestMatchers("/home").permitAll()

🔹 2. authenticated()

.requestMatchers("/profile").authenticated()

🔹 3. hasAuthority()

.requestMatchers("/admin").hasAuthority("admin")

🔹 4. hasRole()

.requestMatchers("/admin").hasRole("ADMIN")

🔹 5. anyRequest()

.anyRequest().authenticated()
Custom security configurations

We can secure the web application APIs .Paths as per our custom requirements using Spring Security framework

  1. RkDigitalSchoolbankApplication.java
package com.rkdigitalschool.security.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RkDigitalSchoolbankApplication {
	public static void main(String[] args) {
	SpringApplication.run(RkDigitalSchoolbankApplication.class, args);
	}
}

2.SecurityConfig.java

package com.rkdigitalschool.security.test.config;
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.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {

	@Bean
	SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
		//http.authorizeHttpRequests((requests)->requests.anyRequest().permitAll());
		//http.authorizeHttpRequests((requests)->requests.anyRequest().denyAll());

		http.csrf(csrf -> csrf.disable()) 
		.authorizeHttpRequests(requests -> requests
				.requestMatchers("/myAccount", "/myBalance", "/myCards").authenticated()
				.requestMatchers("/notices", "/contact").permitAll()
				.anyRequest().authenticated()   // ✅ now it works
				);


		return http.build();
	}
}

3.AccountController.java

package com.rkdigitalschool.security.test.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor
@RestController
public class AccountController {
    @GetMapping("/myAccount")
    public String getAccountDetails() {
    return "account";
    }

}

4.BalanceController.java

package com.rkdigitalschool.security.test.controller;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
public class BalanceController {
    @GetMapping("/myBalance")
    public String getBalanceDetails(@RequestParam long id) {
        return "balance";
    }
}

5.CardsController.java

package com.rkdigitalschool.security.test.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class CardsController {
    @GetMapping("/myCards")
    public String getCardDetails(@RequestParam long id) {
    	return "cards";
    }
}

6.ContactController.java

package com.rkdigitalschool.security.test.controller;
import java.util.Random;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class ContactController {
    @GetMapping("/contact")
    public String saveContactInquiryDetails() {
        return "contact";
    }
   
    public String getServiceReqNumber() {
        Random random = new Random();
        int ranNum = random.nextInt(999999999 - 9999) + 9999;
        return "SR" + ranNum;
    }
}

7. LoansController.java

package com.rkdigitalschool.security.test.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequiredArgsConstructor
public class LoansController {
    @GetMapping("/myLoans")
    public String getLoanDetails() {
    	return "Loans";
    }
}

8. NoticesController.java

package com.rkdigitalschool.security.test.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@RequiredArgsConstructor
public class NoticesController {
    @GetMapping("/notices")
    public String getNotices() {
    	return "Notices";
    }
}

9.UserController.java

package com.rkdigitalschool.security.test.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Date;
import java.util.Optional;
@RestController
@RequiredArgsConstructor
public class UserController {
    @PostMapping("/register")
    public String registerUser() {
    	return "Usercontroller";
    }
}

10. WelcomeContoller.java

package com.rkdigitalschool.security.test.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeContoller {
	@GetMapping("/welcome")
	public String sayWelcome() {
		System.out.println("Welcome to Spring Application with security");
		return "Welcome to Spring Application with security";
	}
}

11. application.properties

spring.application.name=rest_security
spring.security.user.name=user
spring.security.user.password={noop}12345

Leave a Reply

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