관리 메뉴

코딩하는 락커

[Spring Boot를 이용한 RESTful Web Services 개발] 33~34강 본문

🍃 Spring/🌱 Spring Boot를 이용한 RESTful Web Service

[Spring Boot를 이용한 RESTful Web Services 개발] 33~34강

락꿈사 2022. 3. 5. 13:25

Spring Security를 이용한 인증 처리

  • 지금까지 작성한 사용자 관리 등의 REST API는 웹 브라우저나 Postman과 같은 클라이언트 테스트 프로그램을 이용하면 바로 결과를 확인할 수 있었음
  • 일반적으로 공개되어도 좋은 정보가 아니라 중요한 테스트 혹은 일부 인증을 거친 사용자만 사용해야 하는 리소스의 경우 보안에 문제가 생길 수 있음
  • REST API 어플리케이션의 인증을 처리하기 위한 다양한 방법이 있음 (JWT, ID/Password, Spring Security 등)
  • Spring Security란 스프링 프레임워크에서도 어렵고 복잡한 구조로 되어 있지만, ID와 Password만을 사용하기 위해 간단한 구조로 만들 수 있음
  • Pom.xml 파일에 의존성 추가 (버전 정보 꼭 작성해줘야 함)
  • 로그 파일을 확인하여 자동 생성된 현재 프로젝트에서 사용할 수 있는 PW 확인
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.6.3</version>
</dependency>

자동 생성된 비밀번호를 확인할 수 있음
Postman에 URI를 입력하고 Authorization 탭 클릭 -&gt; Type: Base Auth -&gt; Username : user -&gt; Password: 자동생성 비밀번호 붙여넣기를 했을 때 정상적으로 유저 정보가 나오는 것을 확인할 수 있음

 

Configuration 클래스를 이용한 사용자 인증 처리

  • 개발자가 직접 지정한 ID, Password를 이용한 인증 처리 구현
  • application.yml 파일에 내용 추가
security:
  user:
    name: username
    password: passw0rd

Postman에 URI를 입력하고 Authorization 탭 클릭 -&gt; Type: Base Auth -&gt; Username : 지정한 아이디 -&gt; Password: 지정한 비밀번호 붙여넣기 했을 때 정상적으로 유저 정보가 나오는 것을 확인할 수 있음

 

  • 고정된 아이디와 패스워드를 사용하는 방식은 정보가 변경될 때마다 수정해줘야하는 번거로움이 있음
  • 데이터 베이스에서 사용자 정보를 가져오는 방식 구현
  • config 패키지에 SecurityConfig.java 클래스 생성
package com.example.restfulwebservice.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.net.Authenticator;

@Configuration
// WebSecurityConfiguration는 security 관련 config를 설정할 수 있게 해줌
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // memory 방식의 Authentication 추가
        // auth.jdbcAuthentication()도 가능
        auth.inMemoryAuthentication()
                .withUser("roxy")
                .password("{noop}test1234") // {noop}를 붙이면 패스워드 플레인 텍스트 값을 인코딩 없이 사용할 수 있게 해줌
                .roles("USER");
    }
}

지정한 아이디와 비밀번호를 설정하지 정상적으로 리소스를 가져오는 것을 확인할 수 있음
전체 사용자 조회도 정상적으로 작동하는 것을 확인할 수 있음

Comments