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();
}
}
Related
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();
}
}
I'm trying to implement CSRF token security in my Spring Boot API to learn how to deal with that.
I've followed this tutorial (server side part) and this is my security config:
private static final String[] CSRF_IGNORE = {"/api/login"};
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.ignoringAntMatchers(CSRF_IGNORE)
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(new CustomCsrfFilter(), CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint() {
})
.and()
.authenticationProvider(getProvider())
.formLogin()
.loginProcessingUrl("/api/login")
.successHandler(new AuthentificationLoginSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
.invalidateHttpSession(true)
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
Others things are the same as in the tutorial.
I'm testing with Postman.
When i add the endpoint i want in CSRF_IGNORE, i can see with logger/debug that token stocked, and token from cookie are the same, because the security config's part CustomCsrfFilter.java in .addFilterAfter() is used, but when i remove the endpoint from this CSRF_IGNORE, what i get is a 403, and, logger/debug in the CustomCsrfFilter.java isn't used, so i'm thinking that tokens aren't compared.
I think I missed something and I would like to understand.
If you want to use CSRF with a http only false cookie, why not use Spring Security's built in CookieCsrfTokenRepository? Should simplify your config that way. CustomCsrfFilter seems to be adding a XSRF-TOKEN cookie to the HttpServletResponse, which CookieCsrfTokenRepository does for you.
The default CSRF cookie name when using CookieCsrfTokenRepository is X-CSRF-TOKEN, which is conveniently the default name Angular's HttpClientXsrfModule uses. Of course you can customize that if you need.
So your security config becomes:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint())
.and()
.authenticationProvider(getProvider())
.formLogin()
.loginProcessingUrl("/api/login")
.successHandler(new AuthentificationLoginSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
.invalidateHttpSession(true)
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
And with Angular, your app module has HttpClientXsrfModule as
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
HttpClientXsrfModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
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);
}
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();
}
}
}
When i enable the spring-boot-starter-security dependency. CORS support doesn't work.
This is my SecurityConfiguration Class:
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected AuthenticationManager authenticationManager() throws Exception {
return authentication -> {
// ...
};
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf()
// Disabling CSRF
.disable()
// Disabling Session Management
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
// Adding custom REST Authentication filter
.addFilterBefore(new RestAuthenticationFilter(authenticationManager()), LogoutFilter.class)
// Authorizing requests
.authorizeRequests()
.antMatchers("/", "/frontend/login")
.permitAll()
.antMatchers("/api/**", "/frontend/**")
.authenticated()
.antMatchers("/**")
.permitAll();
}
}
My Controller Class has a CrossOrigin Annotation:
#CrossOrigin
#RequestMapping("/frontend")
#RestController
public class FrontEndController extends BaseController {
I can handle CORS with custom CORS Filter but I want to use just one Annoation.
I found 2 methods for adding CORS support to spring-security enabled spring-boot project. We can add spring-web CorsFilter to security filter chain. The following example belongs to token based authentication project. So we used a custom RestAuthenticationFilter.
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final HttpSecurity http) throws Exception {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
source.registerCorsConfiguration("/**", config);
http.csrf()
// Disabling CSRF
.disable()
// Disabling Session Management
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
// Adding spring-web CORS filter
.addFilterBefore(new CorsFilter(source), LogoutFilter.class)
// Adding custom REST Authentication filter
.addFilterBefore(new RestAuthenticationFilter(authenticationManager()), LogoutFilter.class)
// Authorizing requests
.authorizeRequests()
.antMatchers("/", "/frontend/login")
.permitAll()
.antMatchers("/api/**", "/frontend/**")
.authenticated()
.antMatchers("/**")
.permitAll();
}
}
But in the above example our CrossOrigin annotations in the controllers are redundant. So we should give the ability to control CORS requests to spring-web layer. Therefore we can allow CORS pre-flight (OPTIONS HTTP Methods).
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf()
// Disabling CSRF
.disable()
// Disabling Session Management
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
// Adding custom REST Authentication filter
.addFilterBefore(new RestAuthenticationFilter(authenticationManager()), LogoutFilter.class)
// Authorizing requests
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.antMatchers("/", "/frontend/login")
.permitAll()
.antMatchers("/api/**", "/frontend/**")
.authenticated()
.antMatchers("/**")
.permitAll();
}
}
With the help of above configuration we can use both #CrossOrigin annotations and spring-security configuration.