ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • SnsChats - 개발 일기
    project 2022. 5. 25. 21:09

    https://github.com/kenokim/SnsChats

    Spring boot + vue.js + aws 를 이용해서 채팅 어플리케이션을 만들자.

     

     

    [22.05.25]

    로그인 기능을 구현했다. Spring security 5 에서 지원하는 OAuth 2 resource server 의 기능으로 API 를 access token 을 가진 유저만 접근할 수 있도록 구현했다. 먼저 최소한의 설정으로 구현했고, JWT 알고리즘만 customize 했다.

     

    ( JWT 알고리즘은 직접 구현하지 않아서 잘 모르겠다. 다만 여러 글에서 본 건 다음과 같았다. )

    JWT 알고리즘으로 RS256 을 사용했고, 이는 비대칭키 encryption / decryption 방식이다. Authoriztion server 에서 Header 와 payload 를 SHA256 으로 hashing 하여 signature 를 생성하고, 이를 private key 로 encrypt 하여 token endpoint 로 준다. Client 는 access token 을 받아 Authorization 헤더에 Bearer aadjsalkc ... 으로 요청을 보내고 resource server 에서 access token 을 받아 public key 로 decrypt 하여 검증한다. Payload 에서 앞서 담은 principal / subject 를 꺼내어 인증 정보를 사용한다.

     

    코드는 매우 매우 간단하다. OAuth 2 의 workflow 를 지키면 기존 코드를 그대로 사용해도 되기 때문이다. 일부만 여기에 적어보겠다.

    @Test
    public void 인증된_유저_OK() {
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(createValidToken());
        HttpEntity req = new HttpEntity(headers);
        ResponseEntity res = template.exchange("/chats/1", HttpMethod.GET, req, ChatsDetailsDto.class);
        assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
    }

    먼저 이런 식으로 TC 를 작성해서 TDD 했다. (3개 더있음)

    @Bean
    public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt
                                .decoder(jwtDecoder())
                        )
                )
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    		    
                ...
                
                return http.build();
    }

    대략 이런 식으로 config 했다.

    @Bean
    JwtEncoder jwtEncoder() {
        JWK jwk = new RSAKey.Builder(this.pubKey).privateKey(this.privKey).build();
        JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new NimbusJwtEncoder(jwks);
    }
    @Bean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withPublicKey(this.pubKey).build();
    }

    이 부분만 customizing 하고 나머지는 기본 설정이다. Encoder 는 token endpoint 를 구현하기 위해 따로 구성한 것이고, decoder 는 resource server 에 필수로 구현해야 한다. RSA key pair 를 읽어서 encode decode 하며, key 는 docker secret 등으로 안전하게 보관한다. (할 예정이다 .. 지금은 아직 아무것도 없으니까)

     

     

    https://devstudy1413.tistory.com/83

     

    Spring security 5 OAuth2 공부한거

    Spring security 5 OAuth2 workflow 에 대해 다시 정리하고자 한다. (틀린 부분 더 있을거 같다. 점점 고치자.) Spring security 5 는 인증/인가에 대한 framework 로 OAuth2 기능 중 Client, Resource server 를..

    devstudy1413.tistory.com

    이 글에 적은 대로 default 옵션을 사용하지 않고 일일이 다 override 할 수 있다. 예를 들어, request header 에 넣지 않고 cookie 로 넣는다던지..

     

    OAuth 2 framework 를 지킬 경우 위처럼 코드 몇줄 안짜고 구현 가능하다.

    'project' 카테고리의 다른 글

    MGP 과제를 하며 느낀 점 - 테스트의 중요성  (0) 2022.06.11
    광고 프로젝트 - 개발 일기  (0) 2022.06.01
    Docker 시작  (0) 2022.05.22
    Spring security 5 OAuth2 공부한거  (0) 2022.05.06
    테스트 코드의 중요성, TDD  (0) 2022.04.30
Designed by Tistory.