Using Spring Security for basic authorization

The Moviee web service uses Spring Security to authenticate users and authorize them to list, get, and rate movies. The Maven Spring Security starter needs to be specified as follows to enable Spring Security in the web service:

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

The Moviee web service uses basic authentication, an authentication mechanism that uses a header named Authorization with the "Basic "+base64encode(username:password) value. The following is the Spring Security configuration:

@Configuration
@EnableWebFluxSecurity
class SecurityConfig {

@Bean
fun securityWebFilterChain(http : ServerHttpSecurity) : SecurityWebFilterChain {
http.authorizeExchange()
.pathMatchers("/movies/**")
.authenticated()
.and()
.httpBasic()
.and()
.csrf()
.disable();

return http.build();
}

The preceding configuration uses @EnableWebFluxSecurity to configure the web filters necessary for Spring Security Reactive and override any auto-configurations. The securityWebFilterChain function uses its ServerHttpSecurity argument to protect all the endpoint sets under /movies/** and ensure they're accessible only after authentication. This in turns means the user needs to be authenticated; anonymous users will not be allowed to access anything:

    @Bean
fun authenticationManager(movieeReactiveUserDetailsService:
MovieeReactiveUserDetailsService):
UserDetailsRepositoryReactiveAuthenticationManager {
val userDetailsRepositoryReactiveAuthenticationManager =
UserDetailsRepositoryReactiveAuthenticationManager
(movieeReactiveUserDetailsService)
userDetailsRepositoryReactiveAuthenticationManager.
setPasswordEncoder(passwordEncoder())

return userDetailsRepositoryReactiveAuthenticationManager
}

@Bean
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}

The authenticationManager function is used to configure an instance of ReactiveAuthenticationManager with MovieeReactiveUserDetailsService, implemented earlier, along with BCryptPasswordEncoder:

    @Bean
@Profile("default")
fun applicationRunner(userService : UserService): ApplicationRunner
{
return ApplicationRunner {

userService.save(com.packtpub.springboot2movierating.model.User
(1, "user", passwordEncoder().encode("password"), "USER", "User of
Moviee"
)).subscribe();

userService.save(com.packtpub.springboot2movierating.model.User(2,
"admin", passwordEncoder().encode("password"), "ADMIN", "Admin of
Moviee"
)).subscribe()
}
}

}

Finally, ApplicationRunner is used to insert some users into the database at startup.

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

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