Newer
Older
bremer / src / main / kotlin / config / BremerConfig.kt
yhornisse on 12 Aug 2023 2 KB fix login form
/*
 * Copyright (c) 2023. yo-saito. All Rights Reserved.
 */

package net.piedpiper.bremer.config

import net.piedpiper.bremer.service.LoginService
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.LoginService")
    private val loginService: LoginService
) {
    @Bean
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        http.authorizeHttpRequests { authorize ->
            authorize
                .requestMatchers(
                    "/bremer/login",
                    "/bremer/login.html",
                    "/bremer/icon/*"
                ).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(loginService)
        return http.build()
    }
}

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

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