When I use security.basic.enabled=false to disable security on a Spring Boot project that has the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
I see the following Exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration$ManagementWebSecurityConfigurerAdapter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setObjectPostProcessor(org.springframework.security.config.annotation.ObjectPostProcessor); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
In order to fix this exception I had to add the property - management.security.enabled=false . My understanding is that when the actuator is in the classpath, both security.basic.enabled=false and management.security.enabled=false should be set to disable the security.
Could someone please let me know if my understanding is wrong?
In case you have spring-boot-actuator in your package, you should add the following
#EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration.class})
With older Spring-boot, the class was called ManagementSecurityAutoConfiguration.
In newer versions this has changed to
#SpringBootApplication(exclude = {
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration.class}
)
UPDATE
If for reactive application you are having the same issue, you can exclude the following classes
#SpringBootApplication(exclude = {ReactiveSecurityAutoConfiguration.class, ReactiveManagementWebSecurityAutoConfiguration.class })
What also seems to work fine is creating a file application-dev.properties that contains:
security.basic.enabled=false
management.security.enabled=false
If you then start your Spring Boot app with the dev profile, you don't need to log on.
For Spring Boot 2 following properties are deprecated in application.yml configuration
security.basic.enabled: false
management.security.enabled: false
To disable security for Sprint Boot 2 Basic + Actuator Security following properties can be used in application.yml file instead of annotation based exclusion
(#EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}))
spring:
autoconfigure:
exclude[0]: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
exclude[1]: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
For application.properties syntax would be like
spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
If you need security as a dependency but don't want Spring Boot to configure it for you, you can use this exclusion:
#EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class
})
For the spring boot 2 users it has to be
#EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class
})
Step 1: Comment annotation #EnableWebSecurity in your security config
//#EnableWebSecurity
Step 2: Add this to your application.properties file.
security.ignored=/**
spring.security.enabled=false
management.security.enabled=false
security.basic.enabled=false
For more details look here: http://codelocation.com/how-to-turn-on-and-off-spring-security-in-spring-boot-application/
Add following class into your code
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* #author vaquar khan
*/
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated().and().csrf().disable();
}
}
And insie of application.properties add
security.ignored=/**
security.basic.enabled=false
management.security.enabled=false
Answer is to allow all requests in WebSecurityConfigurerAdapter as below.
you can do this in existing class or in new class.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
Please note : If ther is existing GlobalMethodSecurityConfiguration class, you must disable it.
If you are using #WebMvcTest annotation in your test class
#EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
#TestPropertySource(properties = {"spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration"})
doesn't help you.
You can disable security here
#WebMvcTest(secure = false)
The easiest way for Spring Boot 2 without dependencies or code changes is just:
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Permit access to everything using antMatchers("/")
protected void configure(HttpSecurity http) throws Exception {
System.out.println("configure");
http.csrf().disable();
http.authorizeRequests().antMatchers("/").permitAll();
}
I simply added security.ignored=/**in the application.properties,and that did the charm.
The only thing that worked for me:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
}
and
security.ignored=/**
Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.
You need to add this entry to application.properties to bypass Springboot Default Security
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
Then there won't be any authentication box.
otrws, credentials are:-
user and 99b962fa-1848-4201-ae67-580bdeae87e9 (password randomly generated)
Note: my springBootVersion = '1.5.14.RELEASE'
You can configure to toggle spring security in your project by following below 2 steps:
STEP 1:
Add a #ConditionalOnProperty annotation on top of your SecurityConfig class. Refer below:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity (prePostEnabled = true)
#ConditionalOnProperty (name = "myproject.security.enabled", havingValue = "true", matchIfMissing = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// your security config
}
STEP 2:
Add following config to your application.properties or application.yml file.
application.properties
security.ignored=/**
myproject.security.enabled=false
OR
application.yml
security:
ignored: /**
myproject:
security:
enabled: false
In order to avoid security you can use annotations.
Use this annotation on top of configure class:
#EnableWebSecurity
For example:
#EnableWebSecurity
#Configuration
public class AuthFilter{
// configured method
}
As previously multiple solutions mentioned to disable security through commenting of
#EnableWebSecurity
annotation and other is through properties in application.properties or yml. But those properties are showing as deprecated in latest spring boot version.
So, I would like to share another approach to configure default username and password in your application-dev.properties or application-dev.yml and use them to login into swagger and etc in development environment.
spring.security.user.name=admin
spring.security.user.password=admin
So, this approach will also provides you some kind of security as well and you can share this information with your development team. You can also configure user roles as well, but its not required in development level.
Latest spring 2.7.x, create two class, set DISABLE_KEYCLOAK_AUDIT_PROPERTY = 'your key' in application profile for enable/disable security:
public static final String DISABLE_KEYCLOAK_AUDIT_PROPERTY = "enable_security";
#EnableAutoConfiguration(exclude =
{org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration.class
})
#Configuration
#ConditionalOnProperty(name = DISABLE_KEYCLOAK_AUDIT_PROPERTY, havingValue = "true")
static
class DisableSecurityConfig {
}
#Configuration
#ConditionalOnProperty(name = DISABLE_KEYCLOAK_AUDIT_PROPERTY, havingValue = "false")
#Import({KeycloakSecurityConfig.class, KeycloakConfig.class})
static
class EnableSecurityConfig {
}
for example use in application.yml:
enable_security: true
Add the below lines to your main app.
Remove org.activiti.spring.boot.SecurityAutoConfiguration.class if you're not using activiti.
Similarly, remove the one for actuator if you're not using spring-boot-actuator.
#EnableAutoConfiguration(exclude = {
org.activiti.spring.boot.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration.class,
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class })
With Gradle and Spring boot v2.4.4, you can exclude spring security completely by adding this config in your build.gradle
configurations.all {
exclude group:"org.springframework.boot", module: "spring-boot-starter-security"
}
As of Spring Boot 2.7.3 using #EnableAutoConfiguration(exclude = {}) generated an error, suggesting the exclude property be used in the #SpringBootApplication annotation.
Here is what worked for me when disabling Spring Security completely.
#SpringBootApplication(
exclude = {
SecurityAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class
})
public class GeoServiceApplication {
public static void main(String[] args) {
SpringApplication.run(GeoServiceApplication.class, args);
}
}
I tried excluding only SecurityAutoConfiguration.class, but I got an error for no HttpSecurity bean defined for ManagementWebSecurityAutoConfiguration.class.
With Spring 2.6.0 this helped in my case:
#EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityDataConfiguration.class
})
And additional I had to remove the dependency in the pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
In Spring Security 5.7.0-M2 WebSecurityConfigurerAdapter was deprecated. Spring Security team encourages users to move towards a component-based security configuration.
package com.may.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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 http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll(); // config to permit all requests
return http.build();
}
#Bean
public AuthenticationManager authenticationManager() { // to delete default username and password that is printed in the log every time, you can provide here any auth manager (InMemoryAuthenticationManager, etc) as you need
return authentication -> {
throw new UnsupportedOperationException();
};
}
}
More examples here:
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
I added below settings in application.yml and worked fine.
security:
route-patterns-to-be-skipped:
- /**/*
this can be converted as security.route-paterns-to-be-skipped=/**/* for application.properties
Related
I am going to use springfox (2.6.1v) with swagger-ui in my Spring Boot (1.4.2v).
The configuration for it looks:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.genericModelSubstitutes(ResponseEntity.class);
}
}
The problem is that my swagger is behind spring security and I need to allow access there only by admin.
Question is what should be the set of matchers to allow swagger-ui to work within my application?
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("??? <<<what_should_be_here>>> ???") // what should be here?
.hasRole("TENANT_ADMIN");
}
}
Ok first I have found the solution here so following lines:
.antMatchers("/admin/system/state/*", "/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**")
But still sth did not work and because of that I have asked this question. But after deeper investigation it occured that spring-fox does not support GSON. When you use GSON as "to json" converter swagger-ui receives a slightly different JSON format what causes problems...
When we changed converter to Jackson and added above paths to spring-config it works without any problems.
I have even requested the new feature on spring-fox github here.
While testing Spring Boot (1.3.3) with a simple web app using spring-boot-starter-security:1.3.3:RELEASE I observed the following behaviour:
In order to override the default Spring web security configuration, I supplied a custom Java configuration class like so:
#Configuration
// #EnableWebSecurity apparently obsolete ?
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// http security checking left out for brevity ...
}
#Override
protected void configure(
AuthenticationManagerBuilder auth) throws Exception {
// user authentication left out for brevity ...
}
}
After startup, the application redirects to the login page and checks username/password correctly whether the #EnableWebSecurity annotation is provided or not (like in the example above). Is this annotation in this context therefore obsolete ? If so, why ?
The auto configuration of Spring Boot automatically enables web security and retrieves all beans of the type WebSecurityConfigurerAdapter to customize the configuration if certain conditions are met (spring-boot-starter-security on the classpath etc.). The auto configuration for web security is enabled in the class org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration (Spring Boot 1.2.7, class name may have changed in newer versions).
I tried to upgrade from the 3.3.2 to the 3.4.0 version of spring data neo4j on search.maven.org but the build now gives the following exception:
AnnotationFormatError: Invalid default: public abstract java.lang.Class org.springframework.data.neo4j.config.EnableNeo4jRepositories.repositoryBaseClass()
The application works just fine in 3.3.2.
Here is the configuration class:
#Configuration
#EnableNeo4jRepositories(basePackages = { "it.data.neo4j.repository" })
#EnableTransactionManagement
#ComponentScan(basePackages = { "it.data.neo4j.service" })
public class Neo4JRepositoryConfiguration extends Neo4jConfiguration {
private static Logger logger = LoggerFactory.getLogger(Neo4JRepositoryConfiguration.class);
public static final String URL = "http://localhost:7474/db/data/";
public static final String LOGIN = "neo4j";
public static final String PASSWORD = "xxxx";
Neo4JRepositoryConfiguration() {
setBasePackage("it.data.neo4j.domain");
}
#Bean
GraphDatabaseService graphDatabaseService() {
return new SpringCypherRestGraphDatabase(URL, LOGIN, PASSWORD);
}
#Autowired
LocalContainerEntityManagerFactoryBean entityManagerFactory;
#Override
public PlatformTransactionManager neo4jTransactionManager(
GraphDatabaseService graphDatabaseService) {
return new ChainedTransactionManager(
new JpaTransactionManager(entityManagerFactory.getObject()),
new JtaTransactionManagerFactoryBean(graphDatabaseService).getObject());
}
}
The dependencies are:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>3.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-rest</artifactId>
<version>3.4.0.RELEASE</version>
</dependency>
Most likely a conflicting class path dependencies with spring-data-commons.jar
Make sure all jars on the class path are using the same version of spring-data-commons.
In my case I had 2 jars referencing both spring-data-commons.jar 1.10 and 1.11 which caused the issue.
Does your package it.data.neo4j.repository contain both JPA and Neo4j repositories? If so you may need to segregate them into separate packages.
Additionally, Spring Data Neo4j version 4 is a major shift from the previous versions and a bit of code migration is involved, it is possible your actual application code needs to be adjusted to be compatible with SDN4:
http://docs.spring.io/spring-data/neo4j/docs/4.0.0.RELEASE/reference/html/#migration
I have a rest webservice configured as a spring boot application.
All my rest urls have a base path "/api/...".
I am also serving static content from my application.
I need to configure security ONLY for the web service i.e., URLs that start with "/api/..." but give the other static content w/o applying security.
I've only seen examples where we filter some url patterns via:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/*");
}
but not otherwise ...
Use the antMatcher method of HttpSecurity class:
#Configuration
#EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/**");
// add security constraints for /api/... here
}
/* rest of config */
}
Instead of antMatcher, you can you regexMatcher wich can be a negation pattern
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().regexMatchers(XXXXX);
}
Answer to your last comment, if you are using latest spring framework and spring security then define below class and security config as per the config standards.
package org.springframework.security.samples.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
Also, look at below URL if you still find it difficult to get started with spring security.
http://docs.spring.io/spring-security/site/docs/3.2.6.RELEASE/reference/htmlsingle/#hello-web-security-java-configuration
I am trying to implement a Spring Boot version of Pet Clinic overriding as little of Spring Boot defaults as possible.
At this point, my logout link doesn't seem to work and I've been told that it is because I haven't properly added HttpSessionEventPublisher to my application.
How can I add HttpSessionEventPublisher to my application?
I've tried the following:
#Component
#Configuration
public class WebXmlConfig implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addListener(new HttpSessionEventPublisher());
}
}
and
#Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> getHttpSessionEventPublisher() {
return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
}
My main class does not extend any classes. If that is required for me to add HttpSessionEventPublisher, I would need to know which class also.
None of the Spring Boot examples log out properly, so I have nothing to based on off of.
Any help would be appreciated.