Consolidate to one module

This commit is contained in:
Joe Grandja
2020-08-19 14:29:14 -04:00
parent 5ace411fc7
commit e16f15cce3
33 changed files with 5 additions and 74 deletions

View File

@@ -0,0 +1,211 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.config.test.SpringTestRule;
import org.springframework.security.crypto.keys.KeyManager;
import org.springframework.security.crypto.keys.StaticKeyGeneratingKeyManager;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationAttributeNames;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.TestOAuth2Authorizations;
import org.springframework.security.oauth2.server.authorization.TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients;
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration tests for the OAuth 2.0 Authorization Code Grant.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationCodeGrantTests {
private static RegisteredClientRepository registeredClientRepository;
private static OAuth2AuthorizationService authorizationService;
private static KeyManager keyManager;
@Rule
public final SpringTestRule spring = new SpringTestRule();
@Autowired
private MockMvc mvc;
@BeforeClass
public static void init() {
registeredClientRepository = mock(RegisteredClientRepository.class);
authorizationService = mock(OAuth2AuthorizationService.class);
keyManager = new StaticKeyGeneratingKeyManager();
}
@Before
public void setup() {
reset(registeredClientRepository);
reset(authorizationService);
}
@Test
public void requestWhenAuthorizationRequestNotAuthenticatedThenRedirectToLogin() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
MvcResult mvcResult = this.mvc.perform(MockMvcRequestBuilders.get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI)
.params(getAuthorizationRequestParameters(registeredClient)))
.andExpect(status().is3xxRedirection())
.andReturn();
assertThat(mvcResult.getResponse().getRedirectedUrl()).endsWith("/login");
verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId()));
verifyNoInteractions(authorizationService);
}
@Test
public void requestWhenAuthorizationRequestAuthenticatedThenRedirectToClient() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
MvcResult mvcResult = this.mvc.perform(get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI)
.params(getAuthorizationRequestParameters(registeredClient))
.with(user("user")))
.andExpect(status().is3xxRedirection())
.andReturn();
assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://example.com\\?code=.{15,}&state=state");
verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId()));
verify(authorizationService).save(any());
}
@Test
public void requestWhenTokenRequestValidThenResponseIncludesCacheHeaders() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(authorizationService.findByToken(
eq(authorization.getAttribute(OAuth2AuthorizationAttributeNames.CODE)),
eq(TokenType.AUTHORIZATION_CODE)))
.thenReturn(authorization);
this.mvc.perform(MockMvcRequestBuilders.post(OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI)
.params(getTokenRequestParameters(registeredClient, authorization))
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store")))
.andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache")));
verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId()));
verify(authorizationService).findByToken(
eq(authorization.getAttribute(OAuth2AuthorizationAttributeNames.CODE)),
eq(TokenType.AUTHORIZATION_CODE));
verify(authorizationService).save(any());
}
private static MultiValueMap<String, String> getAuthorizationRequestParameters(RegisteredClient registeredClient) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, OAuth2AuthorizationResponseType.CODE.getValue());
parameters.set(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId());
parameters.set(OAuth2ParameterNames.REDIRECT_URI, registeredClient.getRedirectUris().iterator().next());
parameters.set(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " "));
parameters.set(OAuth2ParameterNames.STATE, "state");
return parameters;
}
private static MultiValueMap<String, String> getTokenRequestParameters(RegisteredClient registeredClient,
OAuth2Authorization authorization) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue());
parameters.set(OAuth2ParameterNames.CODE, authorization.getAttribute(OAuth2AuthorizationAttributeNames.CODE));
parameters.set(OAuth2ParameterNames.REDIRECT_URI, registeredClient.getRedirectUris().iterator().next());
return parameters;
}
private static String encodeBasicAuth(String clientId, String secret) throws Exception {
clientId = URLEncoder.encode(clientId, StandardCharsets.UTF_8.name());
secret = URLEncoder.encode(secret, StandardCharsets.UTF_8.name());
String credentialsString = clientId + ":" + secret;
byte[] encodedBytes = Base64.getEncoder().encode(credentialsString.getBytes(StandardCharsets.UTF_8));
return new String(encodedBytes, StandardCharsets.UTF_8);
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfiguration {
@Bean
RegisteredClientRepository registeredClientRepository() {
return registeredClientRepository;
}
@Bean
OAuth2AuthorizationService authorizationService() {
return authorizationService;
}
@Bean
KeyManager keyManager() {
return keyManager;
}
}
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.config.test.SpringTestRule;
import org.springframework.security.crypto.keys.KeyManager;
import org.springframework.security.crypto.keys.StaticKeyGeneratingKeyManager;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration tests for the OAuth 2.0 Client Credentials Grant.
*
* @author Alexey Nesterov
*/
public class OAuth2ClientCredentialsGrantTests {
private static RegisteredClientRepository registeredClientRepository;
private static OAuth2AuthorizationService authorizationService;
private static KeyManager keyManager;
@Rule
public final SpringTestRule spring = new SpringTestRule();
@Autowired
private MockMvc mvc;
@BeforeClass
public static void init() {
registeredClientRepository = mock(RegisteredClientRepository.class);
authorizationService = mock(OAuth2AuthorizationService.class);
keyManager = new StaticKeyGeneratingKeyManager();
}
@Before
public void setup() {
reset(registeredClientRepository);
reset(authorizationService);
}
@Test
public void requestWhenTokenRequestNotAuthenticatedThenUnauthorized() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
this.mvc.perform(MockMvcRequestBuilders.post(OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI)
.param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()))
.andExpect(status().isUnauthorized());
verifyNoInteractions(registeredClientRepository);
verifyNoInteractions(authorizationService);
}
@Test
public void requestWhenTokenRequestValidThenTokenResponse() throws Exception {
this.spring.register(AuthorizationServerConfiguration.class).autowire();
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
this.mvc.perform(post(OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI)
.param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue())
.param(OAuth2ParameterNames.SCOPE, "scope1 scope2")
.header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(
registeredClient.getClientId(), registeredClient.getClientSecret())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.access_token").isNotEmpty())
.andExpect(jsonPath("$.scope").value("scope1 scope2"));
verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId()));
verify(authorizationService).save(any());
}
private static String encodeBasicAuth(String clientId, String secret) throws Exception {
clientId = URLEncoder.encode(clientId, StandardCharsets.UTF_8.name());
secret = URLEncoder.encode(secret, StandardCharsets.UTF_8.name());
String credentialsString = clientId + ":" + secret;
byte[] encodedBytes = Base64.getEncoder().encode(credentialsString.getBytes(StandardCharsets.UTF_8));
return new String(encodedBytes, StandardCharsets.UTF_8);
}
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
static class AuthorizationServerConfiguration {
@Bean
RegisteredClientRepository registeredClientRepository() {
return registeredClientRepository;
}
@Bean
OAuth2AuthorizationService authorizationService() {
return authorizationService;
}
@Bean
KeyManager keyManager() {
return keyManager;
}
}
}

