* Scan package for controller Migrate deprecated Spring config * BAEL-4792: enable CSRF + sample REST API request * Adjust CSRF logs
58 lines
2.1 KiB
Java
58 lines
2.1 KiB
Java
package com.baeldung.spring;
|
|
|
|
import org.springframework.context.annotation.Configuration;
|
|
import org.springframework.context.annotation.Profile;
|
|
import org.springframework.http.HttpMethod;
|
|
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.web.csrf.CookieCsrfTokenRepository;
|
|
|
|
@Configuration
|
|
@EnableWebSecurity
|
|
@Profile("!https")
|
|
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
|
|
|
|
public SecSecurityConfig() {
|
|
super();
|
|
}
|
|
|
|
@Override
|
|
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
|
|
// @formatter:off
|
|
auth.inMemoryAuthentication()
|
|
.withUser("user1").password("{noop}user1Pass").roles("USER")
|
|
.and()
|
|
.withUser("user2").password("{noop}user2Pass").roles("USER")
|
|
.and()
|
|
.withUser("admin").password("{noop}admin0Pass").roles("ADMIN");
|
|
// @formatter:on
|
|
}
|
|
|
|
@Override
|
|
protected void configure(final HttpSecurity http) throws Exception {
|
|
// @formatter:off
|
|
http
|
|
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
|
|
.authorizeRequests()
|
|
.antMatchers("/admin/**").hasRole("ADMIN")
|
|
.antMatchers("/anonymous*").anonymous()
|
|
.antMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/rest").permitAll()
|
|
.anyRequest().authenticated()
|
|
.and()
|
|
.formLogin()
|
|
.loginPage("/index.html")
|
|
.loginProcessingUrl("/perform_login")
|
|
.defaultSuccessUrl("/homepage.html",true)
|
|
.failureUrl("/index.html?error=true")
|
|
.and()
|
|
.logout()
|
|
.logoutUrl("/perform_logout")
|
|
.deleteCookies("JSESSIONID");
|
|
// @formatter:on
|
|
}
|
|
|
|
|
|
}
|