Newer
Older
bremer / src / main / kotlin / config / BremerConfig.kt
yhornisse on 2 Jul 2023 2 KB add project
/*
 * Copyright (c) 2023. yo-saito. All Rights Reserved.
 */

package net.piedpiper.bremer.config

import net.piedpiper.bremer.service.app.LoginAppService
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.SecurityFilterChain
import org.springframework.web.filter.ForwardedHeaderFilter
import kotlin.reflect.KProperty

@Configuration
class AppConfig {
    @Bean("bremer.PasswordEncoder")
    fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()

    @Bean
    fun forwardedHeaderFilter(): ForwardedHeaderFilter = ForwardedHeaderFilter()
}

@Configuration
@EnableWebSecurity
class WebSecurityConfig(
    @Qualifier("bremer.service.LoginAppService")
    private val loginAppService: LoginAppService
) {
    @Bean
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        http.authorizeHttpRequests { authorize ->
            authorize
                .requestMatchers(
                    "/bremer/login",
                    "/bremer/login.html"
                ).permitAll()
                .anyRequest().authenticated()
        }.formLogin { login ->
            login.loginPage("/bremer/login.html").permitAll()
                .loginProcessingUrl("/bremer/login").permitAll()
                .usernameParameter("id")
                .passwordParameter("password")
                .defaultSuccessUrl("/bremer/hello.html")
                .failureUrl("/bremer/login.html?failed")
        }.logout { logout ->
            logout
                .logoutUrl("/bremer/logout")
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/bremer/login.html?logout")
        }
            .csrf { it.disable() }
            .userDetailsService(loginAppService)
        return http.build()
    }
}

class Log {
    companion object {
        private val log = LogManager.getLogger(Log::class.java)
    }

    operator fun getValue(thisRef: Any, property: KProperty<*>): Logger = log
}