Springboot/Security

Spring 3.x이상 UserDetailsService 여러개 사용하기

디비드킴 2024. 5. 7. 20:38

출처

이분 때문에 살았다

https://velog.io/@thisisnine99/%EC%8A%A4%ED%94%84%EB%A7%81%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0-%EB%91%90%EA%B0%9C%EC%9D%98-%EC%97%94%ED%8B%B0%ED%8B%B0%EB%A1%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8

 

스프링시큐리티 두개의 엔티티로 로그인

스프링시큐리티를 통한 폼로그인 여러개의 엔티티(데이터)로 로그인하는 방법 > ### 스프링 시큐리티를 통한 폼로그인 스프링시큐리티의 설정 클래스인 SecurityConfig 클래스를 위처럼 설정해두면

velog.io

너무 깔금하고 이해하기 쉽게 글을써놓셨다

package com.example.demo2.Config;

import com.example.demo2.Admin.Repo.AdminRepo;
import com.example.demo2.Admin.Service.AdminPrincipalDetailsService;
import com.example.demo2.User.Repo.UserRepo;
import com.example.demo2.User.Service.UserPrincipalDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.security.web.util.matcher.AntPathRequestMatcher;

@Configuration//빈등록: 스프링 컨테이너에서 객체에서 관리
@EnableWebSecurity/////필터를 추가해준다
@RequiredArgsConstructor
public class SecurityConfig {

    private final AdminRepo adminRepo;
    private final UserRepo userRepo;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Order(1)
    public SecurityFilterChain adminConfigure(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
                .securityMatcher(new AntPathRequestMatcher("/admin/**"))
                .authenticationProvider(adminDaoAuthenticationProvider())
                .authorizeHttpRequests(auth->
                        auth.requestMatchers("/admin/**").hasRole("ADMIN")
                )
                .formLogin(login ->
                        login
                                .loginPage("/admin/login")
                                .loginProcessingUrl("/admin/login/pro")
                                .permitAll()
                                .passwordParameter("pwd")
                                .defaultSuccessUrl("/admin/index", true)
                                .failureUrl("/admin/login?error=true")
                )
                .logout(logout ->
                        logout
                                .logoutUrl("/admin/logout")
                                .permitAll()
                );
        return http.build();

    }

    @Bean
    @Order(2)
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
                .authenticationProvider(userDaoAuthenticationProvider())
                .authorizeHttpRequests(auth->
                        auth. requestMatchers("/auth/**").authenticated() // /auth/** URL에 대해 인증이 필요하도록 설정
                                .anyRequest().permitAll())
                .formLogin(login ->
                        login
                                .loginProcessingUrl("/login/pro")
                                .permitAll()
                                .passwordParameter("pwd")
                                .defaultSuccessUrl("/index", true)
                                .failureUrl("/login?error=true")
                )
                .logout(logout ->
                        logout
                                .logoutUrl("/logout")
                                .permitAll()
                );
        return http.build();

    }
    @Bean
    DaoAuthenticationProvider adminDaoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(new AdminPrincipalDetailsService(adminRepo));
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }
    @Bean
    DaoAuthenticationProvider userDaoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(new UserPrincipalDetailsService(userRepo));
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }
}