Skip to content

Commit

Permalink
Fix JDBC samples to ensure DataSource is initialized
Browse files Browse the repository at this point in the history
Ideally Spring Boot would initialize the data source for us (see
spring-projects/spring-boot#1115), but we
can work around it with @dependsOn. The main new thing in this
approach though is to use a GlobalAuthenticationConfigurerAdapter
to configure the authentication manager (much better than using
a WebSecurityConfigurerAdapter)

Fixes spring-atticgh-222
  • Loading branch information
Dave Syer committed Jun 18, 2014
1 parent c439a43 commit 650c756
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.UserApprovalRequiredException;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
Expand Down Expand Up @@ -319,7 +318,7 @@ private ResponseEntity<String> attemptToGetConfirmationPage(String clientId, Str
private HttpHeaders getAuthenticatedHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
headers.set("Authorization", "Basic " + new String(Base64.encode("user:password".getBytes())));
headers.set("Authorization", getBasicAuthentication());
if (context.getRestTemplate() != null) {
context.getAccessTokenRequest().setHeaders(headers);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails;
Expand All @@ -22,7 +21,7 @@ public abstract class AbstractImplicitProviderTests extends AbstractIntegrationT
public void testPostForNonAutomaticApprovalToken() throws Exception {

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + new String(Base64.encode("user:password".getBytes())));
headers.set("Authorization", getBasicAuthentication());
context.getAccessTokenRequest().setHeaders(headers);
try {
assertNotNull(context.getAccessToken());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,20 @@
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.test.BeforeOAuth2Context;
import org.springframework.security.oauth2.client.test.OAuth2ContextSetup;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.client.token.grant.redirect.AbstractRedirectResourceDetails;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.InMemoryApprovalStore;
Expand Down Expand Up @@ -81,6 +84,9 @@ public int getPort() {
return container == null ? 8080 : container.getEmbeddedServletContainer().getPort();
}

@Autowired
protected SecurityProperties security;

@Autowired
private ServerProperties server;

Expand All @@ -96,6 +102,10 @@ public void fixPaths() {
if (resource instanceof ImplicitResourceDetails) {
resource.setAccessTokenUri(http.getUrl(authorizePath()));
}
if (resource instanceof ResourceOwnerPasswordResourceDetails) {
((ResourceOwnerPasswordResourceDetails) resource).setUsername(security.getUser().getName());
((ResourceOwnerPasswordResourceDetails) resource).setPassword(security.getUser().getPassword());
}
}

@After
Expand All @@ -104,6 +114,12 @@ public void init() throws Exception {
clear(approvalStore);
}

protected String getBasicAuthentication() {
return "Basic "
+ new String(Base64.encode((security.getUser().getName() + ":" + security.getUser().getPassword())
.getBytes()));
}

private void clear(ApprovalStore approvalStore) throws Exception {
if (approvalStore instanceof Advised) {
Advised advised = (Advised) tokenStore;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ private MultiValueMap<String, String> getTokenFormData(String scope, String clie
formData.add("client_id", clientId);
}
formData.add("scope", scope);
formData.add("username", "user");
formData.add("password", "password");
formData.add("username", security.getUser().getName());
formData.add("password", security.getUser().getPassword());
return formData;
}
}
49 changes: 29 additions & 20 deletions tests/annotation/jdbc/src/main/java/demo/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
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.configuration.EnableAuthorizationServer;
Expand All @@ -34,25 +35,11 @@
@RestController
public class Application {

@Order(Ordered.LOWEST_PRECEDENCE - 8)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Autowired
private SecurityProperties security;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
User user = security.getUser();
// @formatter:off
auth.jdbcAuthentication().dataSource(dataSource)
.withUser(user.getName())
.password(user.getPassword())
.roles(user.getRole().toArray(new String[0]));
// @formatter:on
}
@Bean
@DependsOn("dataSourceAutoConfigurationInitializer")
// @DependsOn only works if it is on a @Bean, so we can't use an @Import here
protected AuthenticationManagerConfiguration authenticationManagerConfiguration() {
return new AuthenticationManagerConfiguration();
}

public static void main(String[] args) {
Expand Down Expand Up @@ -139,3 +126,25 @@ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
}

}

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Autowired
private SecurityProperties security;

@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
User user = security.getUser();
// @formatter:off
auth.jdbcAuthentication().dataSource(dataSource)
.withUser(user.getName())
.password(user.getPassword())
.roles(user.getRole().toArray(new String[0]));
// @formatter:on
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.test.context.ActiveProfiles;
Expand All @@ -21,9 +24,13 @@ public class ApplicationTests {
@Autowired
private TokenStore tokenStore;

@Autowired
private ClientDetailsService clientDetailsService;

@Test
public void contextLoads() {
assertTrue("Wrong token store type: " + tokenStore, tokenStore instanceof JdbcTokenStore);
assertTrue("Wrong client details type: " + clientDetailsService, JdbcClientDetailsService.class.isAssignableFrom(AopUtils.getTargetClass(clientDetailsService)));
}

}
2 changes: 1 addition & 1 deletion tests/annotation/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.0.RELEASE</version>
<version>1.1.1.RELEASE</version>
</parent>

<dependencyManagement>
Expand Down
2 changes: 1 addition & 1 deletion tests/xml/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.0.RELEASE</version>
<version>1.1.1.RELEASE</version>
</parent>

<dependencyManagement>
Expand Down

0 comments on commit 650c756

Please sign in to comment.