Monday, May 22, 2023

How to Enable Disable Spring Security in Spring Boot? Example Tutorial

Hello guys, if you are wondering how to enable and disable Spring Security in a Spring Boot based Java application then you have come to the right place. In the past, I have shared best Spring security courses25 Spring Security questions, as well multiple Spring security tutorials like how to use HTTP Basic auth in Spring Security etc.  and in this article, I will share multiple ways to enable and disable Spring Security in a Spring boot application. But, before that, if you are new to Spring Security then find out what is Spring Security and how does it work?  At its core, Spring Security is simply a bunch of servlet filters that assist you with adding authentication and authorization to your web application. 

It additionally incorporates well with frameworks like Spring Web MVC (or Spring Boot), as well similarly as with norms like OAuth2 or SAML. And it auto-creates login/logout pages and safeguards against normal endeavors like CSRF.  Further, we will learn how to disable/enable Spring security, but first, we will what is Default Security Setup.

Default Security Setup

To add security to our Spring Boot application, we need to add the security starter dependency:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-security</artifactId> 
</dependency>

This will likewise incorporate the SecurityAutoConfiguration class containing the underlying/default security setup.

Notice how we didn't indicate the version here, with the supposition that the project is as of now involving Boot as the parent.

By default, the Authentication gets empowered for the Application. Additionally, the satisfied discussion is utilized to decide whether essential or formLogin ought to be utilized.

There are some predefined properties:

spring.security.user.name 
spring.security.user.password

On the off chance that we don't design the secret phrase utilizing the predefined property spring.security.user.password and begin the application, a default secret phrase is haphazardly created and imprinted in the control center log:

Using default security password: c8be15de-4488-4490-9dc6-fab3f91435c6


Conditionally Disabling Spring Boot Security

Assuming that you are wanting to have your own Custom Security setup for your Spring boot application, here is a portion of the ways of doing it.

Option 1:

First, we will reject spring security Auto-design and afterward control enable/disable security utilizing config parameter.

To disable Security Auto-Configuration and add our own design, we really want to prohibit the SecurityAutoConfiguration class from auto-setup.

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


In the event that you have a spring-boot-actuator included in your dependencies, you really want to bar ManagementWebSecurityAutoConfiguration class from auto-setup.

@SpringBootApplication(exclude = 
{ SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
    public class MySpringBootApplication { 
        public static void main(String[] args) { 
            SpringApplication.run(MySpringBootApplication.class, args); 
    } 
}

Overriding Security Auto-Configuration

The vast majority of times we impair Spring Security Auto Configuration just for altering the security arrangement of our Spring Boot applications. To redo security for the Spring boot Application we want to have class and Annotate with @EnableWebSecurity, which will apply the class to the global WebSecurity.

Extend WebSecurityConfigurerAdapter, which provides you configuration methods, and can be used to specify what URIs to protect or pass through @Configuration


@EnableWebSecurity
public class CustomWebSecurityConfiguration extends
WebSecurityConfigurerAdapter {
}


Enable/Disable Security using the config field


In the wake of impairing Auto-Configuration of Security, we have some control over empowering or crippling custom security design utilizing config parameters.
Typical use-case can be,
  • Having multiple deployment requirements
  • Migrating legacy security setup to Spring Boot @Configuration

@ConditionalOnProperty{ prefix = "app.security.custom",
name = "enabled",
havingValue="true"}
@EnableWebSecurity
public class CustomWebSecurityConfiguration extends
WebSecurityConfigurerAdapter {
}


You can likewise restrictively empower and cripple security for certain profiles by adding @Profile.


Option 2:

We can likewise control empowering and impairing of the security utilizing WebSecurity design. Something like this.

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfiguration extends
    WebSecurityConfigurerAdapter {


    @Value{"${security.enable:true}"}
    private boolean securityEnable;


    @Override
    public void configure{WebSecurity web} throws Exception {


    if {securityEnabled} {
    //only URI 'unsecured/**' is freely accessible.
    web.ignoring().antMatchers{"/unsecured/**"};
    }
    else{
    // all URI's are freely accessible.
    web.ignoring().antMatchers("/**");
    }
  }
}

WebSecurity ignoring() method will disregard demand design from the security channel chain completely and Spring Security's highlights will generally not be accessible. WebSecurity is based above HttpSecurity.

Difference between Spring Boot 2 Security and Spring Boot 1 Security

Contrasted with Spring Boot 1, Spring Boot 2 has incredibly improved on the auto-setup.

In Spring Boot 2, on the off chance that we need our own security design, we can basically add a custom WebSecurityConfigurerAdapter. This will cripple the default auto-design and empower our custom security arrangement.

Spring Boot 2 additionally utilizes the majority of Spring Security's defaults. Thus, a portion of the endpoints that were unstable naturally in Spring Boot 1 is now secured by default.

These endpoints incorporate static assets, for example, /css/**, /js/**, /pictures/**, /webjars/**, /** /favicon.ico and the error endpoint. Assuming we really want to permit unauthenticated admittance to these endpoints, we can expressly design that.

How to Disable and Enable Spring Security in Spring Boot? Example Tutorial


To work on the security-related arrangement, Spring Boot 2 has taken out these Spring Boot 1 properties:

security.basic.authorize-mode 
security.basic.enabled 
security.basic.path 
security.basic.realm 
security.enable-csrf 
security.headers.cache 
security.headers.content-security-policy 
security.headers.content-security-policy-mode 
security.headers.content-type 
security.headers.frame 
security.headers.hsts 
security.headers.xss 
security.ignored 
security.require-ssl 
security.sessions



That's all about how to enable and disable Spring Security in a Spring Boot application. In this tutorial, we zeroed in on the default security arrangement given by Spring Boot. We perceived how the security auto-setup component can be disabled or overridden. You also learned how to setup Spring security for your Java and Spring Boot applicaiton. 

Other Java and Spring articles you may like
  • 15 Microservices Interview questions (answers)
  • 5 courses to learn Spring Boot and Spring Cloud ( courses)
  • Difference between Mock and MockBean in Spring boot (mock vs mockbean)
  • 15 Spring Cloud Interview Questions for Java developers (answers)
  • How to set base URL for REST API in Spring? (base url exmaple)
  • 5 Courses to learn Spring Cloud and Microservices (courses)
  • 3 ways to change Tomcat port in Spring Boot (tutorial)
  • 10 Courses to learn Spring Security with OAuth 2 (courses)
  • 10 Advanced Spring Boot Courses for Java Programmers (courses)
  • 5 Spring Boot Annotations for full-stack Java developers (tutorial)
  • Top 5 Courses to learn Microservices in Java? (courses)
  • 5 Essential Spring MVC annotations for REST (annotations)
  • Top 5 Books and Courses to learn RESTful Web Service (books)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • 5 Course to Master Spring Boot online (courses)
  • 10 Spring MVC annotations Java developers should learn (annotations)
  • 15 Spring Data JPA Interview Questions with answers (questions)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)

Thanks for reading this article so far; if you find Java Spring Boot, and REST tutorial useful, please share them with your friends and colleagues.

P. S. - If you are new to Spring Boot and want to learn about Spring Boot and look for a free Spring Boot online course, I also recommend you join the Introducing Spring Boot (FREE ) class  on Udemy. It's one of the best free resource to learn Spring Boot for Java developers. 
     

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.