Newer
Older
SampleSpringSecurity3 / src / main / java / com / sample / WebSecurityConfig.java
yhornisse on 30 May 2023 1 KB init
package com.sample;

import com.sample.service.SampleUserDetailsService;
import lombok.RequiredArgsConstructor;
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.web.SecurityFilterChain;


@RequiredArgsConstructor
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

  private final SampleUserDetailsService sampleUserDetailsService;

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/login", "/login.html", "/sample/**").permitAll()
            .anyRequest().authenticated())
        .formLogin(login ->
            login.loginPage("/login.html").permitAll()
                .loginProcessingUrl("/login").permitAll()
                .usernameParameter("id")
                .passwordParameter("password")
                .defaultSuccessUrl("/hello.html")
                .failureUrl("/login.html?failed"))
        .logout(logout -> logout
            .logoutUrl("/logout")
            .deleteCookies("JSESSIONID")
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login.html?logout"))
        .csrf(csrf -> csrf.ignoringRequestMatchers("/login", "/logout"))
        .userDetailsService(sampleUserDetailsService);
    return http.build();
  }
}