Spring Security란?

이원석·2023년 10월 28일
0

정보 보안

목록 보기
4/8
post-thumbnail
본 내용은 인프런의 이도원님의 SpringCloud 강의를 참고하여 작성되었습니다.



SSAFY에서 팀 프로젝트를 진행하며 사용자 인증 및 인가 기능을 Filter단에서 적용시키기 위해 Spring Security를 사용했었다. 마감 기한이 촉박했던 터라 완벽하게 이해하고 사용하지 못하기도 했고.. 기억도 희미해져가기 때문에 복기하고자 하는 취지로 간단하게 SpringSecurity를 활용하는 포스팅을 작성해본다.

이번 포스팅에서는 Spring Secuirty의 AuthenticationFilter와 Configure 클래스를 통해 클라이언트의 Request에 대해 인증/인가 작업에 대해 알아보자.

0. Spring Secuirty란?

Spring Security는 Spring 기반의 애플리케이션의 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크이다. Spring Security는 '인증'과 '인가'에 대한 부분을 Filter 흐름에 따라 처리하고 있다.

Spring Security의 아키텍쳐는 아래와 같다.


0-1. 인증(Authorizatoin)과 인가(Authentication)

인증(Authentication): 해당 사용자가 본인이 맞는지를 확인하는 절차
인가(Authorization): 인증된 사용자가 요청한 자원에 접근 가능한지를 결정하는 절차

Spring Security는 기본적으로 인증 절차를 거친 후에 인가 절차를 진행하게 되며, 인가 과정에서 해당 리소스에 대한 접근 권한이 있는지 확인을 하게 된다. Spring Security에서는 이러한 인증과 인가를 위해 Principal을 아이디로, Credential을 비밀번호로 사용하는 Credential 기반의 인증 방식을 사용한다.

Principal(접근 주체): 보호받는 Resource에 접근하는 대상
Credential(비밀번호): Resource에 접근하는 대상의 비밀번호



1. 왜 사용할까?

Filter는 Dispatcher Servlet으로 가기 전에 적용되므로 가장 먼저 URL 요청을 받지만, Interceptor는 Dispatcher와 Controller사이에 위치한다는 점에서 적용 시기의 차이가 있다.

[UserServiceImpl.java]

    @Override
    public ApiResponseDto singIn(UserSignInRequestDto userDto) {
        User user = userRepository.findByUserid(userDto.getUserId());

        if (user == null || !pwdEncoder.matches(userDto.getPassword(), user.getEncryptedPwd())) {
            throw new NotValidSingInRequestException(
                    HttpStatus.BAD_REQUEST,
                    "입력하신 ID나 비밀번호를 다시 확인해주세요");
        }


        return ResponseUtils.ok(userDto);
    }

  1. 편의성
    Spring Security는 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에 개발자 입장에서는 일일이 보안관련 로직을 작성하지 않아도 된다는 장점이 있다.

  2. 보안 취약점 개선
    내가 SpringSecuirty에 대해 잘 모를때 사용자의 로그인을 검증하기 위해 작성했던 로직인데, 요청이 Dispatcher Servlet에 도착하여 이미 Controller를 통과했다. 보안 문제를 서비스 단에서 처리하는 것은 보안 취약점이 이미 발생한 후에 대응하는 것이다.

  3. 레이어 계층 구조
    보안을 다중 레이어 계층 구조로 적용하는 것이 바람직하다. Filter 단에서의 보안 체크는 서비스 단에서의 보안 체크와 함께 사용자 요청을 여러 층에서 거치며 확인하는 방어적인 방법을 제공한다. 이러한 다중 층 구조를 통해 보안의 균형을 유지하고 여러 단계에서 보안 검사를 수행할 수 있다.

  4. 유지 보수
    Filter 단에서 보안을 확인하면 보안 문제를 미리 차단할 수 있으므로, 보안 취약점을 이용한 공격이나 데이터 누설과 같은 문제를 예방할 수 있으며, yml과 같은 환경 설정 파일에서 모든 요청이나 특정 요청에 대해 일관성 있는 보안 규칙을 적용함으로써 유지보수성을 향상시킬 수 있다.



SpringSecurity는 다양한 Servlet Filter, 이들로 구성된 필터체인, 필터체인들로 구성된 위임 모델을 사용하고 때문에 훨씬 체계화 된 보안 방식을 간편하게 사용할 수 있다.



2. Spring Security의 활용

위의 흐름에 따라 Spring Security를 적용시켜보자!

[전체적인 흐름도]
1. Request
클라이언트에서 login을 하고싶어 서버에 요청을 보냈다.

2. AuthenticationFilter
AuthenticationFilter는 클라이언트의 요청이 Dispatcher Servlet에 매핑되기 전에 요청을 낚아챈다.

3. AuthenticationFilter ⟹ attemptAuthentication()
요청 시에 전달받은 사용자 ID, PW를 통해 attemptAuthentication 메서드 내에서 UsernamePasswordAuthenticationToken(자격 증명을 위한 토큰) 을 생성한다.

