JAVA-1089: Move the OAuth related lesson code from

spring-boot-modules/spring-boot-security
This commit is contained in:
sampadawagde 2020-08-11 13:05:01 +05:30
parent ba7a7285fd
commit b09abfc0bf
9 changed files with 0 additions and 351 deletions

View File

@ -1,30 +0,0 @@
package com.baeldung.springbootsecurity.oauth2resource;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@EnableResourceServer
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2resource")
public class SpringBootOAuth2ResourceApplication {
public static void main(String[] args) {
new SpringApplicationBuilder()
.profiles("resource")
.sources(SpringBootOAuth2ResourceApplication.class)
.build()
.run(args);
}
@RestController
class SecuredResourceController {
@GetMapping("/securedResource")
public String securedResource() {
return "Baeldung Secured Resource OK";
}
}
}

View File

@ -1,47 +0,0 @@
package com.baeldung.springbootsecurity.oauth2server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
@EnableResourceServer
@EnableAuthorizationServer
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2server")
public class SpringBootAuthorizationServerApplication {
private static final Logger logger = LoggerFactory.getLogger(SpringBootAuthorizationServerApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringBootAuthorizationServerApplication.class, args);
}
@RestController
class UserController {
@GetMapping("/user")
public Principal user(Principal user) {
return user;
}
@GetMapping("/authentication")
public Object getAuthentication(@CurrentSecurityContext(expression = "authentication") Authentication authentication) {
logger.info("authentication -> {}", authentication);
return authentication.getDetails();
}
@GetMapping("/principal")
public String getPrincipal(@CurrentSecurityContext(expression = "authentication.principal") Principal principal) {
logger.info("principal -> {}", principal);
return principal.getName();
}
}
}

View File

@ -1,18 +0,0 @@
package com.baeldung.springbootsecurity.oauth2server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@Profile("authz")
public class AuthenticationMananagerConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}

View File

@ -1,46 +0,0 @@
package com.baeldung.springbootsecurity.oauth2server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
@Configuration
@Profile("authz")
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("baeldung")
.secret(passwordEncoder().encode("baeldung"))
.authorizedGrantTypes("client_credentials", "password", "authorization_code")
.scopes("openid", "read")
.autoApprove(true)
.and()
.withClient("baeldung-admin")
.secret(passwordEncoder().encode("baeldung"))
.authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token")
.scopes("read", "write")
.autoApprove(true);
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.springbootsecurity.oauth2server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@Profile("!authz")
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return authenticationManager();
}
}

View File

@ -1,19 +0,0 @@
package com.baeldung.springbootsecurity.oauth2sso;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.builder.SpringApplicationBuilder;
@EnableOAuth2Sso
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2sso")
public class SpringBootOAuth2SsoApplication {
public static void main(String[] args) {
new SpringApplicationBuilder()
.profiles("sso")
.sources(SpringBootOAuth2SsoApplication.class)
.build()
.run(args);
}
}

View File

@ -1,89 +0,0 @@
package com.baeldung.springbootsecurity.oauth2server;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import java.util.regex.Pattern;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class)
@ActiveProfiles("authz")
public class CustomConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport {
@LocalServerPort
private int port;
@Before
public void setUp() throws Exception {
base = new URL("http://localhost:" + port);
}
@Test
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
assertNotNull(accessToken);
}
@Test
public void givenOAuth2Context_whenAccessingAuthentication_ThenRespondTokenDetails() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
String authentication = executeGetRequest(restTemplate, "/authentication");
Pattern pattern = Pattern.compile("\\{\"remoteAddress\":\".*" +
"\",\"sessionId\":null,\"tokenValue\":\".*" +
"\",\"tokenType\":\"Bearer\",\"decodedDetails\":null}");
assertTrue("authentication", pattern.matcher(authentication).matches());
}
@Test
public void givenOAuth2Context_whenAccessingPrincipal_ThenRespondBaeldung() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
String principal = executeGetRequest(restTemplate, "/principal");
assertEquals("baeldung", principal);
}
@Test(expected = OAuth2AccessDeniedException.class)
public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
restTemplate.getAccessToken();
}
@Test
public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
assertNotNull(accessToken);
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.springbootsecurity.oauth2server;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.test.context.junit4.SpringRunner;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class,
properties = { "security.oauth2.client.client-id=client", "security.oauth2.client.client-secret=baeldung" })
public class DefaultConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport {
@Test
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("client", asList("read", "write"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
assertNotNull(accessToken);
}
}

View File

@ -1,53 +0,0 @@
package com.baeldung.springbootsecurity.oauth2server;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static org.springframework.http.HttpMethod.GET;
public class OAuth2IntegrationTestSupport {
public static final ResponseExtractor<String> EXTRACT_BODY_AS_STRING = clientHttpResponse ->
IOUtils.toString(clientHttpResponse.getBody(), Charset.defaultCharset());
private static final RequestCallback DO_NOTHING_CALLBACK = request -> {
};
@Value("${local.server.port}")
protected int port;
protected URL base;
protected ClientCredentialsResourceDetails getClientCredentialsResourceDetails(final String clientId, final List<String> scopes) {
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port));
resourceDetails.setClientId(clientId);
resourceDetails.setClientSecret("baeldung");
resourceDetails.setScope(scopes);
resourceDetails.setGrantType("client_credentials");
return resourceDetails;
}
protected OAuth2RestTemplate getOAuth2RestTemplate(final ClientCredentialsResourceDetails resourceDetails) {
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
restTemplate.setMessageConverters(singletonList(new MappingJackson2HttpMessageConverter()));
return restTemplate;
}
protected String executeGetRequest(OAuth2RestTemplate restTemplate, String path) {
return restTemplate.execute(base.toString() + path, GET, DO_NOTHING_CALLBACK, EXTRACT_BODY_AS_STRING);
}
}