Can't configure antMatchers after anyRequest (Multiple antMatcher) - java

I am trying to configure Spring Security and get this following error:
Caused by: java.lang.IllegalStateException: Can't configure antMatchers after anyRequest
This is my SecurityConfig class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable();
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/rest/**").permitAll()
.anyRequest().authenticated()
.and()
.authorizeRequests()
.antMatchers("/secure/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll();
http
.authorizeRequests()
.antMatchers("/login").permitAll();
}
#Bean
public BCryptPasswordEncoder encodePWD(){
return new BCryptPasswordEncoder();
}
}
I already tried call httpSecurityauthorizeRequests().anyRequest().authenticated() as mentioned here,
still didn't work
...any suggestion would be helpfull.

Modify the rule as follows . .anyRequest().authenticated() to be used only once .
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/rest/**").permitAll()
.and()
.authorizeRequests()
.antMatchers("/secure/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll();

It might help someone for same kind of Exception
Here is my code:-
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/**")
.hasAnyRole()
.and()
.formLogin();
}
I just removed the call to super class :- super.configure(http); It worked for me. Just remove that line.

Authenticated should come last
httpSecurity.csrf().disable()
.cors()
.and().authorizeRequests()
.antMatchers("xyz").permitAll()
.antMatchers("abc")
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);

protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.cors()
.disable()
.authorizeRequests()
.antMatchers("/login", "/user/createUser")
.permitAll()
.antMatchers(HttpMethod.OPTIONS)
.permitAll()
.anyRequest()
.authenticated()
.and().exceptionHandling()
.authenticationEntryPoint(unautorizeHandler)
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

Related

H2-Database console not opening with Spring-Security

I'm using the H2-Database and Spring Security, but I'm unable to open it in the browser at http://localhost:8080/h2-console
Here my pom.xml (only the H2 entry)
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Here my application.properties
spring.datasource.url=jdbc:h2:file:/data/noNameDB
spring.h2.console.enabled=true
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.path=/h2-console
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false
And here is my SecurityConfig.java
import com.example.noName.security.JwtAuthenticationEntryPoint;
import com.example.noName.security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#Configuration
#EnableWebSecurity
public class SecurityConfig {
private static final String[] AUTH_WHITE_LIST = {
"/v3/api-docs/**",
"/swagger-ui/**",
"/v2/api-docs/**",
"/swagger-resources/**",
"/h2-console/**",
"/console/**",
"/account/**"
};
#Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
#Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers(AUTH_WHITE_LIST)
.permitAll()
.and()
.headers()
.frameOptions()
.disable()
.and()
.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.httpBasic();
return http.build();
}
}
The following is shown in the console if I try to access the console via http://localhost:8080/h2-console
INFO 3664 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 3664 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
INFO 3664 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
I have already tried everything I could find on the Internet.
The funny thing is that the "exception handling" works for Swagger.
If I try to access the database via:
http://localhost:8080/h2-console
I always get the error:
401 - Unauthorized
Each one is strange, because the access was allowed in the SecurityConfig.
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers(AUTH_WHITE_LIST)
.permitAll()
.and()
.headers()
.frameOptions()
.disable()
.and()
.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.httpBasic();
return http.build();
}
I can access the database through an internal database test. This is provided by Intellij.
However working/editing in the database is not possible through this.
AND:
If I change the AUTH_WHITE_LIST to this, it works.
private static final String[] AUTH_WHITE_LIST = {
"/**"
};
I could reproduce with spring-boot:3.0.0(web, security, h2, ...) and:
return http
.authorizeHttpRequests()
.requestMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.csrf().ignoringRequestMatchers("/h2-console/**")
.and()
.headers().frameOptions().sameOrigin()
.and()
.build();
(/h2-console is still protected!)
Fix:
(spring-boot-way):
import static //
org.springframework.boot.autoconfigure.security.servlet.PathRequest.toH2Console; // !
...
.requestMatchers(toH2Console()).permitAll()
...
.csrf().ignoringRequestMatchers(toH2Console())
Refs:
https://jessitron.com/2020/06/15/spring-security-for-h2-console/
PathRequest
It uses internally:
new AntPathRequestMatcher(h2ConsoleProperties.get().getPath() + "/**");
which seems to be different/better than the requestMatcher(String... paths) (AbstractRequestMatcherRegistry), which invokes this (with method==null):
public C requestMatchers(HttpMethod method, String... patterns) {
List<RequestMatcher> matchers = new ArrayList<>();
if (mvcPresent) {
matchers.addAll(createMvcMatchers(method, patterns)); // <- we land here obviously
} else {
matchers.addAll(RequestMatchers.antMatchers(method, patterns));
}
return requestMatchers(matchers.toArray(new RequestMatcher[0]));
}
... alternatives:
RequestMatchers.antMatcher(null, pathToH2+"/**").
AntPathRequestMatcher (for ignore case (and all http methods), prefer constructors to factories;)
MvcMatcher (is not possible for h2-console, since it is not mvc;(
BUT/AND
I would not do it (unsecured) in production!
According to the post on spring blog about Spring Security without the WebSecurityConfigurerAdapter we can use WebSecurityCustomize for ignoring the whole endpoint from the security.
The case fits perfectly to publish the h2 console, because we want to ignore only this particular endpoint in the case of security.
The working example:
#Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers(new AntPathRequestMatcher(H2_CONSOLE_PATH));
}
And that's all what we need, probably the cleanest solution to this problem.
You can also explicitly fallback to antMatcher inside requestMatchers:
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
....
.....
return http
.authorizeHttpRequests()
.requestMatchers(antMatcher("/h2-console/**")).permitAll()
.anyRequest().authenticated()
.and()
.build();
I've found this article, where the question is well explained:
h2-database-console-with-spring-security
Note: The article is not updated to Spring Security 6, due the known deprecation of the WebSecurityConfigurerAdapter class.
The code should be updated to:
package com.myapp.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.boot.autoconfigure.security.servlet.PathRequest.toH2Console;
#Configuration
public class CustomSecurityConfiguration{
#Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.requestMatchers("/").permitAll()
.requestMatchers(toH2Console()).permitAll()
.and().csrf().ignoringRequestMatchers(toH2Console())
.and().formLogin()
.and().httpBasic();
// Use them only in development or demo environments. NEVER in production !!!
// http.csrf().disable();
http.headers().frameOptions().disable();
return http.build();
}
}

Spring Security login/logout Swagger

How to get login/logout option in Swagger? After app starting I can click on the secure endpoint and I'm asked about my credentials. After successfully logging all works with no problem but I don't have option in Swagger to logout to change user. I can only use localhost:8080/logout. I get a proper communicate I'm logout but when I go again on localhost:8080/swagger-ui/ I'm still logged on the previous user. I want to get some just like that:
My Spring Security config:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] permitAllEndpoints = {
"/api/registration",
"/h2/console/**",
"/v2/api-docs",
"/v3/api-docs/**",
"/swagger-resources/**",
"/swagger-ui/**"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.formLogin()
.permitAll()
.and()
.logout()
.permitAll()
.and()
.authorizeRequests()
.mvcMatchers(permitAllEndpoints)
.permitAll()
.mvcMatchers("api/admin/**")
.hasAnyAuthority("ADMIN")
.anyRequest()
.authenticated()
.and()
.csrf()
.disable()
.headers()
.frameOptions()
.disable();
}
}
My Swagger config:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
#Configuration
class SwaggerConfig {
#Bean
Docket api() {
return new Docket(DocumentationType.OAS_30)
.select()
.paths(PathSelectors.ant("/api/**"))
.build();
}
}

Spring 2 WebSecurity different Authentifications not working as intended

I'm currently struggling with the WebSecurityConfig from Spring. I do have a service which is protected with an IPAuthProvider (only whitelisted IPs can access the service). For monitoring reasons I exposed a /prometheus endpoint and I don't want the IPAuth there but only Basic Auth. However, the following code adds IPAuth AND Basic Auth to the /prometheus endpoint.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig {
#Order(2)
#Configuration
public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final IpAuth ipAuth;
private final CustomAuthenticationFailureHandler failureHandler;
private final CustomAuthenticationSuccessHandler successHandler;
public WebSecurityConfig(IpAuth ipAuth,
CustomAuthenticationFailureHandler failureHandler, CustomAuthenticationSuccessHandler successHandler) {
this.ipAuth = ipAuth;
this.failureHandler = failureHandler;
this.successHandler = successHandler;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/refresh")
.permitAll()
.antMatchers("/css/*.css", "/js/*.js")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/loginPage")
.failureHandler(failureHandler)
.successHandler(successHandler)
.and()
.logout()
.logoutUrl("/logoutPage")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.csrf()
.disable();
}
#Override
public void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(ipAuth);
}
}
#Order(1)
#Configuration
public static class PrometheusConfig extends WebSecurityConfigurerAdapter{
private final PrometheusEntryPoint prometheusEntryPoint;
public PrometheusConfig(SystemConfig systemConfig, PrometheusAuthEntryPoint prometheusAuthEntryPoint){
this.prometheusAuthEntryPoint=prometheusAuthEntryPoint;
this.systemConfig = systemConfig;
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.antMatcher("/prometheus")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(prometheusAuthEntryPoint);
}
}
}
Any help or hint is highly appreciated, I
m really stuck at this point.
Thanks in advance!
You can configure your WebSecurityConfig in such way that processes all the request that do not start with /prometheus.
httpSecurity
.regexMatcher("^(?!/prometheus/).*$")
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/refresh")
.permitAll()
.antMatchers("/css/*.css", "/js/*.js")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/loginPage")
.failureHandler(failureHandler)
.successHandler(successHandler)
.and()
.logout()
.logoutUrl("/logoutPage")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.csrf()
.disable();

Override Spring Security configure(HttpSecurity) when overridden in a Maven dependency

I have a Maven Spring Boot 2 with Spring Security project. One of the maven dependencies extends WebSecurityConfigurerAdapter. e.g.,
public class MyConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
.and()
.csrf()
.and()
.formLogin()
.permitAll()
.successHandler(myLoginHandler)
.failureHandler(formAuthFailureHandler)
.and()
.logout()
.permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher(logoutUrl()))
.logoutSuccessUrl(logoutSuccessUrl())
.and()
.authorizeRequests()
.antMatchers(publicRoutes())
.permitAll()
.antMatchers(HttpMethod.POST).authenticated()
.antMatchers(HttpMethod.PUT).authenticated()
.antMatchers(HttpMethod.PATCH).authenticated()
.antMatchers(HttpMethod.DELETE).denyAll()
.anyRequest()
.authenticated();
}
}
The problem is in this application I need to override successHandler() and add a logout handler like this logout().addLogoutHandler(myLogoutHandler).
Is it possible to just update these bits, or will I need to define the whole chain again? Maybe something like this,
public class AnotherConfig extends MyConfig {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
.and()
.csrf()
.and()
.formLogin()
.permitAll()
.successHandler(myLoginHandler)
.failureHandler(formAuthFailureHandler)
.and()
.logout()
.addLogoutHandler(myLogoutHandler)
.permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher(logoutUrl()))
.logoutSuccessUrl(logoutSuccessUrl())
.and()
.authorizeRequests()
.antMatchers(publicRoutes())
.permitAll()
.antMatchers(HttpMethod.POST).authenticated()
.antMatchers(HttpMethod.PUT).authenticated()
.antMatchers(HttpMethod.PATCH).authenticated()
.antMatchers(HttpMethod.DELETE).denyAll()
.anyRequest()
.authenticated();
}
}
I was hoping there might be a single setter for these two values somewhere.
Thanks
You need to set order of overriding one to higher that overridden one.
#Order(Ordered.LOWEST_PRECEDENCE - 1)
public class AnotherConfig extends MyConfig {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
.and()
.csrf()
.and()
.formLogin()
.permitAll()
.successHandler(myLoginHandler)
.failureHandler(formAuthFailureHandler)
.and()
.logout()
.addLogoutHandler(myLogoutHandler)
.permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher(logoutUrl()))
.logoutSuccessUrl(logoutSuccessUrl())
.and()
.authorizeRequests()
.antMatchers(publicRoutes())
.permitAll()
.antMatchers(HttpMethod.POST).authenticated()
.antMatchers(HttpMethod.PUT).authenticated()
.antMatchers(HttpMethod.PATCH).authenticated()
.antMatchers(HttpMethod.DELETE).denyAll()
.anyRequest()
.authenticated();
}
}
Why Ordered.LOWEST_PRECEDENCE - 1?
Because the default order is Ordered.LOWEST_PRECEDENCE as set for overridden class.
Or you can set it a specific number for overridden.

Spring security configuration: enable/disable authentication

my question is like this:
I want to disable and enable authentication through configuration in class which extends WebSecurityConfigurerAdapter. I have test which expects that status is unauthroized if there is no login info provided. This is configuration class:
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
public static final String USER = "workshop-user";
public static final String ADMIN = "workshop-admin";
#Value("${WORKSHOP_USER_PASSWORD:user}")
private String userPassword;
#Value("${WORKSHOP_ADMIN_PASSWORD:admin}")
private String administratorPassword;
#Value("${features.security.disable}")
private boolean securityDisable;
#Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder(9);
}
#Override
#Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(USER)
.password(encoder().encode(userPassword))
.roles("CLIENT_APP")
.and()
.withUser(ADMIN)
.password(encoder().encode(administratorPassword))
.roles("CLIENT_APP", "ADMINISTRATOR");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
if(!securityDisable) {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/**/import").hasRole("ADMINISTRATOR")
.antMatchers("/api-docs/**", "/swagger-resources/**", "/v2/api-docs", "/**/favicon.ico", "/webjars/**", "/api/admin/health").permitAll()
.anyRequest().permitAll()
//replace .permitAll() with .authenticated() for authentiaction
//replace .authenticated() with .permitAll() for disabling security
.and()
.csrf().disable()
.headers().disable()
.httpBasic();
}
else{
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/**/import").hasRole("ADMINISTRATOR")
.antMatchers("/api-docs/**", "/swagger-resources/**", "/v2/api-docs", "/**/favicon.ico", "/webjars/**", "/api/admin/health").permitAll()
.anyRequest().authenticated()
//replace .permitAll() with .authenticated() for authentiaction
//replace .authenticated() with .permitAll() for disabling security
.and()
.csrf().disable()
.headers().disable()
.httpBasic();
}
}
and this is my flag from application.properties
features.security.disable = true
I have tried to find another way to do it through configuration but couldn't come to another answer. The thing is that i know it is very simple becaues of if/else statement. One is authenticated and the other permitAll entries. Do you know is there a way that uses "better aproach" which does not pollute code with duplication like this? I tried to look in documentation and other posts but couldn't find any relevant information for me.
You can create two security configurations
#Configuration
#Profile("prod")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/**/import").hasRole("ADMINISTRATOR")
.antMatchers("/api-docs/**", "/swagger-resources/**", "/v2/api-docs", "/**/favicon.ico", "/webjars/**", "/api/admin/health").permitAll()
.anyRequest().authenticated()
//replace .permitAll() with .authenticated() for authentiaction
//replace .authenticated() with .permitAll() for disabling security
.and()
.csrf().disable()
.headers().disable()
.httpBasic();
}
}
#Configuration
#Profile("test")
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/**/import").hasRole("ADMINISTRATOR")
.antMatchers("/api-docs/**", "/swagger-resources/**", "/v2/api-docs", "/**/favicon.ico", "/webjars/**", "/api/admin/health").permitAll()
.anyRequest().permitAll()
//replace .permitAll() with .authenticated() for authentiaction
//replace .authenticated() with .permitAll() for disabling security
.and()
.csrf().disable()
.headers().disable()
.httpBasic();
}
}
Run based on your requirement
-Dspring.profiles.active=prod
-Dspring.profiles.active=test

Categories