View File

@@ -0,0 +1,153 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.test;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.util.InMemoryXmlWebApplicationContext;
import org.springframework.test.context.web.GenericXmlWebContextLoader;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.setup.MockMvcConfigurer;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.security.config.BeanIds.SPRING_SECURITY_FILTER_CHAIN;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
/**
* TODO
* This class is a straight copy from Spring Security.
* It should be removed when merging this codebase into Spring Security.
*
* @author Rob Winch
* @since 5.0
*/
public class SpringTestContext implements Closeable {
private Object test;
private ConfigurableWebApplicationContext context;
private List<Filter> filters = new ArrayList<>();
public void setTest(Object test) {
this.test = test;
}
@Override
public void close() {
try {
this.context.close();
} catch(Exception e) {}
}
public SpringTestContext context(ConfigurableWebApplicationContext context) {
this.context = context;
return this;
}
public SpringTestContext register(Class<?>... classes) {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(classes);
this.context = applicationContext;
return this;
}
public SpringTestContext testConfigLocations(String... configLocations) {
GenericXmlWebContextLoader loader = new GenericXmlWebContextLoader();
String[] locations = loader.processLocations(this.test.getClass(),
configLocations);
return configLocations(locations);
}
public SpringTestContext configLocations(String... configLocations) {
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocations(configLocations);
this.context = context;
return this;
}
public SpringTestContext context(String configuration) {
InMemoryXmlWebApplicationContext context = new InMemoryXmlWebApplicationContext(configuration);
this.context = context;
return this;
}
public SpringTestContext mockMvcAfterSpringSecurityOk() {
return addFilter(new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) {
response.setStatus(HttpServletResponse.SC_OK);
}
});
}
private SpringTestContext addFilter(Filter filter) {
this.filters.add(filter);
return this;
}
public ConfigurableWebApplicationContext getContext() {
if (!this.context.isRunning()) {
this.context.setServletContext(new MockServletContext());
this.context.setServletConfig(new MockServletConfig());
this.context.refresh();
}
return this.context;
}
public void autowire() {
this.context.setServletContext(new MockServletContext());
this.context.setServletConfig(new MockServletConfig());
this.context.refresh();
if (this.context.containsBean(SPRING_SECURITY_FILTER_CHAIN)) {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(springSecurity())
.apply(new AddFilter()).build();
this.context.getBeanFactory()
.registerResolvableDependency(MockMvc.class, mockMvc);
}
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(this.context.getBeanFactory());
bpp.processInjection(this.test);
}
private class AddFilter implements MockMvcConfigurer {
public RequestPostProcessor beforeMockMvcCreated(
ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) {
builder.addFilters(SpringTestContext.this.filters.toArray(new Filter[0]));
return null;
}
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.test;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.springframework.security.test.context.TestSecurityContextHolder;
/**
* TODO
* This class is a straight copy from Spring Security.
* It should be removed when merging this codebase into Spring Security.
*
* @author Rob Winch
* @since 5.0
*/
public class SpringTestRule extends SpringTestContext implements MethodRule {
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
return new Statement() {
public void evaluate() throws Throwable {
setTest(target);
try {
base.evaluate();
} finally {
TestSecurityContextHolder.clearContext();
close();
}
}
};
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2009-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.util;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.security.util.InMemoryResource;
/**
* TODO
* This class is a straight copy from Spring Security.
* It should be removed when merging this codebase into Spring Security.
*
* @author Luke Taylor
* @author Eddú Meléndez
*/
public class InMemoryXmlApplicationContext extends AbstractXmlApplicationContext {
static final String BEANS_OPENING = "<b:beans xmlns='http://www.springframework.org/schema/security'\n"
+ " xmlns:context='http://www.springframework.org/schema/context'\n"
+ " xmlns:b='http://www.springframework.org/schema/beans'\n"
+ " xmlns:aop='http://www.springframework.org/schema/aop'\n"
+ " xmlns:mvc='http://www.springframework.org/schema/mvc'\n"
+ " xmlns:websocket='http://www.springframework.org/schema/websocket'\n"
+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n"
+ " xsi:schemaLocation='http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-2.5.xsd\n"
+ "http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-2.5.xsd\n"
+ "http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd\n"
+ "http://www.springframework.org/schema/websocket https://www.springframework.org/schema/websocket/spring-websocket.xsd\n"
+ "http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-2.5.xsd\n"
+ "http://www.springframework.org/schema/security https://www.springframework.org/schema/security/spring-security-";
static final String BEANS_CLOSE = "</b:beans>\n";
static final String SPRING_SECURITY_VERSION = "5.4";
Resource inMemoryXml;
public InMemoryXmlApplicationContext(String xml) {
this(xml, SPRING_SECURITY_VERSION, null);
}
public InMemoryXmlApplicationContext(String xml, ApplicationContext parent) {
this(xml, SPRING_SECURITY_VERSION, parent);
}
public InMemoryXmlApplicationContext(String xml, String secVersion, ApplicationContext parent) {
String fullXml = BEANS_OPENING + secVersion + ".xsd'>\n" + xml + BEANS_CLOSE;
inMemoryXml = new InMemoryResource(fullXml);
setAllowBeanDefinitionOverriding(true);
setParent(parent);
refresh();
}
@Override
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory()) {
@Override
protected boolean allowAliasOverriding() {
return true;
}
};
}
protected Resource[] getConfigResources() {
return new Resource[] { inMemoryXml };
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.security.util.InMemoryResource;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_CLOSE;
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_OPENING;
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION;
/**
* TODO
* This class is a straight copy from Spring Security.
* It should be removed when merging this codebase into Spring Security.
*
* @author Joe Grandja
*/
public class InMemoryXmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
private Resource inMemoryXml;
public InMemoryXmlWebApplicationContext(String xml) {
this(xml, SPRING_SECURITY_VERSION, null);
}
public InMemoryXmlWebApplicationContext(String xml, ApplicationContext parent) {
this(xml, SPRING_SECURITY_VERSION, parent);
}
public InMemoryXmlWebApplicationContext(String xml, String secVersion, ApplicationContext parent) {
String fullXml = BEANS_OPENING + secVersion + ".xsd'>\n" + xml + BEANS_CLOSE;
inMemoryXml = new InMemoryResource(fullXml);
setAllowBeanDefinitionOverriding(true);
setParent(parent);
}
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
reader.loadBeanDefinitions(new Resource[] { inMemoryXml });
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keys;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.crypto.SecretKey;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.security.crypto.keys.KeyGeneratorUtils.generateRsaKey;
import static org.springframework.security.crypto.keys.KeyGeneratorUtils.generateSecretKey;
/**
* Tests for {@link ManagedKey}.
*
* @author Joe Grandja
*/
public class ManagedKeyTests {
private static SecretKey secretKey;
private static KeyPair rsaKeyPair;
@BeforeClass
public static void init() {
secretKey = generateSecretKey();
rsaKeyPair = generateRsaKey();
}
@Test
public void withSymmetricKeyWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ManagedKey.withSymmetricKey(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("secretKey cannot be null");
}
@Test
public void buildWhenKeyIdNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ManagedKey.withSymmetricKey(secretKey).build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("keyId cannot be empty");
}
@Test
public void buildWhenActivatedOnNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ManagedKey.withSymmetricKey(secretKey).keyId("keyId").build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("activatedOn cannot be null");
}
@Test
public void buildWhenSymmetricKeyAllAttributesProvidedThenAllAttributesAreSet() {
ManagedKey expectedManagedKey = TestManagedKeys.secretManagedKey().build();
ManagedKey managedKey = ManagedKey.withSymmetricKey(expectedManagedKey.getKey())
.keyId(expectedManagedKey.getKeyId())
.activatedOn(expectedManagedKey.getActivatedOn())
.build();
assertThat(managedKey.isSymmetric()).isTrue();
assertThat(managedKey.<Key>getKey()).isInstanceOf(SecretKey.class);
assertThat(managedKey.<SecretKey>getKey()).isEqualTo(expectedManagedKey.getKey());
assertThat(managedKey.getPublicKey()).isNull();
assertThat(managedKey.getKeyId()).isEqualTo(expectedManagedKey.getKeyId());
assertThat(managedKey.getActivatedOn()).isEqualTo(expectedManagedKey.getActivatedOn());
assertThat(managedKey.getDeactivatedOn()).isEqualTo(expectedManagedKey.getDeactivatedOn());
assertThat(managedKey.isActive()).isTrue();
assertThat(managedKey.getAlgorithm()).isEqualTo(expectedManagedKey.getAlgorithm());
}
@Test
public void withAsymmetricKeyWhenPublicKeyNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ManagedKey.withAsymmetricKey(null, rsaKeyPair.getPrivate()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("publicKey cannot be null");
}
@Test
public void withAsymmetricKeyWhenPrivateKeyNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ManagedKey.withAsymmetricKey(rsaKeyPair.getPublic(), null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("privateKey cannot be null");
}
@Test
public void buildWhenAsymmetricKeyAllAttributesProvidedThenAllAttributesAreSet() {
ManagedKey expectedManagedKey = TestManagedKeys.rsaManagedKey().build();
ManagedKey managedKey = ManagedKey.withAsymmetricKey(expectedManagedKey.getPublicKey(), expectedManagedKey.getKey())
.keyId(expectedManagedKey.getKeyId())
.activatedOn(expectedManagedKey.getActivatedOn())
.build();
assertThat(managedKey.isAsymmetric()).isTrue();
assertThat(managedKey.<Key>getKey()).isInstanceOf(PrivateKey.class);
assertThat(managedKey.<PrivateKey>getKey()).isEqualTo(expectedManagedKey.getKey());
assertThat(managedKey.getPublicKey()).isNotNull();
assertThat(managedKey.getKeyId()).isEqualTo(expectedManagedKey.getKeyId());
assertThat(managedKey.getActivatedOn()).isEqualTo(expectedManagedKey.getActivatedOn());
assertThat(managedKey.getDeactivatedOn()).isEqualTo(expectedManagedKey.getDeactivatedOn());
assertThat(managedKey.isActive()).isTrue();
assertThat(managedKey.getAlgorithm()).isEqualTo(expectedManagedKey.getAlgorithm());
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keys;
import java.security.KeyPair;
import java.time.Instant;
import java.util.UUID;
import static org.springframework.security.crypto.keys.KeyGeneratorUtils.generateEcKey;
import static org.springframework.security.crypto.keys.KeyGeneratorUtils.generateRsaKey;
import static org.springframework.security.crypto.keys.KeyGeneratorUtils.generateSecretKey;
/**
* @author Joe Grandja
*/
public class TestManagedKeys {
public static ManagedKey.Builder secretManagedKey() {
return ManagedKey.withSymmetricKey(generateSecretKey())
.keyId(UUID.randomUUID().toString())
.activatedOn(Instant.now());
}
public static ManagedKey.Builder rsaManagedKey() {
KeyPair rsaKeyPair = generateRsaKey();
return ManagedKey.withAsymmetricKey(rsaKeyPair.getPublic(), rsaKeyPair.getPrivate())
.keyId(UUID.randomUUID().toString())
.activatedOn(Instant.now());
}
public static ManagedKey.Builder ecManagedKey() {
KeyPair ecKeyPair = generateEcKey();
return ManagedKey.withAsymmetricKey(ecKeyPair.getPublic(), ecKeyPair.getPrivate())
.keyId(UUID.randomUUID().toString())
.activatedOn(Instant.now());
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.jose;
import org.junit.Test;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link JoseHeader}.
*
* @author Joe Grandja
*/
public class JoseHeaderTests {
@Test
public void withAlgorithmWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JoseHeader.withAlgorithm(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("jwsAlgorithm cannot be null");
}
@Test
public void buildWhenAllHeadersProvidedThenAllHeadersAreSet() {
JoseHeader expectedJoseHeader = TestJoseHeaders.joseHeader().build();
JoseHeader joseHeader = JoseHeader.withAlgorithm(expectedJoseHeader.getJwsAlgorithm())
.jwkSetUri(expectedJoseHeader.getJwkSetUri())
.jwk(expectedJoseHeader.getJwk())
.keyId(expectedJoseHeader.getKeyId())
.x509Uri(expectedJoseHeader.getX509Uri())
.x509CertificateChain(expectedJoseHeader.getX509CertificateChain())
.x509SHA1Thumbprint(expectedJoseHeader.getX509SHA1Thumbprint())
.x509SHA256Thumbprint(expectedJoseHeader.getX509SHA256Thumbprint())
.critical(expectedJoseHeader.getCritical())
.type(expectedJoseHeader.getType())
.contentType(expectedJoseHeader.getContentType())
.headers(headers -> headers.put("custom-header-name", "custom-header-value"))
.build();
assertThat(joseHeader.getJwsAlgorithm()).isEqualTo(expectedJoseHeader.getJwsAlgorithm());
assertThat(joseHeader.getJwkSetUri()).isEqualTo(expectedJoseHeader.getJwkSetUri());
assertThat(joseHeader.getJwk()).isEqualTo(expectedJoseHeader.getJwk());
assertThat(joseHeader.getKeyId()).isEqualTo(expectedJoseHeader.getKeyId());
assertThat(joseHeader.getX509Uri()).isEqualTo(expectedJoseHeader.getX509Uri());
assertThat(joseHeader.getX509CertificateChain()).isEqualTo(expectedJoseHeader.getX509CertificateChain());
assertThat(joseHeader.getX509SHA1Thumbprint()).isEqualTo(expectedJoseHeader.getX509SHA1Thumbprint());
assertThat(joseHeader.getX509SHA256Thumbprint()).isEqualTo(expectedJoseHeader.getX509SHA256Thumbprint());
assertThat(joseHeader.getCritical()).isEqualTo(expectedJoseHeader.getCritical());
assertThat(joseHeader.getType()).isEqualTo(expectedJoseHeader.getType());
assertThat(joseHeader.getContentType()).isEqualTo(expectedJoseHeader.getContentType());
assertThat(joseHeader.<String>getHeader("custom-header-name")).isEqualTo("custom-header-value");
assertThat(joseHeader.getHeaders()).isEqualTo(expectedJoseHeader.getHeaders());
}
@Test
public void fromWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JoseHeader.from(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("headers cannot be null");
}
@Test
public void fromWhenHeadersProvidedThenCopied() {
JoseHeader expectedJoseHeader = TestJoseHeaders.joseHeader().build();
JoseHeader joseHeader = JoseHeader.from(expectedJoseHeader).build();
assertThat(joseHeader.getHeaders()).isEqualTo(expectedJoseHeader.getHeaders());
}
@Test
public void headerWhenNameNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).header(null, "value"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("name cannot be empty");
}
@Test
public void headerWhenValueNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).header("name", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("value cannot be null");
}
@Test
public void getHeaderWhenNullThenThrowIllegalArgumentException() {
JoseHeader joseHeader = TestJoseHeaders.joseHeader().build();
assertThatThrownBy(() -> joseHeader.getHeader(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("name cannot be empty");
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.jose;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @author Joe Grandja
*/
public class TestJoseHeaders {
public static JoseHeader.Builder joseHeader() {
return joseHeader(SignatureAlgorithm.RS256);
}
public static JoseHeader.Builder joseHeader(SignatureAlgorithm signatureAlgorithm) {
return JoseHeader.withAlgorithm(signatureAlgorithm)
.jwkSetUri("https://provider.com/oauth2/jwks")
.jwk(rsaJwk())
.keyId(UUID.randomUUID().toString())
.x509Uri("https://provider.com/oauth2/x509")
.x509CertificateChain(Arrays.asList("x509Cert1", "x509Cert2"))
.x509SHA1Thumbprint("x509SHA1Thumbprint")
.x509SHA256Thumbprint("x509SHA256Thumbprint")
.critical(Collections.singleton("custom-header-name"))
.type("JWT")
.contentType("jwt-content-type")
.header("custom-header-name", "custom-header-value");
}
private static Map<String, Object> rsaJwk() {
Map<String, Object> rsaJwk = new HashMap<>();
rsaJwk.put("kty", "RSA");
rsaJwk.put("n", "modulus");
rsaJwk.put("e", "exponent");
return rsaJwk;
}
}

View File

@@ -0,0 +1,159 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.jose.jws;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.crypto.keys.KeyManager;
import org.springframework.security.crypto.keys.ManagedKey;
import org.springframework.security.crypto.keys.TestManagedKeys;
import org.springframework.security.oauth2.jose.JoseHeader;
import org.springframework.security.oauth2.jose.JoseHeaderNames;
import org.springframework.security.oauth2.jose.TestJoseHeaders;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncodingException;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.TestJwtClaimsSets;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for {@link NimbusJwsEncoder}.
*
* @author Joe Grandja
*/
public class NimbusJwsEncoderTests {
private KeyManager keyManager;
private NimbusJwsEncoder jwtEncoder;
@Before
public void setUp() {
this.keyManager = mock(KeyManager.class);
this.jwtEncoder = new NimbusJwsEncoder(this.keyManager);
}
@Test
public void constructorWhenKeyManagerNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new NimbusJwsEncoder(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("keyManager cannot be null");
}
@Test
public void encodeWhenHeadersNullThenThrowIllegalArgumentException() {
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatThrownBy(() -> this.jwtEncoder.encode(null, jwtClaimsSet))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("headers cannot be null");
}
@Test
public void encodeWhenClaimsNullThenThrowIllegalArgumentException() {
JoseHeader joseHeader = TestJoseHeaders.joseHeader().build();
assertThatThrownBy(() -> this.jwtEncoder.encode(joseHeader, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("claims cannot be null");
}
@Test
public void encodeWhenUnsupportedKeyThenThrowJwtEncodingException() {
JoseHeader joseHeader = TestJoseHeaders.joseHeader().build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatThrownBy(() -> this.jwtEncoder.encode(joseHeader, jwtClaimsSet))
.isInstanceOf(JwtEncodingException.class)
.hasMessageContaining("Unsupported key for algorithm 'RS256'");
}
@Test
public void encodeWhenUnsupportedKeyAlgorithmThenThrowJwtEncodingException() {
JoseHeader joseHeader = TestJoseHeaders.joseHeader(SignatureAlgorithm.ES256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatThrownBy(() -> this.jwtEncoder.encode(joseHeader, jwtClaimsSet))
.isInstanceOf(JwtEncodingException.class)
.hasMessageContaining("Unsupported key for algorithm 'ES256'");
}
@Test
public void encodeWhenUnsupportedKeyTypeThenThrowJwtEncodingException() {
ManagedKey managedKey = TestManagedKeys.ecManagedKey().build();
when(this.keyManager.findByAlgorithm(any())).thenReturn(Collections.singleton(managedKey));
JoseHeader joseHeader = TestJoseHeaders.joseHeader(SignatureAlgorithm.ES256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatThrownBy(() -> this.jwtEncoder.encode(joseHeader, jwtClaimsSet))
.isInstanceOf(JwtEncodingException.class)
.hasMessageContaining("Unsupported key type 'EC'");
}
@Test
public void encodeWhenSuccessThenDecodes() {
ManagedKey managedKey = TestManagedKeys.rsaManagedKey().build();
when(this.keyManager.findByAlgorithm(any())).thenReturn(Collections.singleton(managedKey));
JoseHeader joseHeader = TestJoseHeaders.joseHeader()
.headers(headers -> headers.remove(JoseHeaderNames.CRIT))
.build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
Jwt jws = this.jwtEncoder.encode(joseHeader, jwtClaimsSet);
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey((RSAPublicKey) managedKey.getPublicKey()).build();
jwtDecoder.decode(jws.getTokenValue());
}
@Test
public void encodeWhenMultipleActiveKeysThenUseMostRecent() {
ManagedKey managedKeyActivated2DaysAgo = TestManagedKeys.rsaManagedKey()
.activatedOn(Instant.now().minus(2, ChronoUnit.DAYS))
.build();
ManagedKey managedKeyActivated1DayAgo = TestManagedKeys.rsaManagedKey()
.activatedOn(Instant.now().minus(1, ChronoUnit.DAYS))
.build();
ManagedKey managedKeyActivatedToday = TestManagedKeys.rsaManagedKey()
.activatedOn(Instant.now())
.build();
when(this.keyManager.findByAlgorithm(any())).thenReturn(
Stream.of(managedKeyActivated2DaysAgo, managedKeyActivated1DayAgo, managedKeyActivatedToday)
.collect(Collectors.toSet()));
JoseHeader joseHeader = TestJoseHeaders.joseHeader()
.headers(headers -> headers.remove(JoseHeaderNames.CRIT))
.build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
Jwt jws = this.jwtEncoder.encode(joseHeader, jwtClaimsSet);
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey((RSAPublicKey) managedKeyActivatedToday.getPublicKey()).build();
jwtDecoder.decode(jws.getTokenValue());
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.jwt;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link JwtClaimsSet}.
*
* @author Joe Grandja
*/
public class JwtClaimsSetTests {
@Test
public void buildWhenClaimsEmptyThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JwtClaimsSet.withClaims().build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("claims cannot be empty");
}
@Test
public void buildWhenAllClaimsProvidedThenAllClaimsAreSet() {
JwtClaimsSet expectedJwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.withClaims()
.issuer(expectedJwtClaimsSet.getIssuer())
.subject(expectedJwtClaimsSet.getSubject())
.audience(expectedJwtClaimsSet.getAudience())
.issuedAt(expectedJwtClaimsSet.getIssuedAt())
.notBefore(expectedJwtClaimsSet.getNotBefore())
.expiresAt(expectedJwtClaimsSet.getExpiresAt())
.id(expectedJwtClaimsSet.getId())
.claims(claims -> claims.put("custom-claim-name", "custom-claim-value"))
.build();
assertThat(jwtClaimsSet.getIssuer()).isEqualTo(expectedJwtClaimsSet.getIssuer());
assertThat(jwtClaimsSet.getSubject()).isEqualTo(expectedJwtClaimsSet.getSubject());
assertThat(jwtClaimsSet.getAudience()).isEqualTo(expectedJwtClaimsSet.getAudience());
assertThat(jwtClaimsSet.getIssuedAt()).isEqualTo(expectedJwtClaimsSet.getIssuedAt());
assertThat(jwtClaimsSet.getNotBefore()).isEqualTo(expectedJwtClaimsSet.getNotBefore());
assertThat(jwtClaimsSet.getExpiresAt()).isEqualTo(expectedJwtClaimsSet.getExpiresAt());
assertThat(jwtClaimsSet.getId()).isEqualTo(expectedJwtClaimsSet.getId());
assertThat(jwtClaimsSet.<String>getClaim("custom-claim-name")).isEqualTo("custom-claim-value");
assertThat(jwtClaimsSet.getClaims()).isEqualTo(expectedJwtClaimsSet.getClaims());
}
@Test
public void fromWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JwtClaimsSet.from(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("claims cannot be null");
}
@Test
public void fromWhenClaimsProvidedThenCopied() {
JwtClaimsSet expectedJwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.from(expectedJwtClaimsSet).build();
assertThat(jwtClaimsSet.getClaims()).isEqualTo(expectedJwtClaimsSet.getClaims());
}
@Test
public void claimWhenNameNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JwtClaimsSet.withClaims().claim(null, "value"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("name cannot be empty");
}
@Test
public void claimWhenValueNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> JwtClaimsSet.withClaims().claim("name", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("value cannot be null");
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.jwt;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.UUID;
/**
* @author Joe Grandja
*/
public class TestJwtClaimsSets {
public static JwtClaimsSet.Builder jwtClaimsSet() {
URL issuer = null;
try {
issuer = URI.create("https://provider.com").toURL();
} catch (MalformedURLException e) { }
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plus(1, ChronoUnit.HOURS);
return JwtClaimsSet.withClaims()
.issuer(issuer)
.subject("subject")
.audience(Collections.singletonList("client-1"))
.issuedAt(issuedAt)
.notBefore(issuedAt)
.expiresAt(expiresAt)
.id(UUID.randomUUID().toString())
.claim("custom-claim-name", "custom-claim-value");
}
}