org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication#org.springframework.security.oauth2.jwt.JwtDecoder源码实例Demo

下面列出了org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication#org.springframework.security.oauth2.jwt.JwtDecoder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


@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);
}
 

@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);
			});
}
 

@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;
}
 

@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();
}
 

/**
 * 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;
}
 

@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));
	});
}
 

@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())));
			});
}
 

@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());
}
 

@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");
}
 

@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");
}
 

@Bean
@ConditionalOnMissingBean(name = "firebaseAuthenticationJwtDecoder")
public JwtDecoder firebaseAuthenticationJwtDecoder(
		DelegatingOAuth2TokenValidator<Jwt> firebaseJwtDelegatingValidator,
		FirebaseAuthenticationProperties properties) {
	return new FirebaseJwtTokenDecoder(restOperations(), properties.getPublicKeysEndpoint(),
			firebaseJwtDelegatingValidator);
}
 

@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;
}
 

@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));
}
 

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();
}
 

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);
    }
}
 
源代码16 项目: platform   文件: WebSecurityConfig.java

@Autowired
public WebSecurityConfig(PasswordEncoder passwordEncoder,
                         JwtDecoder jwtDecoder,
                         SecurityUserDetailsService userDetailsService) {
    this.passwordEncoder = passwordEncoder;
    this.jwtDecoder = jwtDecoder;
    this.userDetailsService = userDetailsService;
}
 

@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 

@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 

@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 

@Bean
public JwtDecoder xsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration) {
	return new XsuaaJwtDecoderBuilder(xsuaaServiceConfiguration).build();
}
 

@Bean
public JwtDecoder xsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration) {
	return new XsuaaJwtDecoderBuilder(xsuaaServiceConfiguration).build();
}
 

@Bean
public JwtDecoder customJwtDecoder() {
	return NimbusJwtDecoder.withJwkSetUri("http://localhost:8080/uaa/oauth/token_keys").build();
}
 

@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
}
 

@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();
}
 

@Bean
public JwtDecoder jwtDecoder() {
	return (s) -> mockJwt;
}
 

@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();
}
 

@Bean
JwtDecoder jwtDecoder() {
    return mock(JwtDecoder.class);
}
 
源代码28 项目: platform   文件: SecurityConfig.java

@Bean
public JwtDecoder jwtDecoder(KeyPair keyPair) {
    return NimbusJwtDecoder.withPublicKey((RSAPublicKey) keyPair.getPublic()).build();
}
 

/**
 * 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);
}