Skip to content

Commit

Permalink
Add sample app for JAXB configuration (XML tokens)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dave Syer committed Nov 19, 2014
1 parent fbb13cd commit ce2bc89
Show file tree
Hide file tree
Showing 13 changed files with 552 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@

package sparklr.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.sql.DataSource;

import org.junit.After;
Expand All @@ -26,6 +31,8 @@
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
Expand Down Expand Up @@ -55,7 +62,7 @@ public abstract class AbstractIntegrationTests {
private static String globalCheckTokenPath;

private static String globalAuthorizePath;

@Value("${local.server.port}")
private int port;

Expand All @@ -82,9 +89,9 @@ public abstract class AbstractIntegrationTests {

@Autowired
private ServerProperties server;

@Before
public void init() {
public void init() {
String prefix = server.getServletPrefix();
http.setPort(port);
http.setPrefix(prefix);
Expand All @@ -96,6 +103,10 @@ public void fixPaths() {
http.setPort(port);
http.setPrefix(prefix);
BaseOAuth2ProtectedResourceDetails resource = (BaseOAuth2ProtectedResourceDetails) context.getResource();
List<HttpMessageConverter<?>> converters = new ArrayList<>(context.getRestTemplate().getMessageConverters());
converters.addAll(getAdditionalConverters());
context.getRestTemplate().setMessageConverters(converters);
context.getRestTemplate().setInterceptors(getInterceptors());
resource.setAccessTokenUri(http.getUrl(tokenPath()));
if (resource instanceof AbstractRedirectResourceDetails) {
((AbstractRedirectResourceDetails) resource).setUserAuthorizationUri(http.getUrl(authorizePath()));
Expand All @@ -109,16 +120,24 @@ public void fixPaths() {
}
}

protected List<ClientHttpRequestInterceptor> getInterceptors() {
return Collections.emptyList();
}

protected Collection<? extends HttpMessageConverter<?>> getAdditionalConverters() {
return Collections.emptySet();
}

protected String getPassword() {
return security.getUser().getPassword();
}

protected String getUsername() {
return security.getUser().getName();
}

public interface DoNotOverride {

}

@After
Expand All @@ -128,9 +147,7 @@ public void close() throws Exception {
}

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

private void clear(ApprovalStore approvalStore) throws Exception {
Expand Down
9 changes: 9 additions & 0 deletions tests/annotation/jaxb/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
This project shows what you can do with the minimum configuration to
set up an Authorization Server and Resource Server with XML serialization
of access tokens and error responses.

You need to teach Spring how to serialize `OAuth2AccessTokens` and
`OAuth2Exceptions` using the converters provided in Spring OAuth. The
steps to do this can be seen in the server (`Application` configuration)
and also in the client (where we inject `HttpMessageConverters` into the
`RestTemplate` used to access resources in the integration tests).
50 changes: 50 additions & 0 deletions tests/annotation/jaxb/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>jaxb</artifactId>

<name>jaxb</name>
<description>Demo project</description>

<parent>
<groupId>org.demo</groupId>
<artifactId>spring-oauth2-tests-parent</artifactId>
<version>2.0.5.BUILD-SNAPSHOT</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.demo</groupId>
<artifactId>spring-oauth2-tests-common</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
119 changes: 119 additions & 0 deletions tests/annotation/jaxb/src/main/java/demo/Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package demo;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.authentication.AuthenticationManager;
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;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.http.converter.jaxb.JaxbOAuth2AccessTokenMessageConverter;
import org.springframework.security.oauth2.http.converter.jaxb.JaxbOAuth2ExceptionMessageConverter;
import org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.error.OAuth2ExceptionRenderer;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableResourceServer
@RestController
public class Application extends WebMvcConfigurerAdapter {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@RequestMapping("/")
public String home() {
return "Hello World";
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new JaxbOAuth2AccessTokenMessageConverter());
converters.add(new JaxbOAuth2ExceptionMessageConverter());
}

@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.authenticationEntryPoint(authenticationEntryPoint()).accessDeniedHandler(accessDeniedHandler());
}

private AccessDeniedHandler accessDeniedHandler() {
OAuth2AccessDeniedHandler accessDeniedHandler = new OAuth2AccessDeniedHandler();
accessDeniedHandler.setExceptionRenderer(exceptionRenderer());
return accessDeniedHandler;
}

private AuthenticationEntryPoint authenticationEntryPoint() {
OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
authenticationEntryPoint.setExceptionRenderer(exceptionRenderer());
return authenticationEntryPoint;
}

private OAuth2ExceptionRenderer exceptionRenderer() {
DefaultOAuth2ExceptionRenderer exceptionRenderer = new DefaultOAuth2ExceptionRenderer();
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(new JaxbOAuth2ExceptionMessageConverter());
exceptionRenderer.setMessageConverters(converters);
return exceptionRenderer;
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.resourceIds("oauth2-resource")
.accessTokenValiditySeconds(60)
.and()
.withClient("my-client-with-registered-redirect")
.authorizedGrantTypes("authorization_code")
.authorities("ROLE_CLIENT")
.scopes("read", "trust")
.resourceIds("oauth2-resource")
.redirectUris("http://anywhere?key=value")
.and()
.withClient("my-client-with-secret")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT")
.scopes("read")
.resourceIds("oauth2-resource")
.secret("secret");
// @formatter:on
}

}

}
8 changes: 8 additions & 0 deletions tests/annotation/jaxb/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
spring:
application:
name: vanilla
management:
context_path: /admin
security:
user:
password: password
20 changes: 20 additions & 0 deletions tests/annotation/jaxb/src/test/java/demo/ApplicationTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port=0")
public class ApplicationTests {

@Test
public void contextLoads() {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright 2006-2011 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
*
* http://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 demo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.Collection;

import org.junit.Test;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;

import sparklr.common.AbstractAuthorizationCodeProviderTests;

/**
* @author Dave Syer
*/
@SpringApplicationConfiguration(classes = Application.class)
public class AuthorizationCodeProviderTests extends AbstractAuthorizationCodeProviderTests {

@Test
public void testWrongClientIdProvided() throws Exception {
ResponseEntity<String> response = attemptToGetConfirmationPage("no-such-client", "http://anywhere");
// With no client id you get an InvalidClientException on the server which is forwarded to /oauth/error
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
String body = response.getBody();
assertTrue("Wrong body: " + body, body.contains("<html"));
assertTrue("Wrong body: " + body, body.contains("Bad client credentials"));
}

@Test
public void testWrongClientIdAndOmittedResponseType() throws Exception {
// Test wrong client id together with an omitted response_type
ResponseEntity<String> response = attemptToGetConfirmationPage("no-such-client", "http://anywhere", null);
// With bad client id you get an InvalidClientException on the server which is forwarded to /oauth/error
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
String body = response.getBody();
assertTrue("Wrong body: " + body, body.contains("<html"));
assertTrue("Wrong body: " + body, body.contains("Bad client credentials"));
}

@Test
public void testWrongClientIdAndBadResponseTypeProvided() throws Exception {
// Test wrong client id together with an omitted response_type
ResponseEntity<String> response = attemptToGetConfirmationPage("no-such-client", "http://anywhere", "unsupported");
// With bad client id you get an InvalidClientException on the server which is forwarded to /oauth/error
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
String body = response.getBody();
assertTrue("Wrong body: " + body, body.contains("<html"));
assertTrue("Wrong body: " + body, body.contains("Bad client credentials"));
}

@Override
protected Collection<? extends HttpMessageConverter<?>> getAdditionalConverters() {
return Converters.getJaxbConverters();
}

}
Loading

0 comments on commit ce2bc89

Please sign in to comment.