[스프링] Spring Security + JWT 발급 및 로그인(1)

CodeByHan·2024년 10월 2일

스프링

목록 보기
5/33
post-thumbnail

인증(Authentication)
보호된 리소스에 접근하는 대상,즉 사용자에게 적절한 접근 권한이 있는지 확인하는 일련의 과정(해당 사용자가 본인이 맞는지 확인)
인가(Authorization)
인증절차가 끝난 접근 주체(Principal)가 보호된 리소스에 접근 가능한지를 결정하는 것을 의미(인증된 사용자가 요청한 자원에 접근 가능한지를 결정)

스프링 시큐리티(Spring Security)

스프링 시큐리티란?

  • API가 실행될 때마다 사용자를 인증해야하는데, 그 인증을 구현 한 것
  • 스프링 기반의 애플리케이션의 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크
  • 인증(Authenticate, 누구인가)과 인가(Authorize,어떤것을 할 수 있는지)를 담당하는 프레임워크
  • Spring Security는 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에,개발자 입장에서 일일이 보안 관련 로직을 작성하지 않아도 된다는 장점
  • Filter 흐름에 따라 처리
    Client (request) → Filter → DispatcherServlet → Interceptor → Controller

Spring Security Architecture

  1. 사용자가 로그인 정보(아이디,비밀번호 등)와 함께 인증 요청(http Request)

  2. AuthenticationFilter(인증 필터)가 요청 가로챔 -> 가로챈 정보를 통해 UsernamePasswordAuthenticationToken의 인증용 객체 생성

  3. AuthenticationManager의 구현체인 ProviderManager에게 생성한 UsernamePasswordToken 객체 전달

  4. AuthenticationManager는 등록된 AuthenticationProvider 조회-> 인증 요구

  5. 실제 DB에서 사용자 인증정보를 가져오는 UserDetailsService에 사용자 정보 넘겨줌

  6. 넘겨받은 사용자 정보를 통해 DB에서 찾은 사용자 정보인 UserDetails 객체 생성

  7. AuthenticationProvider는 UserDeatils를 넘겨받고 사용자 정보 비교

  8. 인증이 완료되면 권한 등의 사용자 정보를 담은 Authentication 객체 반환

  9. 다시 최초의 AuthenticationFilter에 Authentication 객체가 반환

  10. Authentication 객체를 SecurityContext에 저장

최종적으로 SecurityContextHolder는 세션 영역에 있는 SecurityContext에 Authentication 객체 저장

사용자 정보를 저장한다는 것은 Spring Security가 전통적인 세션-쿠키 기반의 인증 방식을 사용한다는 것을 의미

Authentication

  • 현재 접근하는 주체의 정보와 권한을 담는 인터페이스
  • Authentication 객체는 SecurityContext에 저장되며,SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근 가능
public interface Authentication extends Principal, Serializable {

	// 현재 사용자의 권한 목록을 가져옴
    // 인증된 사용자가 여러 권한을 가질 수 있기 때문에, 권한 목록은 Collection 타입으로 반환

	Collection<? extends GrantedAuthority> getAuthorities();

    

	// credentials(주로 비밀번호)을 가져옴

	Object getCredentials();

    

	Object getDetails();

 

	// Principal(인증된 사용자를 표현하는 객체) 객체를 가져옴

	Object getPrincipal();

 

	// 인증 여부를 가져옴(true이면 사용자는 인증된 상태이며, false이면 인증되지 않은 상태)

	boolean isAuthenticated();

    

	// 인증 여부를 설정함

	void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;

 
}

사용 예시

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

// 사용자 이름 (Principal)
String username = authentication.getName();

// 사용자 권한 목록
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

// 인증 여부 확인
boolean isAuthenticated = authentication.isAuthenticated();

UsernamePasswordAuthenticationToken

  • UsernamePasswordAuthenticationToken은 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스

  • User의 ID가 Principal 역할을 하고, Password가 Credential의 역할

  • UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두번째는 인증이 완료된 객체를 생성

public abstract class AbstractAuthenticationToken implements Authentication, CredentialsContainer {

}

 

