Add authorization server sample

This commit is contained in:
Steve Riesenberg
2021-07-23 14:59:33 -05:00
committed by Steve Riesenberg
parent def1af3e75
commit 67f36c5862
13 changed files with 908 additions and 0 deletions

View File

@@ -0,0 +1,184 @@
/*
* Copyright 2021 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 example;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
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 {@link OAuth2AuthorizationServerApplication}.
*
* @author Steve Riesenberg
*/
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class OAuth2AuthorizationServerApplicationITests {
private static final String CLIENT_ID = "messaging-client";
private static final String CLIENT_SECRET = "secret";
private final ObjectMapper objectMapper = new ObjectMapper();
@Autowired
private MockMvc mockMvc;
@Test
void performTokenRequestWhenValidClientCredentialsThenOk() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/oauth2/token")
.param("grant_type", "client_credentials")
.param("scope", "message:read")
.with(basicAuth(CLIENT_ID, CLIENT_SECRET)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.access_token").isString())
.andExpect(jsonPath("$.expires_in").isNumber())
.andExpect(jsonPath("$.scope").value("message:read"))
.andExpect(jsonPath("$.token_type").value("Bearer"));
// @formatter:on
}
@Test
void performTokenRequestWhenMissingScopeThenOk() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/oauth2/token")
.param("grant_type", "client_credentials")
.with(basicAuth(CLIENT_ID, CLIENT_SECRET)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.access_token").isString())
.andExpect(jsonPath("$.expires_in").isNumber())
.andExpect(jsonPath("$.scope").value("message:read message:write"))
.andExpect(jsonPath("$.token_type").value("Bearer"));
// @formatter:on
}
@Test
void performTokenRequestWhenInvalidClientCredentialsThenUnauthorized() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/oauth2/token")
.param("grant_type", "client_credentials")
.param("scope", "message:read")
.with(basicAuth("bad", "password")))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("invalid_client"));
// @formatter:on
}
@Test
void performTokenRequestWhenMissingGrantTypeThenUnauthorized() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/oauth2/token")
.with(basicAuth("bad", "password")))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("invalid_client"));
// @formatter:on
}
@Test
void performIntrospectionRequestWhenValidTokenThenOk() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/oauth2/introspect")
.param("token", getAccessToken())
.with(basicAuth(CLIENT_ID, CLIENT_SECRET)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.active").value("true"))
.andExpect(jsonPath("$.aud[0]").value(CLIENT_ID))
.andExpect(jsonPath("$.client_id").value(CLIENT_ID))
.andExpect(jsonPath("$.exp").isNumber())
.andExpect(jsonPath("$.iat").isNumber())
.andExpect(jsonPath("$.iss").value("http://localhost:9000"))
.andExpect(jsonPath("$.jti").isString())
.andExpect(jsonPath("$.nbf").isNumber())
.andExpect(jsonPath("$.scope").value("message:read"))
.andExpect(jsonPath("$.sub").value(CLIENT_ID))
.andExpect(jsonPath("$.token_type").value("Bearer"));
// @formatter:on
}
@Test
void performIntrospectionRequestWhenInvalidCredentialsThenUnauthorized() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/oauth2/introspect")
.param("token", getAccessToken())
.with(basicAuth("bad", "password")))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("invalid_client"));
// @formatter:on
}
private String getAccessToken() throws Exception {
// @formatter:off
MvcResult mvcResult = this.mockMvc.perform(post("/oauth2/token")
.param("grant_type", "client_credentials")
.param("scope", "message:read")
.with(basicAuth(CLIENT_ID, CLIENT_SECRET)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.access_token").exists())
.andReturn();
// @formatter:on
String tokenResponseJson = mvcResult.getResponse().getContentAsString();
Map<String, Object> tokenResponse = this.objectMapper.readValue(tokenResponseJson, new TypeReference<>() {
});
return tokenResponse.get("access_token").toString();
}
private static BasicAuthenticationRequestPostProcessor basicAuth(String username, String password) {
return new BasicAuthenticationRequestPostProcessor(username, password);
}
private static final class BasicAuthenticationRequestPostProcessor implements RequestPostProcessor {
private final String username;
private final String password;
private BasicAuthenticationRequestPostProcessor(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(this.username, this.password);
request.addHeader("Authorization", headers.getFirst("Authorization"));
return request;
}
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2021 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 example;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;
import com.nimbusds.jose.jwk.RSAKey;
/**
* Utils for generating JWKs.
*
* @author Joe Grandja
*/
final class Jwks {
private Jwks() {
}
static RSAKey generateRsa() {
KeyPair keyPair = KeyGeneratorUtils.generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// @formatter:off
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
// @formatter:on
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2021 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 example;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
/**
* Utils for generating keys.
*
* @author Joe Grandja
*/
final class KeyGeneratorUtils {
private KeyGeneratorUtils() {
}
static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2021 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 example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* OAuth Authorization Server Application.
*
* @author Steve Riesenberg
*/
@SpringBootApplication
public class OAuth2AuthorizationServerApplication {
public static void main(String[] args) {
SpringApplication.run(OAuth2AuthorizationServerApplication.class, args);
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2021 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 example;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
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.config.ProviderSettings;
import org.springframework.security.web.SecurityFilterChain;
/**
* OAuth Authorization Server Configuration.
*
* @author Steve Riesenberg
*/
@EnableWebSecurity
public class OAuth2AuthorizationServerSecurityConfiguration {
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
// @formatter:off
http
.sessionManagement((sessionManagement) ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
// @formatter:on
return http.build();
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
// @formatter:off
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("messaging-client")
.clientSecret("{noop}secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.scope("message:read")
.scope("message:write")
.clientSettings((clientSettings) -> clientSettings.requireUserConsent(true))
.build();
// @formatter:on
return new InMemoryRegisteredClientRepository(registeredClient);
}
@Bean
public JWKSource<SecurityContext> jwkSource() {
RSAKey rsaKey = Jwks.generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return new ImmutableJWKSet<>(jwkSet);
}
@Bean
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
Set<JWSAlgorithm> jwsAlgs = new HashSet<>();
jwsAlgs.addAll(JWSAlgorithm.Family.RSA);
jwsAlgs.addAll(JWSAlgorithm.Family.EC);
jwsAlgs.addAll(JWSAlgorithm.Family.HMAC_SHA);
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
JWSKeySelector<SecurityContext> jwsKeySelector = new JWSVerificationKeySelector<>(jwsAlgs, jwkSource);
jwtProcessor.setJWSKeySelector(jwsKeySelector);
// Override the default Nimbus claims set verifier as NimbusJwtDecoder handles it
// instead
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
return new NimbusJwtDecoder(jwtProcessor);
}
@Bean
public ProviderSettings providerSettings() {
return new ProviderSettings().issuer("http://localhost:9000");
}
}

View File

@@ -0,0 +1,2 @@
server:
port: 9000