Revert "Temporarily remove authorization-server sample"

This reverts commit c68696343a.
This commit is contained in:
Marcus Da Coregio
2022-10-24 09:28:00 -03:00
parent 4638e1e428
commit dd8ecd241c
12 changed files with 844 additions and 0 deletions

View File

@@ -0,0 +1,195 @@
/*
* 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")
.param("scope", "message:read message:write")
.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 performTokenRequestWhenGrantTypeNotRegisteredThenBadRequest() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/oauth2/token")
.param("grant_type", "client_credentials")
.with(basicAuth("login-client", "openid-connect")))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error").value("unauthorized_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("$.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,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,166 @@
/*
* 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;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;
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.SecurityContext;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
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.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.ProviderSettings;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
/**
* OAuth Authorization Server Configuration.
*
* @author Steve Riesenberg
*/
@Configuration
@EnableWebSecurity
public class OAuth2AuthorizationServerSecurityConfiguration {
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
return http.formLogin(Customizer.withDefaults()).build();
}
@Bean
@Order(2)
public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults());
// @formatter:on
return http.build();
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
// @formatter:off
RegisteredClient loginClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("login-client")
.clientSecret("{noop}openid-connect")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/login-client")
.redirectUri("http://127.0.0.1:8080/authorized")
.scope(OidcScopes.OPENID)
.scope(OidcScopes.PROFILE)
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
.build();
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("messaging-client")
.clientSecret("{noop}secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.scope("message:read")
.scope("message:write")
.build();
// @formatter:on
return new InMemoryRegisteredClientRepository(loginClient, registeredClient);
}
@Bean
public JWKSource<SecurityContext> jwkSource(KeyPair keyPair) {
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// @formatter:off
RSAKey rsaKey = new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
// @formatter:on
JWKSet jwkSet = new JWKSet(rsaKey);
return new ImmutableJWKSet<>(jwkSet);
}
@Bean
public JwtDecoder jwtDecoder(KeyPair keyPair) {
return NimbusJwtDecoder.withPublicKey((RSAPublicKey) keyPair.getPublic()).build();
}
@Bean
public ProviderSettings providerSettings() {
return ProviderSettings.builder().issuer("http://localhost:9000").build();
}
@Bean
public UserDetailsService userDetailsService() {
// @formatter:off
UserDetails userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
// @formatter:on
return new InMemoryUserDetailsManager(userDetails);
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
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,2 @@
server:
port: 9000