I'm using spring boot for the first time in a project with angular, everything was working fine until I added the spring security dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Now I get this error in the client side:
Access to XMLHttpRequest at 'http://localhost:8080/api/v1/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I tried to change the config as the documentation suggest so I added class
src/main/java/com/example/securingweb/WebSecurityConfig.java
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer{
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
I also have this in my controller:
#CrossOrigin(origins = "http://localhost:4200")
As you have added Spring security dependency, so spring will enable Basic Auth which will validate your each and every request. And that enable CORS(Cross Origin Request Sharing) aswell. Though you have added CrossOrigin for every request that is not enough to disable the CORS.
More Details About CORS
So either you need to send the spring security generated token which will print on your console
or
you need to configure Spring security Configuration class which will validate your authetication or permit the specific url.
More about Spring Security here
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
#Configuration
public class CorsConfig {
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("GET","POST"));
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
import org.springframework.context.annotation.Bean;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.filter.CorsFilter;
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/h2-console/**"
);
}
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/offerTransactionCall").permitAll()
.anyRequest().authenticated();
}
}
Related
I'm creating an user API and trying to implement an authentication method through Spring Boot security.
Even using the correct password and the default Spring Security user user, my Postman still gives me an authorization error. I can't see where the problem is in this code.
Security config:
package com.api.business_products_management.config;
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.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()
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
}
}
Controller:
package com.api.business_products_management.controllers;
import com.api.business_products_management.dtos.UserDto;
import com.api.business_products_management.models.UserModel;
import com.api.business_products_management.services.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping("/user")
public class UserController {
private BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
#PostMapping
public ResponseEntity<Object> saveUser(#RequestBody #Valid UserDto userDto) {
var userModel = new UserModel();
BeanUtils.copyProperties(userDto, userModel);
userModel.setPassword(passwordEncoder().encode(userModel.getPassword()));
return ResponseEntity.status(HttpStatus.CREATED).body(userService.save(userModel));
}
}
Console:
2023-02-17T18:24:13.152-03:00 INFO 8418 --- [nio-8099-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-02-17T18:24:13.152-03:00 INFO 8418 --- [nio-8099-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-02-17T18:24:13.154-03:00 INFO 8418 --- [nio-8099-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Without seeing your Postman request, my initial guess would be that it's the lack of CSRF (from your Postman request) which is causing the 401. You can read more about CSRF within Spring here: https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html
From that document:
As of Spring Security 4.0, CSRF protection is enabled by default
You can test this theory by temporarily disabling CSRF as shown in the example configuration here:
https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html#csrf-configure
i.e.:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
}
}
I'd highly recommend reading the rest of the documentation to familiarize yourself with what CSRF protects against and whether it's an acceptable risk to turn it off (or selectively turn disable for certain paths) prior to disabling it in a production environment though.
In my Spring Boot app in which I've implemented Spring Security, I am currently running it on HTTPS but I want to expose a certain actuator endpoint on HTTP in order to Prometheus gets metrics from. Every tutorial I've found so far, has only the opposite. I know that the below code in my Main Class redirects all HTTP traffic to HTTPS but since I've already achieved that, I tried if I could modify the code for the opposite result only to no avail.
Then, I tried to check if somehow I could achieve my goal with,
management.server.ssl.enabled=false
management.server.port=8081
but I couldn't get any results in my browser in exposing Prometheus metrics, since for some reason the port isn't accesible.
So is it possible to have my whole application on HTTPS as it is right now, and redirect - expose just one Get Mapping mathod on HTTP? Just for testing purposes I have the Greeting Method below, in order to make my implementations.
Rest Controller Class (For Test Purposes)
package com.andrekreou.iot.control.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Sample {
#GetMapping(value = "/greeting")
public String greeting() {
return "I am working with both HTTP and HTTPS";
}
}
Security Config Class
package com.andrekreou.iot.authentication.security;
import com.andrekreou.iot.authentication.user.ApplicationUserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
#Configuration
#AllArgsConstructor
#EnableWebSecurity
public class ApplicationSecurityConfig {
private final ApplicationUserService applicationUserService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
#Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.requiresChannel()
.antMatchers("/greeting","/actuator/prometheus")
.requiresInsecure()
.and()
.authorizeRequests()
.antMatchers("/api/v*/registration/**","/register*","/login","/registration","/registration-complete","/greeting").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.permitAll()
.defaultSuccessUrl("/",true)
.and()
.logout()
.logoutUrl("/logout")
.clearAuthentication(true)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID","Idea-2e8e7cee")
.logoutSuccessUrl("/login");
return http.build();
}
#Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
#Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider =
new DaoAuthenticationProvider();
provider.setPasswordEncoder(bCryptPasswordEncoder);
provider.setUserDetailsService(applicationUserService);
return provider;
}
}
Main Class
package com.andrekreou.iot;
import io.micrometer.core.aop.TimedAspect;
import io.micrometer.core.instrument.MeterRegistry;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
public class IotApplication {
public static void main(String[] args) {
SpringApplication.run(IotApplication.class, args);
}
#Bean
public TimedAspect timedAspect(MeterRegistry registry) {
return new TimedAspect(registry);
}
#Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
#Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
Application.properties
#Server properties for HTTPS configuration
server.ssl.enabled=true
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:local-ssl.p12
server.ssl.key-store-password=<password>
server.ssl.key-alias=local_ssl
server.port=8443
This question already has answers here:
Why is my method undefined for the type object?
(4 answers)
Closed 2 years ago.
I'm building a spring application with spring security. I have added basic authentication of a username and password in the code. I want to access APIs via a reactjs web app with this basic authentication. For this, I'm trying to add the cors policy.
In the security configuration of spring security, I'm getting the error:
The method withDefaults() is undefined for the type SecurityConfiguration
I have got all the necessary dependencies installed.
What can be the possible solution?
Attaching my code below.
package com.example.demo;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.config.annotation.web.configurers.CorsConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors(withDefaults()) //getting the error here
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").authenticated()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers(HttpMethod.GET).authenticated()
.anyRequest().authenticated()
.and()
.httpBasic();
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedHeaders(List.of("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "OPTIONS"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
#Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
Your SecurityConfiguration, nor the WebSecurityConfigurerAdapter have a method withDefaults(). You need to add a static import:
import static org.springframework.security.config.Customizer.withDefaults;
I am developing rest APIs in Spring Boot. I am able to do CRUD operations and postman gives correct responses, but when I add Spring Security username and password Postman gives 401 Unauthorized.
I have provided a spring boot security username and password as below.
application.proptries
spring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/pal?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.security.user.name=root
spring.security.user.password=root
I have done basic auth with username as root and password as root.
Preview request gives headers updated successfully message :
EDIT
I have deleted the cookies in postman but still facing the same issue
SecurityConfing.java
My Security Configuration are as below.
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
#Configuration
#EnableWebSecurity
#Order(1000)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.jdbcAuthentication().dataSource(dataSource())
.usersByUsernameQuery(
"select email,password from user where email=? and statusenable=true")
.authoritiesByUsernameQuery(
"select email,role from user where email=? and statusenable=true");
System.out.println(authenticationMgr.jdbcAuthentication().dataSource(dataSource())
.usersByUsernameQuery(
"select email,password from user where email=? and statusenable=true")
.authoritiesByUsernameQuery(
"select email,role from user where email=? and statusenable=true"));
}
#Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/pal");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("");
return driverManagerDataSource;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.authorizeRequests().antMatchers("/admin/**").hasAnyRole("ROLE_ADMIN","ROLE_USER").anyRequest().permitAll()
.and()
.authorizeRequests().antMatchers("/user/**").hasAnyRole("ROLE_USER").anyRequest().permitAll();
}
#Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers(HttpMethod.POST,"/newuser").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(HttpMethod.POST,"/newuser/*").permitAll()
.antMatchers(HttpMethod.GET,"/master/*").permitAll()
.antMatchers(HttpMethod.GET,"/exploreCourse").permitAll()
.anyRequest().authenticated()
}
}
You need to configure Spring Security, by default all routes all secured for authrorization.
Please have a look JWT Token implementation at this Link.
If Authorization needed in spring boot, the below annotation at root configuration class.
#EnableAuthorizationServer
( and other required annotations)
public class Application{
....
....
}
Below dependency also needed to be added
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
I have an HTTP Spring Security configuration that appears to work when I comment out each individual aspect but it doesn't work when I combine the Spring Security rules together, so I know the problem is not with the regexMatcher or the antMatcher but with the rules applied in combination.
Here is my Spring Security class:
package com.driver.website.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import javax.servlet.http.HttpServletRequest;
import java.security.AccessControlContext;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${widget.headers.xframeoptions.domains.allowed}")
private String allowedXFrameOptions;
#Value("${widget.headers.origins.allowed}")
private String allowedOrigins;
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.exceptionHandling().accessDeniedPage("/login")
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/myaccount", true).permitAll()
.and()
.authorizeRequests()
.antMatchers("/**").permitAll();
http.regexMatcher("^((?!(/widget|/assistedSearch)).)*$")
.headers().frameOptions().disable()
.regexMatcher("^((?!(/widget|/assistedSearch)).)*$")
.headers()
.xssProtection()
.contentTypeOptions()
.addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "SAMEORIGIN"));
http.antMatcher("/widget")
.headers()
.frameOptions()
.disable()
.antMatcher("/widget")
.headers()
.addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "ALLOW-FROM " + allowedXFrameOptions));
http.requestMatchers().antMatchers("/assistedSearch", "/widget")
.and()
.headers()
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", allowedOrigins))
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Methods", "GET, POST"))
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers", "Content-Type"));
// #formatter:on
}
}
The rules should be...
For all urls but not /widget and /assistedSearch we should add the SAMEORIGIN X-Frame-Options header
For the /widget endpoint we should add the X-Frame-Options: ALLOW-FROM header
For the /widget and /assistedSearch endpoints we should add the Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers headers
As I mentioned above if I comment out the For all urls ruleset then the other two work in unison, but with the For all urls rule uncommented none of the headers appear.
Does anyone have any ideas why this might be? How do you add multiple rulesets in Spring Security and override existing rulesets with new ones?
I tried
http.antMatcher("/widget")
.headers()
.frameOptions()
.disable()
Which again appears to work on it's own but not in combination.
Thanks in advance!
You override your previous matchers, see HttpSecurity.html#antMatcher:
Invoking antMatcher(String) will override previous invocations of mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).
and HttpSecurity.html#regexMatcher:
Invoking regexMatcher(String) will override previous invocations of mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).
If you want more than one configuration of HttpSecurity, see Spring Security Reference:
We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.
#EnableWebSecurity
public class MultiHttpSecurityConfig {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) { 1
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
#Configuration
#Order(1) 2
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**") 3
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
#Configuration 4
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}