Java Code Examples for org.springframework.security.oauth2.jwt.JwtDecoder

The following examples show how to use org.springframework.security.oauth2.jwt.JwtDecoder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-cloud-gcp   Source File: FirebaseJwtTokenDecoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Jwt decode(String token) throws JwtException {
	SignedJWT jwt = parse(token);
	if (isExpired()) {
		try {
			keysLock.tryLock();
			refresh();
		}
		finally {
			keysLock.unlock();
		}
	}
	JwtDecoder decoder = delegates.get(jwt.getHeader().getKeyID());
	if (decoder == null) {
		throw new JwtException("No certificate found for key: " + jwt.getHeader().getKeyID());
	}
	return decoder.decode(token);
}
 
Example 2
@Test
public void testUserBeansReturnedUserConfigPresent() {
	this.contextRunner
			.withUserConfiguration(UserConfiguration.class)
			.withPropertyValues("spring.cloud.gcp.security.iap.audience=unused")
			.run((context) -> {
				JwtDecoder jwtDecoder =  context.getBean(JwtDecoder.class);
				assertThat(jwtDecoder).isNotNull();
				assertThat(jwtDecoder).isNotInstanceOf(NimbusJwtDecoderJwkSupport.class);
				assertThat(jwtDecoder.decode("Ceci n'est pas un Jwt")).isSameAs(mockJwt);

				BearerTokenResolver resolver = context.getBean(BearerTokenResolver.class);
				assertThat(resolver).isNotNull();
				assertThat(resolver.resolve(this.mockIapRequest)).isEqualTo(FAKE_USER_TOKEN);
				assertThat(resolver.resolve(this.mockNonIapRequest)).isEqualTo(FAKE_USER_TOKEN);
			});
}
 
Example 3
@Bean
public JwtDecoder jwtDecoderByIssuerUri() {
    final String jwkSetUri = getClientRegistration().getProviderDetails().getJwkSetUri();
    final NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
    jwtDecoder.setClaimSetConverter(new KeycloakUsernameSubClaimAdapter(getProvider().getUserNameAttribute()));;
    return jwtDecoder;
}
 
Example 4
@Bean
@ConditionalOnBean({ XsuaaServiceConfiguration.class, RestOperations.class })
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnMissingBean
public JwtDecoder xsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration,
		RestOperations xsuaaRestOperations) {
	logger.debug("auto-configures JwtDecoder using restOperations of type: {}", xsuaaRestOperations);
	return new XsuaaJwtDecoderBuilder(xsuaaServiceConfiguration)
			.withRestOperations(xsuaaRestOperations)
			.build();
}
 
Example 5
/**
 * Assembles a JwtDecoder
 *
 * @return JwtDecoder
 */
public JwtDecoder build() {
	XsuaaJwtDecoder jwtDecoder = new XsuaaJwtDecoder(configuration, decoderCacheValidity, decoderCacheSize,
			getValidators(), postValidationActions);
	Optional.ofNullable(restOperations).ifPresent(jwtDecoder::setRestOperations);
	return jwtDecoder;
}
 
Example 6
@Test
public void autoConfigurationActive() {
	contextRunner.run((context) -> {
		assertThat(context.containsBean("xsuaaJwtDecoder"), is(true));
		assertThat(context.getBean("xsuaaJwtDecoder"), instanceOf(XsuaaJwtDecoder.class));
		assertThat(context.getBean(JwtDecoder.class), is(not(nullValue())));
		assertThat(context.getBean(JwtDecoder.class), instanceOf(XsuaaJwtDecoder.class));
	});
}
 
Example 7
@Test
public void autoConfigurationActiveInclProperties() {
	contextRunner
			.withPropertyValues("spring.xsuaa.auto:true").run((context) -> {
				assertThat(context.containsBean("xsuaaJwtDecoder"), is(true));
				assertThat(context.getBean("xsuaaJwtDecoder"), instanceOf(XsuaaJwtDecoder.class));
				assertThat(context.getBean(JwtDecoder.class), is(not(nullValue())));
			});
}
 
