1.1.34.10.2. fejezet, Adatbázisban tárolt felhasználói adatok

Kapcsolódó hivatkozások

PostgreSQL felhasználói táblák

CREATE TABLE users(
	username VARCHAR(50) NOT NULL PRIMARY KEY,
	password VARCHAR(500) NOT NULL,
	enabled BOOLEAN NOT NULL
);
 
CREATE TABLE authorities (
	username VARCHAR(50) NOT NULL,
	authority VARCHAR(50) NOT NULL,
	CONSTRAINT fk_authorities_users FOREIGN KEY(username) REFERENCES users(username)
);
CREATE UNIQUE INDEX ix_auth_username ON authorities (username,authority);

RequestController

@RestController
class GreetingsController {
 
    @GetMapping("/hello")
    fun sayHello(): String {
        return "Hello"
    }
 
    @PreAuthorize("hasRole('USER') || hasRole('ADMIN')")
    @GetMapping("/user")
    fun userEndpoint(): String {
        return "Hello User"
    }
 
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    fun adminEndpoint(): String {
        return "Hello Admin"
    }
}

SecurityConfig

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
class SecurityConfig {
 
    @Autowired
    lateinit var dataSource: DataSource
 
    @Bean
    fun defaultSecurityFilterChain(http:HttpSecurity): SecurityFilterChain {
        http.authorizeHttpRequests{request-> request
            .requestMatchers("/swagger-ui/**").permitAll()
            .requestMatchers("/v3/api-docs/**").permitAll()
            .anyRequest().authenticated()}
        http.sessionManagement{session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)}
        http.httpBasic(Customizer.withDefaults())
        return http.build()
    }
 
    @Bean
    fun userDetailService():UserDetailsService {
        val user = User.withUsername("pzoli").password(passwordEncoder().encode("q")).roles("USER").build()
        val admin = User.withUsername("admin").password(passwordEncoder().encode("admin123")).roles("ADMIN").build()
        val userDetailsManager = JdbcUserDetailsManager(dataSource)
        try {
            userDetailsManager.createUser(user)
            userDetailsManager.createUser(admin)
        } catch (e:Exception) {
            println(e.localizedMessage)
        }        return userDetailsManager
    }
 
    @Bean
    fun passwordEncoder():PasswordEncoder {
        return BCryptPasswordEncoder()
    }
}