Skip to content

Commit 9cf5638

Browse files
chanbinmerwinch
authored andcommitted
Add null check for authentication token in JwtAuthenticationProvider
Add Assert.notNull validation to ensure the authentication token returned by jwtAuthenticationConverter is not null, preventing potential NullPointerException in subsequent operations. Signed-off-by: chanbinme <[email protected]>
1 parent c2c84c4 commit 9cf5638

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProvider.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ public Authentication authenticate(Authentication authentication) throws Authent
8787
BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
8888
Jwt jwt = getJwt(bearer);
8989
AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt);
90+
Assert.notNull(token, "token cannot be null");
9091
if (token.getDetails() == null) {
9192
token.setDetails(bearer.getDetails());
9293
}

oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@
3535
import org.springframework.security.oauth2.jwt.TestJwts;
3636
import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes;
3737

38-
import static org.assertj.core.api.Assertions.assertThat;
39-
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
38+
import static org.assertj.core.api.Assertions.*;
4039
import static org.mockito.BDDMockito.given;
4140
import static org.mockito.Mockito.mock;
4241

@@ -152,6 +151,19 @@ public void authenticateWhenConverterSetsAuthenticationDetailsThenProviderDoesNo
152151
// @formatter:on
153152
}
154153

154+
@Test
155+
public void authenticateWhenConverterReturnsNullThenThrowException() {
156+
BearerTokenAuthenticationToken token = this.authentication();
157+
Jwt jwt = TestJwts.jwt().build();
158+
given(this.jwtDecoder.decode("token")).willReturn(jwt);
159+
given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(null);
160+
// @formatter:off
161+
assertThatIllegalArgumentException()
162+
.isThrownBy(() -> this.provider.authenticate(token))
163+
.withMessageContaining("token cannot be null");
164+
// @formatter:on
165+
}
166+
155167
@Test
156168
public void supportsWhenBearerTokenAuthenticationTokenThenReturnsTrue() {
157169
assertThat(this.provider.supports(BearerTokenAuthenticationToken.class)).isTrue();

0 commit comments

Comments
 (0)