- Spring 5.0 Cookbook
- Sherwin John Calleja Tragura
- 248字
- 2021-07-08 10:16:29
How to do it...
After the initial setup and configuration, it is time to experiment with the Spring Security 4.2.2 module:
- Let us now disable the previous AppSecurityConfig model by applying comment symbols to its @Configuration and @EnableWebSecurity annotations:
//@Configuration //@EnableWebSecurity public class AppSecurityConfig extends WebSecurityConfigurerAdapter { // refer to sources }
The use of the @Order annotation can be another option instead of manually commenting the annotations in AppSecurityConfig. This also generates a precedence rule whenever we have a series of security models, although there are slight inconsistencies when @Order is used after their roll-out.
- Create another security model named AppSecurityModelA with the same in-memory user details and WebSecurity URL exemptions, but with some highlights on the HttpSecurity configuration for HTTPS security rules:
@Configuration @EnableWebSecurity public class AppSecurityModelA extends WebSecurityConfigurerAdapter{ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // refer to sources } @Override protected void configure(HttpSecurity http) throws Exception { http .requiresChannel() .anyRequest().requiresSecure() .and().authorizeRequests() .antMatchers("/login**", "/after**").permitAll() .anyRequest().authenticated() .and().formLogin() .loginPage("/login.html") .defaultSuccessUrl("/deptform.html", false) .failureUrl("/login.html?error=true") .and() .logout().logoutUrl("/logout.html") .logoutSuccessUrl("/after_logout.html"); http .portMapper() .http(8080).mapsTo(8443); http.csrf().disable(); } @Override public void configure(WebSecurity web) throws Exception { // refer to sources } }
- Update SpringContextConfig by importing AppSecurityModelA, replacing the previous security context definition:
@Import(value = { AppSecurityModelA.class }) @Configuration @EnableWebMvc @ComponentScan(basePackages = "org.packt.secured.mvc") public class SpringContextConfig { }
- Save all files. Then clean, install, and deploy the project.
Shut down Tomcat 9 and remove the previously deployed ch04 project and its WAR file for this recipe to work. Clear also all the browser sessions.