public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {

 

	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

 

	// 주로 사용자의 ID에 해당

	private final Object principal;

 

	// 주로 사용자의 PW에 해당

	private Object credentials;

 

	// 인증 완료 전의 객체 생성

	public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {

		super(null);

		this.principal = principal;

		this.credentials = credentials;

		setAuthenticated(false);

	}

 

	// 인증 완료 후의 객체 생성

	public UsernamePasswordAuthenticationToken(Object principal, Object credentials,

			Collection<? extends GrantedAuthority> authorities) {

		super(authorities);

		this.principal = principal;

		this.credentials = credentials;

		super.setAuthenticated(true); // must use super, as we override

	}

}

AuthenticationManager

  • 인증에 대한 부분은 AuthenticationManager를 통해서 처리하게 되는데, 실질적으로는 AuthenticationManager에등록된 AuthenticationProvider에 의해 처리
  • 인증에 성공하면 두번째 생성자를 이용해 객체를 생성하여 SecurityContext에 저장
public interface AuthenticationManager {

    // 주어진 인증 정보(Authentication 객체)를 사용해 인증을 시도하고, 성공하면 인증된 Authentication 객체를 반환
    // 인증 실패 시 AuthenticationException을 던짐
	Authentication authenticate(Authentication authentication) throws AuthenticationException;


}

AuthenticationProvider

  • AuthenticationProvider에서는 실제 인증에 대한 부분을 처리하는데, 인증 전의 Authentication 객체를 받아서 인증이 완료된 객체를 반환하는 역할
  • 아래와 같은 인터페이스를 구현해 Custom한 AuthenticationProvider를 작성하고 AuthenticationManager에 등록
public interface AuthenticationProvider {

 

	Authentication authenticate(Authentication authentication) throws AuthenticationException;



	boolean supports(Class<?> authentication);

 

}

ProviderManager

  • AuthenticationManager를 implements한 ProviderManager는 AuthenticationProvider를 구성하는 목록을 갖는다
public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {

	

    public List<AuthenticationProvider> getProviders() {

		return this.providers;

	}

    

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		Class<? extends Authentication> toTest = authentication.getClass();

		AuthenticationException lastException = null;

		AuthenticationException parentException = null;

		Authentication result = null;

		Authentication parentResult = null;

		int currentPosition = 0;

		int size = this.providers.size();

        

        // for문으로 모든 provider를 순회하여 처리하고 result가 나올때까지 반복한다.

		for (AuthenticationProvider provider : getProviders()) { ... }

	}

}

UserDetailsService

  • UserDetailsService는 UserDetails 객체를 반환하는 하나의 메소드만을 가지고 있는데, 일반적으로 이를 implements한 클래스에 UserRepository를 주입받아 DB와 연결하여 처리한다.
public interface UserDetailsService {


	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

}

UserDetails

  • 인증에 성공하여 생성된 UserDetails 객체는 Authentication객체를 구현한 UsernamePasswordAuthenticationToken을 생성하기 위해 사용된다. UserDetails를 implements하여 처리할 수 있다.
public interface UserDetails extends Serializable {

 

	// 권한 목록

	Collection<? extends GrantedAuthority> getAuthorities();

 

	String getPassword();

 

	String getUsername();

 

	// 계정 만료 여부

	boolean isAccountNonExpired();

 

	// 계정 잠김 여부

	boolean isAccountNonLocked();

 

	// 비밀번호 만료 여부

	boolean isCredentialsNonExpired();

 

	// 사용자 활성화 여부

	boolean isEnabled();

 

}

SecurityContextHolder
보안 주체의 세부 정보를 포함하여 응용프로그램의 현재 보안 컨텍스트에 대한 세부 정보가 저장된다.

SecurityContext
Authentication을 보관하는 역할을 하며, SecurityContext를 통해 Authentication을 저장하거나 꺼내올 수 있다.

GrantedAuthority
현재 사용자(Principal)가 가지고 있는 권한을 의미하며, ROLEADMIN이나 ROLE_USER와 같이 ROLE*의 형태로 사용한다. GrantedAuthority 객체는 UserDetailsService에 의해 불러올 수 있고, 특정 자원에 대한 권한이 있는지를 검사하여 접근 허용 여부를 결정한다.

출처
참고

profile
노력은 배신하지 않아 🔥

0개의 댓글