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

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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

  @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"));
    return http.build();
  }

  @Bean
  public UserDetailsService userDetailsService() {
    return new InMemoryUserDetailsManager(
        User.withUsername("user")
            .password("{noop}password")
            .roles("USER")
            .build());
  }
}