4. 해당 Token을 AuthenticationManager에 넘겨 인증을 위임한다. ⟹ Authenticate 객체 생성

5. authenticationFilter(사용자 인증 필터) 에 authenticationManager를 주입한다.

6. WebSecurity configure에서 사용자 인증 필터를 추가한다. ⟹ getAuthenticationFilter()

7. successfulAuthentication 메서드에서 loadUserByUsername 를 호출하여 사용자의 유/무 여부를 확인하고 JWT Token을 발급하여 response Header에 담아 클라이언트에게 응답한다.

해당 흐름도에 따라 WebSecurity Config와 AuthenticationFilter를 구현해보자!



2-1. Request

{
  "userId" : "test"
  "password" : "test1234"
}

사용자가 로그인을 하기 위해 해당 JSON 형식의 데이터를 보냈다.


2-2. WebSecurity Configure

[WebSecurity.java]

      // 사용자 신원 인증을 위한 구성 메서드
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
      }


      // 요청에 대한 사용자 권한을 위한 구성 메서드
      @Override
      public void configure(HttpSecurity http) throws Exception {

          http.csrf().disable();

          // 1. 모든 요청과, 특정 IP 주소에서 들어오는 요청만 허용
          http.authorizeRequests()
                  .antMatchers("/**") // 모든 요청에 대해서
                  .hasIpAddress("IP ADDRESS")   // 특정 IP 주소에서 들어오는 요청만 허용 (IP 주소를 지정해야 합니다)
                  .and()
                  .addFilter(getAuthenticationFilter()); // 사용자 인증 필터 추가



          http.headers().frameOptions().disable();
      }

SpringSecurity의 Filter를 통과하기 전 사용자의 인증/인가를 부여하는 작업을 거쳐야 한다.

  1. 사용자의 신원 파악 - configure(AuthenticationManagerBuilder auth)
    auth.userDetailsService(userService)를 설정하게 되면 userServiceDetails 를 구현한 userService의 loadByUserName(String userId) 메서드를 통해 사용자의 정보를 가져온다.
    해당 메서드의 파라미터 이름이 사용자의 요청에서 아이디를 찾는 Key값이 된다. (위의 요청값에서는 사용자 아이디의 Key값이 userId)

    auth.userDetailsService(userService) ⟹ loadByUserName(String userId)

    가져온 사용자의 정보(UserDetails) 를 통해 AuthenticationManagerBuilder가 AuthenticationManager를 구성한며, 나중에 Filter에서 UsernamePasswordAuthenticationToken을 검증하는 용도로 사용된다.

  1. 사용자의 권한 부여 - configure(HttpSecurity http)
    HTTP 요청에 대한 보안 규칙을 설정하며, 특정 엔드포인트에 대한 인증 및 권한을 구성한다.

    // 1. 모든 요청과, 특정 IP 주소에서 들어오는 요청만 허용
    http.authorizeRequests()
            .antMatchers("/**") // 모든 요청에 대해서
            .hasIpAddress("IP ADDRESS")   // 특정 IP 주소에서 들어오는 요청만 허용 (IP 주소를 지정해야 합니다)
            .and()
            .addFilter(getAuthenticationFilter()); // 사용자 인증 필터 추가

configure(HttpSecurity http) 메서드에서 접근 권한과 보안 설정을 구성하고, 실제 요청은 이 설정에 따라 필터 체인(AuthenticationFilter) 을 통과할 차례이다!



2-3. AuthenticationFilter

먼저 Filter를 커스터마이징 하기 전!
상속할 UsernamePasswordAuthenticationFilter에 대해 알아보자.

UsernamePasswordAuthenticationFilter 의 attemptAuthentication

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (this.postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		String username = obtainUsername(request);
		username = (username != null) ? username.trim() : "";
		String password = obtainPassword(request);
		password = (password != null) ? password : "";
		UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
				password);
		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);
		return this.getAuthenticationManager().authenticate(authRequest);
	}

UsernamePasswordAuthenticationFilter는 Form based Authentication 방식으로 인증을 진행할 때 아이디, 패스워드 데이터를 파싱하여 인증 요청을 위임하는 필터이다.
request 요청에서 username, password를 가져와 Token을 생성하는 attemptAuthentication 메서드를 오버라이드 한다.



[AuthenticationFilter.java]

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

	private UserService userService;

    public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService) 
    {...}

    public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService, String endPoint) 
    {...}

	@Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        try {
            // 1. 요청 본문에서 JSON 데이터를 읽어 UserSignInRequestDto로 매핑
            UserSignInRequestDto creds = new ObjectMapper().readValue(
                    request.getInputStream(),
                    UserSignInRequestDto.class);

            // 2. 매핑된 자격 증명을 사용하여 사용자를 인증하도록 인증 매니저에 요청
            //    - UserSignInRequestDto 객체에서 사용자 ID와 비밀번호를 추출하여 UsernamePasswordAuthenticationToken 생성
            //    - new ArrayList<>()는 사용자의 권한(권한이 없는 경우 빈 리스트)을 나타냅니다.
            //    - 사용자가 제공한 자격 증명을 추출하고 AuthenticationManager 에 제출

            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                    creds.getUserId(),
                    creds.getPassword(),
                    new ArrayList<>()
            );

            Authentication authenticate = getAuthenticationManager().authenticate(token);

            return authenticate;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException
	{...}

