Updating SecurityConfiguration

Now, let's update SecurityConfiguration to make Spring Security aware of the new filter and handlers:

...
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(PUBLIC).permitAll()
.anyRequest().authenticated()
.and()
.addFilterAt(authenticationFilter(),
UsernamePasswordAuthenticationFilter.class)
.formLogin().loginPage("/login")
.and()
.logout().logoutUrl("/logout")
.logoutSuccessHandler(logoutSuccessHandler())
.and()
.csrf().disable();
}
...
@Bean
public AuthenticationFilter authenticationFilter() throws Exception {
AuthenticationFilter authenticationFilter = new
AuthenticationFilter();
authenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
authenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
authenticationFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationFilter;
}

@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new SimpleAuthenticationSuccessHandler();
}

@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return new SimpleAuthenticationFailureHandler();
}

@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
return new SimpleLogoutSuccessHandler();
}
}

As you can see, we use the http.addFilterAt() method to replace UsernamePasswordAuthenticationFilter with AuthenticationFilter, which is initialized in the authenticationFilter() method. We also change LogoutSuccessHandler to our implementation, SimpleLogoutSuccessHanlder. You can find the details of this handler along with the other two handlers in the commit record. Inside authenticationFilter(), we create a new AuthenticationFilter and provide the handlers, as well as AuthenticationManager, which is gained through the authenticationManagerBean() method that WebSecurityConfigurerAdapter provides.

That's it. We've implemented authentication using Spring Security with some customization. As usual, let's make sure there is a successful build before committing the code. The following is the commit record:

Figure 10.16: Implementing login page backend commit
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.216