Using Spring Security for authentication and authorization

This web application has used Spring Security to authenticate users and to authorize them to submit comments. The Maven Spring Security starter needs to be specified as follows to enable Spring Security in the web application:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>

The following is the Spring Security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserService userDetailService;

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/h2-console/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.and()
.logout()
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/**")
.hasRole("USER");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}

@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(passwordEncoder());
authenticationProvider.setUserDetailsService(userDetailService);
return authenticationProvider;
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public ApplicationRunner applicationRunner() {
return args -> {
userDetailService.create(new User(null, "shazin", passwordEncoder().encode("password"),
"ROLE_USER"));
userDetailService.create(new User(null, "shahim", passwordEncoder().encode("password"),
"ROLE_USER"));
};
}
}

The preceding configuration has @EnableWebSecurity to configure the filters necessary for Spring Security and override any auto-configuration. The configure(WebSecurity web) method ignores Spring Security for the URL /h2-console/ and all of its sub-URLs. The configure(HttpSecurity http) method configures formLogin, log out, and access to all URLs (/**) that have the user role (ROLE_USER) authorization. This, in turn, means the user needs to be authenticated and anonymous users will not be allowed to access anything. 

The configure(AuthenticationManagerBuilder auth) method is used to configure AuthenticationProvider with our implementation for UserDetailsService (UserService) and PasswordEncoder, in our case BCryptPasswordEncoder. Finally, ApplicationRunner is used to insert some users into the database at startup.

The following code helps to load the currently logged-in user:

@Component
public class AuditAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (authentication == null || !authentication.isAuthenticated()) {
return Optional.empty();
}

return Optional.of(((User) authentication.getPrincipal()).getUsername());
}
}

Furthermore, to support the @CreatedUser annotation used in JPA Auditing, there is AuditAware implementation that makes use of SecurityContextHolder, which is responsible for holding the Authentication object for a logged in user. The principal from the Authentication object is retrieved to get the username of the logged in user, which will be persisted with a Comment object.

..................Content has been hidden....................

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