클라이언트의 request JSON 데이터의 아이디와 비밀번호, 빈 권한(List) 인자로 두어 Token을 생성했다.

AuthenticationManager에게 Token을 전달하여 실제 인증을 시도하고 문제가 없다면 인증 객체(Authentication)를 반환한다. 이 객체는 나중에 Spring Security에서 사용자 관련 작업을 수행하는 데 사용되며 AuthenticationManager에서 관리된다.



2-4. Customized AuthenticationFilter 추가

[WebSecurity.java]

  // 요청에 대한 사용자 권한을 위한 구성 메서드
  @Override
  public void configure(HttpSecurity http) throws Exception {

      http.csrf().disable();

      // 1. 모든 요청과, 특정 IP 주소에서 들어오는 요청만 허용
      http.authorizeRequests()
              .antMatchers("/**") // 모든 요청에 대해서
              .hasIpAddress("127.0.0.1")   // 특정 IP 주소에서 들어오는 요청만 허용 (IP 주소를 지정해야 합니다)
              .and()
              .addFilter(getAuthenticationFilter()); // 사용자 인증 필터 추가



      http.headers().frameOptions().disable();
  }

  // 사용자 인증 필터를 반환하는 메서드
  private AuthenticationFilter getAuthenticationFilter() throws Exception {
      // 1. 사용자 인증 필터 생성 및 설정
      AuthenticationFilter authenticationFilter =
              new AuthenticationFilter(authenticationManager(), userService, "/signin");

      // authenticationFilter.setAuthenticationManager(authenticationManager());

      return authenticationFilter;
  }

사용자 인증 필터를 반환하기 위한 getAuthenticationFilter() 메서드를 체이닝 형식의 addFilter()에 추가해주자.

getAuthenticationFilter() 메서드를 실행시키면 AuthenticationFilter에 대한 인스턴스를 생성한다. 파라미터로는 authenticationManager(), userService가 필요하며 추가적으로 필요한 파라미터가 있다면 유동적으로 생성자를 추가해주면 된다!


Servlet Filter는 Spring Framework의 일부가 아니라 Java EE 표준 (Java Servlet API)에 속하는 웹 애플리케이션 구성 요소이다. Filter는 Java Servlet 스펙에서 제공하는 것이며, Spring Framework의 IoC(Inversion of Control) 컨테이너에 의해 관리되는 Spring Bean이 아니다.

의존성 주입은 Spring Framework의 관리 아래에 있는 빈(Bean) 클래스들 간에 이루어지기 때문에 의존성 주입(Manager, userService)을 받은 WebSecuirty에서 넘겨주어야 한다.



2-5. successfulAuthentication

[AuthenticationFilter.java]

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private UserService userService;

    public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService) 
    {...}

    public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService, String endPoint) 
    {...}


	@Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException 
  	{...}
    

    // JWT Token을 생성하고 response
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {

        String userId = ((User) authResult.getPrincipal()).getUsername();
        UserResponseDto userDetails = userService.getUserDetailsByUserId(userId);

        String token = Jwts.builder()
                .setSubject(userDetails.getUserId())
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpirationTime))
                .signWith(Keys.hmacShaKeyFor(tokenSecret.getBytes()), SignatureAlgorithm.HS512)
                .compact();


        response.addHeader("token", token);
        response.addHeader("userId", userDetails.getUserId());
    }
}

attemptAuthentication 메서드에서 AuthenticationManager에 등록된 토큰이 문제없이 인증되었다면, 다음으로 successfulAuthentication 메서드가 실행된다.

클라이언트가 성공적으로 인증되었을 때 수행해야 하는 작업을 정의하는 데 사용되며, 일반적으로는 로그인 후 작업을 수행하거나 토큰을 생성하고 클라이언트에게 응답하는데 활용된다.



POSTMan 을 활용하여 회원가입과 로그인을 진행해보자.
아래의 사진을 보면 HttpStatus Code (200 OK) 를 응답받아 성공적으로 로그인에 성공했다. Header를 살펴보면 발급받은 token과 회원가입 시 부여받은 userCode를 확인할 수 있다.



마무리

이로써 SpringSecuirty를 활용하여 클라이언트의 요청에 대해 인증/인가 작업과 JWT Token을 발행하는 방법에 대해 알아보았다. 다음 포스팅에서는 왜 JWT Token에 대해 알아보고 서버단에서 어떻게 Token을 통해 사용자의 신원을 검증하는지 알아보자.





참고문헌
Inflearn: Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA) 강의자료
https://programmer93.tistory.com/78
https://mangkyu.tistory.com/76

0개의 댓글