아카이브

[스프링 기반 REST API 개발] 시큐리티 폼 인증 설정하기 본문

Spring/스프링 기반 REST API 개발

[스프링 기반 REST API 개발] 시큐리티 폼 인증 설정하기

주멘이 2021. 1. 9. 14:05

configure(HttpSecurity Http) 커스터마이징

  • 익명 사용자 사용 활성화
  • 폼 인증 방식 활성화
    • 기본 로그인 페이지 제공
  • 요청에 인증 적용
    • /api 이하 모든 GET 요청에 인증이 필요함
    • (permitAll()을 사용하여 인증이 필요 없이 익명으로 접근이 가능케 할 수 있음)
    • 그밖에 모은 요청도 인증이 필요함
    /* filterchain 안에서 거르기*/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .anonymous()	// 익명사용자 허용
                .and()
                .formLogin()	// 폼 인증
                .and()
                .authorizeRequests()	// 인증요청에 대해서
                	.mvcMatchers(HttpMethod.GET, "/api/**").authenticated()	// /api/* 경로 익명 허용
                	.anyRequest().authenticated();	// 나머지는 인증이 필요하다
    }

 

PasswordEncoder를 통한 인코딩 패스워드 저장하기 (AccountService.class)

    public Account saveAccount(Account account) {
        account.setPassword(this.passwordEncoder.encode(account.getPassword()));
        return this.accountRepository.save(account);
    }

 

findByUsername() Test 코드 수정하기

    @Test
    void findByUsername() {
        //Given
        String username = "jumen@naver.com";
        String password = "5215";
        Account account = Account.builder()
                .email(username)
                .password(password)
                .roles(Set.of(AccountRole.ADMIN, AccountRole.USER))
                .build();

        this.accountService.saveAccount(account);   // using passwordEncoder

        // When
        UserDetailsService userDetailsService = accountService;
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        // Then
        assertThat(this.passwordEncoder.matches(password, userDetails.getPassword())).isTrue();


    }

 

테스트용 계정을 만드는 ApplicationRunner 추가하기 (AppConfig.class)

    @Bean
    public ApplicationRunner applicationRunner() {
        return new ApplicationRunner() {
            @Autowired
            AccountService accountService;

            @Override
            public void run(ApplicationArguments args) throws Exception {
                Account account = Account.builder()
                        .email("knoc5215@naver.com")
                        .password("5215")
                        .roles(Set.of(AccountRole.ADMIN, AccountRole.USER))
                        .build();

                accountService.saveAccount(account);

            }
        };
    }