1. 개요
이 빠른 튜토리얼에서는 Spring Security OAuth2 구현을 다루며 Spring Security OAuth 2.2.0.RELEASE 에서 소개 된 새로운 JwtClaimsSetVerifier를 사용하여 JWT 클레임을 확인하는 방법을 학습합니다 .
2. Maven 설정
첫째, 우리는 최신 버전의 스프링 보안으로 OAuth2를 pom.xml 파일에 추가:
1 2 3 4 5 |
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.2.0.RELEASE</version> </dependency> |
3. 토큰 저장소 구성
다음으로 Resource Server에 TokenStore 를 구성 해 봅시다 :
1 2 3 4 5 6 7 8 9 10 11 12 |
@Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); }
@Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("123"); converter.setJwtClaimsSetVerifier(jwtClaimsSetVerifier()); return converter; } |
JwtAccessTokenConverter에 새로운 검증자를 추가하는 방법에 유의하십시오 .
JwtTokenStore 를 구성하는 방법에 대한 자세한 내용은 Spring Security OAuth에서 JWT 사용에 대한 글을 확인하십시오 .
다음 섹션에서는 다양한 유형의 클레임 검증 자와 이들을 함께 작동시키는 방법에 대해 살펴 보겠습니다.
4. IssuerClaimVerifier
다음과 같이 IssuerClaimVerifier를 사용하여 Issuer " iss "클레임을 확인함으로써 간단하게 시작할 것입니다 .:
1 2 3 4 5 6 7 8 |
@Bean public JwtClaimsSetVerifier issuerClaimVerifier() { try { return new IssuerClaimVerifier(new URL("http://localhost:8081")); } catch (MalformedURLException e) { throw new RuntimeException(e); } } |
이 예제에서는 발급자를 확인하기 위해 간단한 IssuerClaimVerifier 를 추가했습니다 . JWT 토큰에 발급자 "iss"클레임에 다른 값이 포함되어 있으면 간단한 InvalidTokenException 이 발생합니다.
물론 토큰에 발급자 "iss"클레임이 포함되어 있으면 예외가 throw되지 않고 토큰이 유효한 것으로 간주됩니다.
5. 사용자 정의 Claim Verifier
여기서 흥미로운 점은 사용자 정의 검증 검증 프로그램을 구축 할 수 있다는 것입니다.:
1 2 3 4 |
@Bean public JwtClaimsSetVerifier customJwtClaimVerifier() { return new CustomClaimVerifier(); } |
다음은 JWT 토큰에 user_name 클레임이 있는지 확인하기위한 간단한 구현입니다 .:
1 2 3 4 5 6 7 8 9 |
public class CustomClaimVerifier implements JwtClaimsSetVerifier { @Override public void verify(Map<String, Object> claims) throws InvalidTokenException { String username = (String) claims.get("user_name"); if ((username == null) || (username.length() == 0)) { throw new InvalidTokenException("user_name claim is empty"); } } } |
여기서 JwtClaimsSetVerifier 인터페이스 를 구현하는 방법을 확인한 다음 verify 메소드에 대한 완벽한 사용자 정의 구현을 제공하여 필요한 모든 유형의 체크에 대해 완전한 유연성을 제공합니다.
6.여러 클레임 검증 자 결합
마지막으로, 다음과 같이 DelegatingJwtClaimsSetVerifier를 사용하여 여러 클레임 확인자를 결합하는 방법을 살펴 보겠습니다:
1 2 3 4 5 |
@Bean public JwtClaimsSetVerifier jwtClaimsSetVerifier() { return new DelegatingJwtClaimsSetVerifier(Arrays.asList( issuerClaimVerifier(), customJwtClaimVerifier())); } |
DelegatingJwtClaimsSetVerifier 는 JwtClaimsSetVerifier 객체 의 목록을 가져 와서 검증 확인 프로세스를 이러한 검증 자에게 위임합니다.
7. 간단한 통합 테스트
구현이 완료되었으므로 간단한 통합 테스트 를 통해 클레임 검증자를 테스트 해 봅시다 .
1 2 3 4 5 6 7 8 9 10 11 |
@RunWith(SpringRunner.class) @SpringBootTest( classes = ResourceServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class JwtClaimsVerifierIntegrationTest {
@Autowired private JwtTokenStore tokenStore;
... } |
우리는 발급자를 포함하지 않지만 ( user_name을 포함하는 ) 토큰으로 시작할 것입니다 - 유효해야합니다 :
1 2 3 4 5 6 7 |
@Test public void whenTokenDontContainIssuer_thenSuccess() { String tokenValue = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...."; OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue);
assertTrue(auth.isAuthenticated()); } |
이것이 유효한 이유는 간단합니다. 첫 번째 확인자는 발급자 소유권이 토큰에있는 경우에만 활성화됩니다. 해당 소유권 주장이 존재하지 않으면 검증자가 실행되지 않습니다.
다음으로 유효한 발급자 ( http : // localhost : 8081 )와 user_name 을 포함하는 토큰을 살펴 보겠습니다 . 이것은 또한 유효해야합니다 :
1 2 3 4 5 6 7 |
@Test public void whenTokenContainValidIssuer_thenSuccess() { String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...."; OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue);
assertTrue(auth.isAuthenticated()); } |
토큰에 유효하지 않은 발급자 ( http : // localhost : 8082 )가 포함되어 있으면 유효성이 확인되고 유효성이 확인됩니다.
1 2 3 4 5 6 7 |
@Test(expected = InvalidTokenException.class) public void whenTokenContainInvalidIssuer_thenException() { String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...."; OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue);
assertTrue(auth.isAuthenticated()); } |
다음으로, 토큰에 user_name 클레임이 포함되어 있지 않으면 무효가됩니다.
1 2 3 4 5 6 7 |
@Test(expected = InvalidTokenException.class) public void whenTokenDontContainUsername_thenException() { String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...."; OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue);
assertTrue(auth.isAuthenticated()); } |
마지막으로 토큰에 빈 user_name 클레임이 포함되어 있으면이 토큰 도 유효하지 않습니다.
1 2 3 4 5 6 7 |
@Test(expected = InvalidTokenException.class) public void whenTokenContainEmptyUsername_thenException() { String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...."; OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue);
assertTrue(auth.isAuthenticated()); } |
8. 결론
이 기사에서는 Spring Security OAuth의 새로운 검증 기능에 대해 살펴 보았습니다.
항상 그렇듯이 전체 소스 코드는 GitHub에서 사용할 수 있습니다 .
[출처]https://www.baeldung.com/spring-security-oauth-2-verify-claims
'SPRING' 카테고리의 다른 글
[Spring] UriComponents 클래스 (0) | 2020.02.21 |
---|---|
[Spring] 단일, 다중파일 업로드하기 (0) | 2019.07.05 |