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

The following examples show how to use org.springframework.security.oauth2.jwt.JwtDecoder. 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 File: FirebaseJwtTokenDecoder.java    From spring-cloud-gcp with 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
Source File: IapAuthenticationAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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
Source File: XsuaaResourceServerJwkAutoConfigurationTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@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 #4
Source File: IapAuthenticationAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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 #5
Source File: FirebaseAuthenticationAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "firebaseAuthenticationJwtDecoder")
public JwtDecoder firebaseAuthenticationJwtDecoder(
		DelegatingOAuth2TokenValidator<Jwt> firebaseJwtDelegatingValidator,
		FirebaseAuthenticationProperties properties) {
	return new FirebaseJwtTokenDecoder(restOperations(), properties.getPublicKeysEndpoint(),
			firebaseJwtDelegatingValidator);
}
 
Example #6
Source File: IapAuthenticationAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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 #7
Source File: XsuaaJwtDecoderTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@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 #8
Source File: XsuaaJwtDecoderTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: SpringSecurityContextTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: IapAuthenticationAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: XsuaaResourceServerJwkAutoConfigurationTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: XsuaaJwtDecoderBuilder.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #13
Source File: XsuaaResourceServerJwkAutoConfiguration.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: OidcUserManagementAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
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 #15
Source File: WebSecurityConfig.java    From platform with 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 #16
Source File: UndertowSpringSecurityAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@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 #17
Source File: SecurityConfig.java    From platform with Apache License 2.0 4 votes vote down vote up
@Bean
public JwtDecoder jwtDecoder(KeyPair keyPair) {
    return NimbusJwtDecoder.withPublicKey((RSAPublicKey) keyPair.getPublic()).build();
}
 
Example #18
Source File: IapAuthenticationAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public JwtDecoder jwtDecoder() {
	return (s) -> mockJwt;
}
 
Example #19
Source File: SecurityConfiguration.java    From grpc-spring-boot-starter with 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 #20
Source File: TestSecurityConfiguration.java    From jhipster-registry with Apache License 2.0 4 votes vote down vote up
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example #21
Source File: SecurityConfiguration.java    From grpc-spring-boot-starter with 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 #22
Source File: WebSecurityConfiguration.java    From spring-cloud-demo with Apache License 2.0 4 votes vote down vote up
@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
}
 
Example #23
Source File: XsuaaResourceServerJwkAutoConfigurationTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Bean
public JwtDecoder customJwtDecoder() {
	return NimbusJwtDecoder.withJwkSetUri("http://localhost:8080/uaa/oauth/token_keys").build();
}
 
Example #24
Source File: SecurityConfiguration.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Bean
public JwtDecoder xsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration) {
	return new XsuaaJwtDecoderBuilder(xsuaaServiceConfiguration).build();
}
 
Example #25
Source File: SecurityConfiguration.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Bean
public JwtDecoder xsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration) {
	return new XsuaaJwtDecoderBuilder(xsuaaServiceConfiguration).build();
}
 
Example #26
Source File: TestSecurityConfiguration.java    From java-microservices-examples with Apache License 2.0 4 votes vote down vote up
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example #27
Source File: TestSecurityConfiguration.java    From java-microservices-examples with Apache License 2.0 4 votes vote down vote up
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example #28
Source File: TestSecurityConfiguration.java    From java-microservices-examples with Apache License 2.0 4 votes vote down vote up
@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
Example #29
Source File: SpringSecurityContext.java    From cloud-security-xsuaa-integration with Apache License 2.0 3 votes vote down vote up
/**
 * 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);
}