Search in sources :

Example 61 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenPrivateKeyJwtClientAuthenticationMethodThenCustomized.

@Test
public void convertWhenPrivateKeyJwtClientAuthenticationMethodThenCustomized() throws Exception {
    RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
    given(this.jwkResolver.apply(any())).willReturn(rsaJwk);
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE)).isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    assertThat(encodedJws).isNotNull();
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build();
    Jwt jws = jwtDecoder.decode(encodedJws);
    assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(SignatureAlgorithm.RS256.getName());
    assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
    assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getAudience()).isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
    assertThat(jws.getId()).isNotNull();
    assertThat(jws.getIssuedAt()).isNotNull();
    assertThat(jws.getExpiresAt()).isNotNull();
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Jwt(org.springframework.security.oauth2.jwt.Jwt) Test(org.junit.jupiter.api.Test)

Example 62 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenClientSecretJwtClientAuthenticationMethodThenCustomized.

@Test
public void convertWhenClientSecretJwtClientAuthenticationMethodThenCustomized() {
    OctetSequenceKey secretJwk = TestJwks.DEFAULT_SECRET_JWK;
    given(this.jwkResolver.apply(any())).willReturn(secretJwk);
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE)).isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    assertThat(encodedJws).isNotNull();
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build();
    Jwt jws = jwtDecoder.decode(encodedJws);
    assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(MacAlgorithm.HS256.getName());
    assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(secretJwk.getKeyID());
    assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getAudience()).isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
    assertThat(jws.getId()).isNotNull();
    assertThat(jws.getIssuedAt()).isNotNull();
    assertThat(jws.getExpiresAt()).isNotNull();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Jwt(org.springframework.security.oauth2.jwt.Jwt) OctetSequenceKey(com.nimbusds.jose.jwk.OctetSequenceKey) Test(org.junit.jupiter.api.Test)

Example 63 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class OAuth2ResourceServerConfigurerTests method requestWhenCustomJwtValidatorFailsThenCorrespondingErrorMessage.

@Test
public void requestWhenCustomJwtValidatorFailsThenCorrespondingErrorMessage() throws Exception {
    this.spring.register(RestOperationsConfig.class, CustomJwtValidatorConfig.class).autowire();
    mockRestOperations(jwks("Default"));
    String token = this.token("ValidNoScopes");
    OAuth2TokenValidator<Jwt> jwtValidator = this.spring.getContext().getBean(CustomJwtValidatorConfig.class).getJwtValidator();
    OAuth2Error error = new OAuth2Error("custom-error", "custom-description", "custom-uri");
    given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(error));
    // @formatter:off
    this.mvc.perform(get("/").with(bearerToken(token))).andExpect(status().isUnauthorized()).andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("custom-description")));
// @formatter:on
}
Also used : Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test)

Example 64 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class OAuth2ResourceServerConfigurerTests method requestWhenJwtAuthenticationConverterConfiguredOnDslThenIsUsed.

@Test
public void requestWhenJwtAuthenticationConverterConfiguredOnDslThenIsUsed() throws Exception {
    this.spring.register(JwtDecoderConfig.class, JwtAuthenticationConverterConfiguredOnDsl.class, BasicController.class).autowire();
    Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = this.spring.getContext().getBean(JwtAuthenticationConverterConfiguredOnDsl.class).getJwtAuthenticationConverter();
    given(jwtAuthenticationConverter.convert(JWT)).willReturn(JWT_AUTHENTICATION_TOKEN);
    JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(jwtDecoder.decode(anyString())).willReturn(JWT);
    // @formatter:off
    this.mvc.perform(get("/").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk());
    // @formatter:on
    verify(jwtAuthenticationConverter).convert(JWT);
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) Test(org.junit.jupiter.api.Test)

Example 65 with JWT

use of com.auth0.jwt.JWT in project yyl_example by Relucent.

the class JwtDemo method main.

public static void main(String[] args) throws Exception {
    long currentMillis = System.currentTimeMillis();
    // JWT 生存时间(5秒)
    long ttl = 5000;
    // 生成JWT的时间
    Date iat = new Date(currentMillis);
    // 生成JWT失效时间
    Date exp = new Date(currentMillis + ttl);
    // 签名秘钥
    String secret = "key";
    // 签发人
    String issuer = "root";
    // 算法
    Algorithm algorithm = Algorithm.HMAC256(secret);
    // 本地的密码解码
    JWTCreator.Builder builder = JWT.create();
    // 签发时间
    builder.withIssuedAt(iat);
    // 签发人
    builder.withIssuer(issuer);
    // 过期时间
    builder.withExpiresAt(exp);
    // 主题
    builder.withClaim("subject", "MySubject");
    String token = builder.sign(algorithm);
    System.out.println(token);
    // 解密
    JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
    DecodedJWT jwt = verifier.verify(token);
    Map<String, Claim> claims = jwt.getClaims();
    NullClaim nullClaim = new NullClaim();
    System.out.println(claims.getOrDefault("subject", nullClaim).asString());
    // 等待5秒
    System.out.println("Wait 5 seconds!");
    Thread.sleep(5000);
    try {
        // 这时候Token已经超时了,会抛出异常
        verifier.verify(token);
    } catch (JWTVerificationException e) {
        System.err.println(e);
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTCreator(com.auth0.jwt.JWTCreator) NullClaim(com.auth0.jwt.impl.NullClaim) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)99 Test (org.junit.jupiter.api.Test)80 GrantedAuthority (org.springframework.security.core.GrantedAuthority)51 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)23 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 Arrays (java.util.Arrays)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 List (java.util.List)17 Algorithm (com.auth0.jwt.algorithms.Algorithm)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Authentication (org.springframework.security.core.Authentication)16 Test (org.junit.Test)14 HashMap (java.util.HashMap)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Instant (java.time.Instant)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 JWTVerifier (com.auth0.jwt.JWTVerifier)10