[rest api 프로젝트 구축] - spring security (3) 스프링 시큐리티 기본 설정

geun kim·2023년 3월 27일
0

REST API 구축

목록 보기
13/20

스프링 시큐리티 기본 설정

시큐리티 필터를 적용하지 않음...

● /docs/index.html

로그인 없이 접근 가능

● GET /api/events
● GET /api/events/{id}

로그인 해야 접근 가능

● 나머지 다...
● POST /api/events
● PUT /api/events/{id}
● ...

application.properties 설정

#############################
# spring security 관련
#############################
logging.level.org.springframework.security=DEBUG

WebConfiguration

@Configuration
public class WebConfiguration {

    /**
     * Dto <-> domain간 값 복사 용도로 modelmapper 빈으로 등록 
     */
    @Bean
    public ModelMapper modelMapper(){
        return new ModelMapper();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

SecurityConfig

/**********************************
 * spring boot가 제공 해주는 spring security 설정은 유효하지 않는다.
 * spring security costomizing class
 **********************************/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AccountService accountService;
    @Autowired
    PasswordEncoder passwordEncoder;

    /****************
     *
     * Token 저장소 ( 여기선 oAuth 토큰을 저장)
     */
    @Bean
    public TokenStore tokenStore(){
        return new InMemoryTokenStore();
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    /**
     * AuthenticationManager 설정
     * userDetailsService > accountService로 대체
     * PasswordEncoder > passwordEncoder로 대체
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(accountService)
                .passwordEncoder(passwordEncoder);
    }

    /**
     * 1.Security Filter를 적용할지 않할지 설정 하는 부분
     * 적용 예외 처리
     * 정적 리소스 security filter 적용하지 않음
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers("/docs/index.html");
        //정적 리소스 security filter 적용하지 않음
        web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }


    /**
     * 2.Security Filter 사용 시
     * 적용 예외 처리
     * 정적 리소스 security filter 적용하지 않음
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/docs/index.html").anonymous()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }


}

AccountService 구현 ( UserDetailsService 상속 받아서 반드시 구현 해야 함 , 아래 메소드 반드시 구현 해야 함)


@Service
public class AccountService implements UserDetailsService {

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    //비밀번호를 PasswordEncoder로 인코딩 해 주어야 함
    public Account saveAccount(Account account){
        account.setPassword(passwordEncoder.encode(account.getPassword()));
        return accountRepository.save(account);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         Account account = accountRepository.findByEmail(username).orElseThrow( () -> new UsernameNotFoundException(username));
        return new User(account.getEmail(),account.getPassword(),authorities(account.getRoles()));
    }

    private Collection<? extends GrantedAuthority> authorities(Set<AccountRole> roles) {
        return roles.stream().map(r -> {
            return new SimpleGrantedAuthority("ROLE_" + r.name());
        }).collect(Collectors.toSet());
    }
}
profile
Devops Load Map

0개의 댓글