Example 8
@Test(expected = IllegalArgumentException.class) // Passed JwtDecoder instance must be of type 'XsuaaJwtDecoder'
public void initSecurityContextRaiseExceptionIfNotXsuaaJwtDecoder() {
	String message = "";
	SpringSecurityContext.init(token_1.getTokenValue(), new JwtDecoder() {
		@Override
		public Jwt decode(String s) throws JwtException {
			return token_1;
		}
	}, new DefaultAuthoritiesExtractor());
}
 
Example 9
@Test
public void decode_withVerficationKey() throws IOException {
	String token = IOUtils.resourceToString("/accessTokenRSA256WithVerificationKey.txt", StandardCharsets.UTF_8);
	final JwtDecoder cut = new XsuaaJwtDecoderBuilder(configurationWithVerificationKey).build();

	final Jwt jwt = cut.decode(token);

	assertThat(jwt.getClaimAsString(TokenClaims.CLAIM_CLIENT_ID)).isEqualTo("sb-clientId!t0815");
}
 
Example 10
@Test
public void decode_withNonMatchingVerificationKey_throwsException() throws IOException {
	String token = IOUtils.resourceToString("/token_cc.txt", StandardCharsets.UTF_8);

	final JwtDecoder cut = new XsuaaJwtDecoderBuilder(configuration).build();

	assertThatThrownBy(() -> cut.decode(token)).isInstanceOf(JwtException.class)
			.hasMessageContaining("Cannot verify with online token key, jku, kid, uaadomain is null");
}
 
Example 11
@Bean
@ConditionalOnMissingBean(name = "firebaseAuthenticationJwtDecoder")
public JwtDecoder firebaseAuthenticationJwtDecoder(
		DelegatingOAuth2TokenValidator<Jwt> firebaseJwtDelegatingValidator,
		FirebaseAuthenticationProperties properties) {
	return new FirebaseJwtTokenDecoder(restOperations(), properties.getPublicKeysEndpoint(),
			firebaseJwtDelegatingValidator);
}
 
Example 12
@Bean
@ConditionalOnMissingBean
public JwtDecoder iapJwtDecoder(IapAuthenticationProperties properties,
		@Qualifier("iapJwtDelegatingValidator") DelegatingOAuth2TokenValidator<Jwt> validator) {

	NimbusJwtDecoderJwkSupport jwkSupport
			= new NimbusJwtDecoderJwkSupport(properties.getRegistry(), properties.getAlgorithm());
	jwkSupport.setJwtValidator(validator);

	return jwkSupport;
}
 
Example 13
@Test
public void testAutoconfiguredBeansMissingWhenGatingPropertyFalse() {

	this.expectedException.expect(NoSuchBeanDefinitionException.class);
	this.expectedException.expectMessage("No qualifying bean of type " +
			"'org.springframework.security.oauth2.jwt.JwtDecoder' available");

	this.contextRunner
			.withPropertyValues("spring.cloud.gcp.security.iap.enabled=false")
			.run((context) ->	context.getBean(JwtDecoder.class));
}
 
Example 14
private void verifyJwtBeans(AssertableApplicationContext context) {
	JwtDecoder jwtDecoder =  context.getBean(JwtDecoder.class);
	assertThat(jwtDecoder).isNotNull();
	assertThat(jwtDecoder).isInstanceOf(NimbusJwtDecoderJwkSupport.class);

	BearerTokenResolver resolver = context.getBean(BearerTokenResolver.class);
	assertThat(resolver).isNotNull();
	assertThat(resolver.resolve(this.mockIapRequest)).isEqualTo("very fake jwt");

	assertThat(resolver.resolve(this.mockNonIapRequest)).isNull();
}
 
