Spring Security

[Spring Security 6.x] Authentication Manager / Authentication Provider

person456 2024. 6. 22. 18:06

1.  Athentication Manager

 

Authentication Manager는 Filter로부터 Authentication 객체를 전달받은 이후 해당 객체에 대한 인증 처리를 Authentication Provider 객체에게 위임한다.

만약 Provider에 의해 정상적으로 인증이 완료되었다면 사용자 정보, 권한 등이 완전히 채워진 Authentication 객체를 Provider로부터 받아 이를 Filter에게 넘겨준다.

 

즉, 일련의 과정 자체를 봤을 때 Authentication Manager는 인증을 위한 Provider와 인증 전 Filter를 연결하기 위한 다리 역할을 하고 있는 것이다.

 

이 과정 속에서 Authentication Manager에는 여러 Authentication Provider 들을 관리하며 인증 요청이 들어오면 갖고있는 Provider의 목록들을 순차적으로 조회하며 인증처리를 진행할 수 있는 올바른 Provider에게 해당 인증을 위임한다.


 

 

위의 그림과 같이 사용자는 여러 방법을 통해 인증 요청을 서버로 보낼 수 있다.

따라서 Authentication Manager는 자신이 갖고있는 여러 Provider들을 순차적으로 조회하며 해당 요청을 적절히 수행할 수 있는 Provider에게 인증 요청을 위임하는 것이다.

하지만 만약 자신이 갖고 있는 Provider 중 그러한 내용을 처리할 수 없다면 부모 Authentication Manager의 Providers까지 조회하여 처리하려는 동작을 취한다.

하지만 부모까지 조회한 결과 적절한 Provider를 찾지 못했을 때, ProviderNotFountException 예외를 발생시킨다.


 

 

코드를 살펴보면 List<AuthenticationProvider>에는 Provider를 List형태로 모아놓은 providers 변수가 존재하고,

AuthenticationManager 타입의 변수 parent가 존재한다.

 

해당 코드는 Provider Manager의 "authenticated()" 메서드의 내부 코드다.

코드를 살펴보면 자신이 갖고있는 Provider를 토대로 반복을 돌려 사용자의 요청을 처리할 수 있는 알맞은 Provider를 순차적으로 조회한다.

앞서 언급했듯 Authentication Manager는 Filter와 Provider를 연결해주는 다리의 역할을 해주기 때문에 자신이 실질적으로 인증 절차를 수행하는 것이 아닌, provider의 authenticate() 메서드를 통해 인증 결과를 넘겨받는 것을 확인할 수 있다.

 

 

또한 자신이 갖고있는 Provider들로는 해당 요청을 처리하지 못해서 result의 값이 null일 경우를 대비한 if문이 존재한다.

해당 내용은 result가 null이지만 자신의 parent가 null이 아닐 때, parent를 통해 authenticate() 메서드를 호출하는 것을 볼 수 있다.

즉, 자신의 Provider 뿐 아니라 부모의 Provider 역시 순차 조회하여 인증을 처리하려는 시도를 하는 것이다.

해당 시도를 거쳐 만약 인증을 처리하지 못한다면 ProviderNotFoundException 예외를 발생시킨다.

 

 

 

 

2. Authentication Provider

 

Authentication Provider는 Authentication Manager로부터 넘겨받은 Authentication 객체를 토대로, 사용자의 자격 증명을 실질적으로 처리하는 클래스다.

인증이 성공적으로 마무리가 된다면 Authentication 타입의 객체에 권한 정보, 인증 여부 정보, 신원 정보 등을 넣어 다시 Authentication Manager에게 반환하고 인증 과정 중 문제가 생긴다면 AuthenticationException과 같은 예외를 발생시킨다.