Example 15
Set<GrantedAuthority> extract(final ClientRegistration clientRegistration, final String tokenValue) {
    try {
        // Token is already verified by spring security
        final JwtDecoder jwtDecoder = new NimbusJwtDecoderJwkSupport(
                clientRegistration.getProviderDetails().getJwkSetUri());
        final Jwt token = jwtDecoder.decode(tokenValue);

        return extract(clientRegistration.getClientId(), token.getClaims());
    } catch (final JwtException e) {
        throw new OAuth2AuthenticationException(INVALID_REQUEST, e);
    }
}
 
Example 16
Source Project: platform   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public WebSecurityConfig(PasswordEncoder passwordEncoder,
                         JwtDecoder jwtDecoder,
                         SecurityUserDetailsService userDetailsService) {
    this.passwordEncoder = passwordEncoder;
    this.jwtDecoder = jwtDecoder;
    this.userDetailsService = userDetailsService;
}
 
Example 17
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example 18
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example 19
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example 20
@Bean
public JwtDecoder xsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration) {
	return new XsuaaJwtDecoderBuilder(xsuaaServiceConfiguration).build();
}
 
Example 21
@Bean
public JwtDecoder xsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration) {
	return new XsuaaJwtDecoderBuilder(xsuaaServiceConfiguration).build();
}
 
Example 22
@Bean
public JwtDecoder customJwtDecoder() {
	return NimbusJwtDecoder.withJwkSetUri("http://localhost:8080/uaa/oauth/token_keys").build();
}
 
Example 23
@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
}
 
Example 24
Source Project: grpc-spring-boot-starter   Source File: SecurityConfiguration.java    License: MIT License 4 votes vote down vote up
@Bean
JwtDecoder jwtDecoder() {
    // Uses local Keycloak instance running on port 8080 with the realm: TestRealm
    final String endpointURI = "http://localhost:8080/auth/realms/TestRealm/protocol/openid-connect/certs";
    return NimbusJwtDecoder.withJwkSetUri(endpointURI).build();
}
 
Example 25
@Bean
public JwtDecoder jwtDecoder() {
	return (s) -> mockJwt;
}
 
Example 26
Source Project: grpc-spring-boot-starter   Source File: SecurityConfiguration.java    License: MIT License 4 votes vote down vote up
@Bean
JwtDecoder jwtDecoder() {
    // Uses local Keycloak instance running on port 8080 with the realm: TestRealm
    final String endpointURI = "http://localhost:8080/auth/realms/TestRealm/protocol/openid-connect/certs";
    return NimbusJwtDecoder.withJwkSetUri(endpointURI).build();
}
 
Example 27
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example 28
Source Project: platform   Source File: SecurityConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public JwtDecoder jwtDecoder(KeyPair keyPair) {
    return NimbusJwtDecoder.withPublicKey((RSAPublicKey) keyPair.getPublic()).build();
}
 
Example 29
/**
 * Initializes the Spring Security Context {@link SecurityContextHolder} and
 * extracts the authorities. With version 1.5.0 you can configure your own
 * {@link AuthoritiesExtractor} to specify how to extract the authorities.
 *
 * @param encodedJwtToken
 *            the jwt token that is decoded with the given JwtDecoder
 * @param xsuaaJwtDecoder
 *            the decoder of type {@link XsuaaJwtDecoder}
 * @param authoritiesExtractor
 *            the extractor used to turn Jwt scopes into Spring Security
 *            authorities.
 */
static public void init(String encodedJwtToken, JwtDecoder xsuaaJwtDecoder,
		AuthoritiesExtractor authoritiesExtractor) {
	Assert.isInstanceOf(XsuaaJwtDecoder.class, xsuaaJwtDecoder,
			"Passed JwtDecoder instance must be of type 'XsuaaJwtDecoder'");
	Jwt jwtToken = xsuaaJwtDecoder.decode(encodedJwtToken);

	TokenAuthenticationConverter authenticationConverter = new TokenAuthenticationConverter(authoritiesExtractor);
	Authentication authentication = authenticationConverter.convert(jwtToken);

	SecurityContextHolder.createEmptyContext();
	SecurityContextHolder.getContext().setAuthentication(authentication);
}