Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

CFID-80: add Legacy* components for authentication with CF.com

Change-Id: I020059d7847633d01dcfeb6d7e4d766c2aa0c89f
  • Loading branch information...
commit 33131070c7066364e60538521bdc0864a2af2de0 1 parent 67aa3fb
Dave Syer authored January 01, 2012
7  README.md
Source Rendered
@@ -136,7 +136,12 @@ To launch in a microcloud type environment you need the SCIM user
136 136
 endpoints to be unsecure so that a user can create an account and set
137 137
 its password to bootstrap the system.  For this use the Spring profile
138 138
 `private`.  The opposite is `!private` which needs to be specified
139  
-excplicitly if the any other profiles are active.
  139
+explicitly if the any other profiles are active.
  140
+
  141
+To launch in legacy mode with the CF.com cloud controller as the
  142
+authentication and token source use profile `legacy`.  The opposite is
  143
+`!legacy` which needs to be specified explicitly if the any other
  144
+profiles are active.
140 145
 
141 146
 ## The API Application
142 147
 
3  samples/api/src/main/resources/log4j.properties
... ...
@@ -1,9 +1,10 @@
1 1
 log4j.rootCategory=INFO, CONSOLE
2 2
 
  3
+PID=????
3 4
 # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
4 5
 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
5 6
 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
6  
-log4j.appender.CONSOLE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %p [%c{1}] - %m%n
  7
+log4j.appender.CONSOLE.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss.SSS}] samples/api - ${PID} [%t] .... %5p --- %c{1}: %m%n
7 8
 
8 9
 log4j.category.org.springframework.security=DEBUG
9 10
 log4j.category.org.springframework.web=DEBUG
3  samples/app/src/main/resources/log4j.properties
... ...
@@ -1,9 +1,10 @@
1 1
 log4j.rootCategory=INFO, CONSOLE
2 2
 
  3
+PID=????
3 4
 # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
4 5
 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
5 6
 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
6  
-log4j.appender.CONSOLE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %p [%c{1}] - %m%n
  7
+log4j.appender.CONSOLE.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss.SSS}] samples/app - ${PID} [%t] .... %5p --- %c{1}: %m%n
7 8
 
8 9
 log4j.category.org.springframework.security=DEBUG
9 10
 log4j.category.org.springframework.web=DEBUG
139  uaa/src/main/java/org/cloudfoundry/identity/uaa/authentication/LegacyAuthenticationProvider.java
... ...
@@ -0,0 +1,139 @@
  1
+/*
  2
+ * Copyright 2002-2011 the original author or authors.
  3
+ *
  4
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5
+ * the License. You may obtain a copy of the License at
  6
+ *
  7
+ * http://www.apache.org/licenses/LICENSE-2.0
  8
+ *
  9
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11
+ * specific language governing permissions and limitations under the License.
  12
+ */
  13
+
  14
+package org.cloudfoundry.identity.uaa.authentication;
  15
+
  16
+import java.util.Arrays;
  17
+import java.util.Collections;
  18
+import java.util.HashMap;
  19
+import java.util.List;
  20
+import java.util.Map;
  21
+
  22
+import javax.servlet.http.HttpServletRequest;
  23
+
  24
+import org.cloudfoundry.identity.uaa.user.UaaUser;
  25
+import org.cloudfoundry.identity.uaa.user.UaaUserDatabase;
  26
+import org.springframework.context.support.MessageSourceAccessor;
  27
+import org.springframework.http.HttpEntity;
  28
+import org.springframework.http.HttpHeaders;
  29
+import org.springframework.http.MediaType;
  30
+import org.springframework.security.authentication.AuthenticationDetailsSource;
  31
+import org.springframework.security.authentication.AuthenticationProvider;
  32
+import org.springframework.security.authentication.BadCredentialsException;
  33
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  34
+import org.springframework.security.core.Authentication;
  35
+import org.springframework.security.core.AuthenticationException;
  36
+import org.springframework.security.core.SpringSecurityMessageSource;
  37
+import org.springframework.security.web.authentication.WebAuthenticationDetails;
  38
+import org.springframework.util.StringUtils;
  39
+import org.springframework.web.client.HttpClientErrorException;
  40
+import org.springframework.web.client.RestTemplate;
  41
+import org.springframework.web.util.WebUtils;
  42
+
  43
+/**
  44
+ * Provider which delegates authentication to an existing api for user accounts. By default the
  45
+ * {@link #setCloudControllerUrl(String) url} points to the cloud controller on cloudfoundry.com. The remote api is a
  46
+ * cloud controller, so it accpets <code>(email, password)</code> form inputs and returns a token as a JSON property
  47
+ * "token". The token is added to the successful {@link Authentication#getDetails() authentication details} as a map
  48
+ * entry (i.e. the details are a map).
  49
+ * 
  50
+ * @author Dave Syer
  51
+ */
  52
+public class LegacyAuthenticationProvider implements AuthenticationProvider,
  53
+		AuthenticationDetailsSource<HttpServletRequest, Map<String, String>> {
  54
+
  55
+	private String url = "http://api.cloudfoundry.com/users/{username}/tokens";
  56
+
  57
+	private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
  58
+
  59
+	private List<String> parameterKeys = Arrays.asList("email", "password");
  60
+
  61
+	private UaaUserDatabase userDatabase = new LegacyUaaUserDatabase();
  62
+
  63
+	public void setCloudControllerUrl(String url) {
  64
+		this.url = url;
  65
+	}
  66
+
  67
+	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  68
+
  69
+		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) authentication;
  70
+		String username = usernamePasswordAuthenticationToken.getName();
  71
+		String password = usernamePasswordAuthenticationToken.getCredentials().toString();
  72
+
  73
+		Map<String, String> details = extractDetails(usernamePasswordAuthenticationToken);
  74
+
  75
+		Map<String, String> result = doAuthentication(username, password);
  76
+		result.putAll(details);
  77
+
  78
+		UaaUser user = userDatabase.retrieveUserByName(username);
  79
+		Authentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), result);
  80
+
  81
+		return success;
  82
+
  83
+	}
  84
+
  85
+	public boolean supports(Class<?> authentication) {
  86
+		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
  87
+	}
  88
+
  89
+	private Map<String, String> doAuthentication(String username, String password) {
  90
+
  91
+		Map<String, String> body = new HashMap<String, String>();
  92
+		body.put("password", password);
  93
+
  94
+		HttpHeaders headers = new HttpHeaders();
  95
+		headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
  96
+		headers.setContentType(MediaType.APPLICATION_JSON);
  97
+
  98
+		@SuppressWarnings("rawtypes")
  99
+		HttpEntity<Map> request = new HttpEntity<Map>(body, headers);
  100
+
  101
+		Map<String, String> result;
  102
+		try {
  103
+			@SuppressWarnings("unchecked")
  104
+			Map<String, String> object = new RestTemplate().postForObject(url, request, Map.class, username);
  105
+			result = new HashMap<String, String>(object);
  106
+		}
  107
+		catch (HttpClientErrorException e) {
  108
+			throw new BadCredentialsException(messages.getMessage(
  109
+					"AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
  110
+		}
  111
+
  112
+		if (StringUtils.hasLength(result.get("token"))) {
  113
+			result.put("tokenized", "true");
  114
+		}
  115
+		return result;
  116
+	}
  117
+
  118
+	public Map<String, String> buildDetails(HttpServletRequest context) {
  119
+		WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetails(context);
  120
+		Map<String, String> map = new HashMap<String, String>();
  121
+		map.put("remote_addess", webAuthenticationDetails.getRemoteAddress());
  122
+		map.put("session_id", webAuthenticationDetails.getSessionId());
  123
+		@SuppressWarnings("unchecked")
  124
+		Map<String, String[]> parameterMap = context.getParameterMap();
  125
+		for (String key : parameterKeys) {
  126
+			if (parameterMap.containsKey(key)) {
  127
+				map.put(key, WebUtils.findParameterValue(parameterMap, key));
  128
+			}
  129
+		}
  130
+		return map;
  131
+	}
  132
+
  133
+	@SuppressWarnings("unchecked")
  134
+	private Map<String, String> extractDetails(Authentication authentication) {
  135
+		return authentication.getDetails() instanceof Map ? new HashMap<String, String>(
  136
+				(Map<String, String>) authentication.getDetails()) : new HashMap<String, String>();
  137
+	}
  138
+
  139
+}
66  uaa/src/main/java/org/cloudfoundry/identity/uaa/authentication/LegacyTokenServices.java
... ...
@@ -0,0 +1,66 @@
  1
+/*
  2
+ * Copyright 2006-2011 the original author or authors.
  3
+ * 
  4
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5
+ * the License. You may obtain a copy of the License at
  6
+ * 
  7
+ * http://www.apache.org/licenses/LICENSE-2.0
  8
+ * 
  9
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11
+ * specific language governing permissions and limitations under the License.
  12
+ */
  13
+package org.cloudfoundry.identity.uaa.authentication;
  14
+
  15
+import java.util.HashMap;
  16
+import java.util.Map;
  17
+
  18
+import org.springframework.security.core.Authentication;
  19
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
  20
+import org.springframework.security.oauth2.common.OAuth2RefreshToken;
  21
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
  22
+import org.springframework.security.oauth2.provider.token.RandomValueTokenServices;
  23
+
  24
+/**
  25
+ * OAuth2 token services for authorization and resource server. The token value has to be passed in as part of the
  26
+ * authentication details, so it is assumed to be populated during authentication somehow. The authentication details
  27
+ * should be a map with the token stored under key "token".
  28
+ * 
  29
+ * @author Dave Syer
  30
+ * 
  31
+ */
  32
+public class LegacyTokenServices extends RandomValueTokenServices {
  33
+
  34
+	@Override
  35
+	public void afterPropertiesSet() throws Exception {
  36
+		super.afterPropertiesSet();
  37
+		setSupportRefreshToken(false);
  38
+	}
  39
+
  40
+	@Override
  41
+	protected OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
  42
+
  43
+		OAuth2AccessToken accessToken = super.createAccessToken(authentication, refreshToken);
  44
+		if (authentication.getUserAuthentication() == null) {
  45
+			return accessToken;
  46
+		}
  47
+
  48
+		Map<String, String> details = extractDetails(authentication.getUserAuthentication());
  49
+		if (!details.containsKey("token")) {
  50
+			throw new IllegalStateException("Expected token to be part of authentication details");
  51
+		}
  52
+
  53
+		OAuth2AccessToken result = new OAuth2AccessToken(details.get("token"));
  54
+		result.setScope(accessToken.getScope());
  55
+		result.setExpiration(accessToken.getExpiration());
  56
+		return result;
  57
+
  58
+	}
  59
+
  60
+	@SuppressWarnings("unchecked")
  61
+	private Map<String, String> extractDetails(Authentication authentication) {
  62
+		return authentication.getDetails() instanceof Map ? new HashMap<String, String>(
  63
+				(Map<String, String>) authentication.getDetails()) : new HashMap<String, String>();
  64
+	}
  65
+
  66
+}
34  uaa/src/main/java/org/cloudfoundry/identity/uaa/authentication/LegacyUaaUserDatabase.java
... ...
@@ -0,0 +1,34 @@
  1
+/*
  2
+ * Copyright 2006-2011 the original author or authors.
  3
+ * 
  4
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5
+ * the License. You may obtain a copy of the License at
  6
+ * 
  7
+ * http://www.apache.org/licenses/LICENSE-2.0
  8
+ * 
  9
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11
+ * specific language governing permissions and limitations under the License.
  12
+ */
  13
+package org.cloudfoundry.identity.uaa.authentication;
  14
+
  15
+import org.cloudfoundry.identity.uaa.user.UaaUser;
  16
+import org.cloudfoundry.identity.uaa.user.UaaUserDatabase;
  17
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
  18
+
  19
+/**
  20
+ * Really simple {@link UaaUserDatabase} that doesn't use any backend store. All users retrieved have the same name
  21
+ * ("Legacy User") and differ only in their username. Used in conjuction with other legacy components to allow delegated
  22
+ * authentication (i.e. this app doesn't do authentication, it just trusts a remote source).
  23
+ * 
  24
+ * @author Dave Syer
  25
+ * 
  26
+ */
  27
+public class LegacyUaaUserDatabase implements UaaUserDatabase {
  28
+
  29
+	@Override
  30
+	public UaaUser retrieveUserByName(String username) throws UsernameNotFoundException {
  31
+		return new UaaUser(username, "", username, "Legacy", "User");
  32
+	}
  33
+
  34
+}
1  uaa/src/main/java/org/cloudfoundry/identity/uaa/authentication/UaaPrincipal.java
@@ -33,4 +33,5 @@ public String getName() {
33 33
 	public String getEmail() {
34 34
 		return email;
35 35
 	}
  36
+
36 37
 }
10  uaa/src/main/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpoint.java
@@ -38,10 +38,18 @@ public void afterPropertiesSet() throws Exception {
38 38
 	@ResponseBody
39 39
 	public Map<String, String> loginInfo(Principal principal) {
40 40
 		OAuth2Authentication authentication = (OAuth2Authentication) principal;
41  
-		UaaPrincipal uaaPrincipal = (UaaPrincipal) authentication.getUserAuthentication().getPrincipal();
  41
+		UaaPrincipal uaaPrincipal = extractUaaPrincipal(authentication);
42 42
 		return getResponse(uaaPrincipal);
43 43
 	}
44 44
 
  45
+	protected UaaPrincipal extractUaaPrincipal(OAuth2Authentication authentication) {
  46
+		Object object = authentication.getUserAuthentication().getPrincipal();
  47
+		if (object instanceof UaaPrincipal) {
  48
+			return (UaaPrincipal) object;
  49
+		}
  50
+		throw new IllegalStateException("User authentication could not be converted to UaaPrincipal");
  51
+	}
  52
+
45 53
 	protected Map<String, String> getResponse(UaaPrincipal principal) {
46 54
 		UaaUser user = userDatabase.retrieveUserByName(principal.getName());
47 55
 		Map<String, String> response = new LinkedHashMap<String, String>() {
36  uaa/src/main/resources/users.ldif
... ...
@@ -1,36 +0,0 @@
1  
-dn: ou=groups,dc=springframework,dc=org
2  
-objectclass: top
3  
-objectclass: organizationalUnit
4  
-ou: groups
5  
-
6  
-dn: ou=people,dc=springframework,dc=org
7  
-objectclass: top
8  
-objectclass: organizationalUnit
9  
-ou: people
10  
-
11  
-dn: uid=marissa,ou=people,dc=springframework,dc=org
12  
-objectclass: top
13  
-objectclass: person
14  
-objectclass: organizationalPerson
15  
-objectclass: inetOrgPerson
16  
-cn: Marissa
17  
-sn: Marissa
18  
-uid: marissa
19  
-userPassword: koala
20  
-
21  
-dn: uid=paul,ou=people,dc=springframework,dc=org
22  
-objectclass: top
23  
-objectclass: person
24  
-objectclass: organizationalPerson
25  
-objectclass: inetOrgPerson
26  
-cn: Paul
27  
-sn: Paul
28  
-uid: paul
29  
-userPassword: emu
30  
-
31  
-dn: cn=user,ou=groups,dc=springframework,dc=org
32  
-objectclass: top
33  
-objectclass: groupOfNames
34  
-cn: user
35  
-member: uid=marissa,ou=people,dc=springframework,dc=org
36  
-member: uid=paul,ou=people,dc=springframework,dc=org
43  uaa/src/main/webapp/WEB-INF/spring-servlet.xml
@@ -103,15 +103,6 @@
103 103
 
104 104
 	<authentication-manager id="emptyAuthenticationMgr" xmlns="http://www.springframework.org/schema/security" />
105 105
 
106  
-	<bean id="authzAuthenticationMgr" class="org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationManager">
107  
-		<constructor-arg ref="userDatabase" />
108  
-	</bean>
109  
-
110  
-	<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.RandomValueTokenServices">
111  
-		<property name="tokenStore" ref="tokenStore" />
112  
-		<property name="supportRefreshToken" value="true" />
113  
-	</bean>
114  
-
115 106
 	<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />
116 107
 
117 108
 	<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
@@ -127,8 +118,8 @@
127 118
 	</oauth:authorization-server>
128 119
 
129 120
 	<oauth:client-details-service id="clientDetails">
130  
-		<oauth:client client-id="varz" authorized-grant-types="client_credentials" scope="varz"
131  
-			authorities="ROLE_CLIENT" secret="varzclientsecret" />
  121
+		<oauth:client client-id="varz" authorized-grant-types="client_credentials" scope="varz" authorities="ROLE_CLIENT"
  122
+			secret="varzclientsecret" />
132 123
 		<oauth:client client-id="app" authorized-grant-types="password,authorization_code,refresh_token" scope="read,openid"
133 124
 			authorities="ROLE_GUEST" secret="appclientsecret" />
134 125
 		<oauth:client client-id="my" authorized-grant-types="authorization_code,refresh_token,implicit,client_credentials"
@@ -254,4 +245,34 @@
254 245
 
255 246
 	</beans>
256 247
 
  248
+	<beans profile="default,!legacy">
  249
+
  250
+		<bean id="authzAuthenticationMgr" class="org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationManager">
  251
+			<constructor-arg ref="userDatabase" />
  252
+		</bean>
  253
+
  254
+		<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.RandomValueTokenServices">
  255
+			<property name="tokenStore" ref="tokenStore" />
  256
+			<property name="supportRefreshToken" value="true" />
  257
+		</bean>
  258
+
  259
+	</beans>
  260
+
  261
+	<beans profile="legacy">
  262
+
  263
+		<bean id="userDatabase" class="org.cloudfoundry.identity.uaa.authentication.LegacyUaaUserDatabase"/>
  264
+
  265
+		<authentication-manager id="authzAuthenticationMgr" xmlns="http://www.springframework.org/schema/security">
  266
+			<authentication-provider ref="legacyAuthenticationProvider" />
  267
+		</authentication-manager>
  268
+
  269
+		<bean id="legacyAuthenticationProvider" class="org.cloudfoundry.identity.uaa.authentication.LegacyAuthenticationProvider" />
  270
+
  271
+		<bean id="tokenServices" class="org.cloudfoundry.identity.uaa.authentication.LegacyTokenServices">
  272
+			<property name="tokenStore" ref="tokenStore" />
  273
+			<property name="supportRefreshToken" value="false" />
  274
+		</bean>
  275
+
  276
+	</beans>
  277
+
257 278
 </beans>
8  uaa/src/test/java/org/cloudfoundry/identity/uaa/BootstrapTests.java
@@ -48,7 +48,7 @@ public void cleanup() {
48 48
 
49 49
 	@Test
50 50
 	public void testRootContextWithJdbcUsers() throws Exception {
51  
-		System.setProperty("spring.profiles.active", "jdbc,hsqldb");
  51
+		System.setProperty("spring.profiles.active", "jdbc,hsqldb,!legacy");
52 52
 		context = new GenericXmlApplicationContext(new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
53 53
 		assertNotNull(context.getBean("userDatabase", JdbcUaaUserDatabase.class));
54 54
 	}
@@ -61,7 +61,7 @@ public void testRootContextWithDevUsers() throws Exception {
61 61
 
62 62
 	@Test
63 63
 	public void testRootContextWithJdbcSecureUsers() throws Exception {
64  
-		System.setProperty("spring.profiles.active", "jdbc,hsqldb,!private");
  64
+		System.setProperty("spring.profiles.active", "jdbc,hsqldb,!private,!legacy");
65 65
 		context = new GenericXmlApplicationContext(new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
66 66
 		assertNotNull(context.getBean("userDatabase", JdbcUaaUserDatabase.class));
67 67
 		FilterChainProxy filterChain = context.getBean(FilterChainProxy.class);
@@ -72,7 +72,7 @@ public void testRootContextWithJdbcSecureUsers() throws Exception {
72 72
 
73 73
 	@Test
74 74
 	public void testRootContextWithJdbcUnsecureUsers() throws Exception {
75  
-		System.setProperty("spring.profiles.active", "jdbc,hsqldb,private");
  75
+		System.setProperty("spring.profiles.active", "jdbc,hsqldb,private,!legacy");
76 76
 		context = new GenericXmlApplicationContext(new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
77 77
 		assertNotNull(context.getBean("userDatabase", JdbcUaaUserDatabase.class));
78 78
 		FilterChainProxy filterChain = context.getBean(FilterChainProxy.class);
@@ -84,7 +84,7 @@ public void testRootContextWithJdbcUnsecureUsers() throws Exception {
84 84
 	@Test
85 85
 	public void testOverrideYmlConfig() throws Exception {
86 86
 		System.setProperty("CLOUD_FOUNDRY_CONFIG_PATH", "src/test/resources/test/config");
87  
-		System.setProperty("spring.profiles.active", "jdbc,hsqldb");
  87
+		System.setProperty("spring.profiles.active", "jdbc,hsqldb,legacy");
88 88
 		context = new GenericXmlApplicationContext(new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
89 89
 		Properties properties = context.getBean("applicationProperties", Properties.class);
90 90
 		assertEquals("bar", properties.get("foo"));
94  uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/LegacyAuthenticationProviderTests.java
... ...
@@ -0,0 +1,94 @@
  1
+/*
  2
+ * Copyright 2006-2011 the original author or authors.
  3
+ * 
  4
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5
+ * the License. You may obtain a copy of the License at
  6
+ * 
  7
+ * http://www.apache.org/licenses/LICENSE-2.0
  8
+ * 
  9
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11
+ * specific language governing permissions and limitations under the License.
  12
+ */
  13
+package org.cloudfoundry.identity.uaa.authentication;
  14
+
  15
+import static org.junit.Assert.assertEquals;
  16
+import static org.junit.Assert.assertFalse;
  17
+import static org.junit.Assert.assertNotNull;
  18
+import static org.junit.Assert.assertTrue;
  19
+
  20
+import java.io.IOException;
  21
+import java.io.OutputStream;
  22
+import java.util.Collections;
  23
+import java.util.Map;
  24
+
  25
+import org.junit.AfterClass;
  26
+import org.junit.BeforeClass;
  27
+import org.junit.Test;
  28
+import org.springframework.mock.web.MockHttpServletRequest;
  29
+import org.springframework.remoting.support.SimpleHttpServerFactoryBean;
  30
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  31
+import org.springframework.security.core.Authentication;
  32
+
  33
+import com.sun.net.httpserver.HttpExchange;
  34
+import com.sun.net.httpserver.HttpHandler;
  35
+
  36
+/**
  37
+ * @author Dave Syer
  38
+ *
  39
+ */
  40
+@SuppressWarnings("restriction")
  41
+public class LegacyAuthenticationProviderTests {
  42
+	
  43
+	private LegacyAuthenticationProvider authenticationProvider = new LegacyAuthenticationProvider();
  44
+	private static SimpleHttpServerFactoryBean factory;
  45
+	
  46
+	@BeforeClass
  47
+	public static void setup() throws Exception {
  48
+		factory = new SimpleHttpServerFactoryBean();
  49
+		factory.setPort(8888);
  50
+		factory.setContexts(Collections.singletonMap("/token", (HttpHandler) new HttpHandler() {
  51
+			@Override
  52
+			public void handle(HttpExchange exchange) throws IOException {
  53
+				exchange.getResponseHeaders().set("Content-Type", "application/json");
  54
+				exchange.sendResponseHeaders(200, 0);
  55
+				OutputStream stream = exchange.getResponseBody();
  56
+				stream.write("{\"token\":\"FOO\"}".getBytes());
  57
+				stream.flush();
  58
+			}		
  59
+		}));
  60
+		factory.afterPropertiesSet();
  61
+	}
  62
+	
  63
+	@AfterClass
  64
+	public static void close() throws Exception {
  65
+		factory.destroy();
  66
+	}
  67
+
  68
+	@Test
  69
+	public void testAuthenticate() {
  70
+		authenticationProvider.setCloudControllerUrl("http://localhost:8888/token");
  71
+		Authentication result = authenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("foo@bar.com", ""));
  72
+		assertNotNull(result);
  73
+		@SuppressWarnings("unchecked")
  74
+		Map<String,String> details = (Map<String,String>)result.getDetails();
  75
+		assertEquals("FOO", details.get("token"));
  76
+	}
  77
+	
  78
+	@Test
  79
+	public void testBuildDetails() throws Exception {
  80
+		MockHttpServletRequest request = new MockHttpServletRequest();
  81
+		request.addParameter("email", "foo@bar.com");
  82
+		request.addParameter("password", "secret");
  83
+		Map<String, String> details = authenticationProvider.buildDetails(request);
  84
+		assertNotNull(details);
  85
+		assertEquals("foo@bar.com", details.get("email"));
  86
+	}
  87
+	
  88
+	@Test
  89
+	public void testSupports() throws Exception {
  90
+		assertTrue(authenticationProvider.supports(UsernamePasswordAuthenticationToken.class));
  91
+		assertFalse(authenticationProvider.supports(UaaAuthentication.class));
  92
+	}
  93
+
  94
+}
53  uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/LegacyTokenServicesTests.java
... ...
@@ -0,0 +1,53 @@
  1
+/*
  2
+ * Copyright 2006-2011 the original author or authors.
  3
+ * 
  4
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5
+ * the License. You may obtain a copy of the License at
  6
+ * 
  7
+ * http://www.apache.org/licenses/LICENSE-2.0
  8
+ * 
  9
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11
+ * specific language governing permissions and limitations under the License.
  12
+ */
  13
+package org.cloudfoundry.identity.uaa.authentication;
  14
+
  15
+import static org.junit.Assert.assertEquals;
  16
+
  17
+import java.util.Arrays;
  18
+import java.util.HashMap;
  19
+import java.util.Map;
  20
+
  21
+import org.junit.Test;
  22
+import org.springframework.security.core.GrantedAuthority;
  23
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
  24
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
  25
+import org.springframework.security.oauth2.provider.ClientToken;
  26
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
  27
+import org.springframework.security.oauth2.provider.token.InMemoryTokenStore;
  28
+
  29
+/**
  30
+ * @author Dave Syer
  31
+ *
  32
+ */
  33
+public class LegacyTokenServicesTests {
  34
+	
  35
+	private LegacyTokenServices tokenServices = new LegacyTokenServices();
  36
+	private UaaAuthentication userAuthentication;
  37
+	private Map<String,String> details = new HashMap<String, String>();
  38
+	
  39
+	{
  40
+		tokenServices.setTokenStore(new InMemoryTokenStore());
  41
+		userAuthentication = new UaaAuthentication(UaaTestFactory.getPrincipal("NaN", "foo@bar.com", "foo@bar.com"),
  42
+				Arrays.<GrantedAuthority> asList(new SimpleGrantedAuthority("ROLE_USER")), details );
  43
+	}
  44
+
  45
+	@Test
  46
+	public void testCreateAccessToken() {
  47
+		details.put("token", "FOO");
  48
+		OAuth2Authentication authentication = new OAuth2Authentication(new ClientToken("foo", "bar", null), userAuthentication);
  49
+		OAuth2AccessToken token = tokenServices.createAccessToken(authentication , null);
  50
+		assertEquals("FOO", token.getValue());
  51
+	}
  52
+
  53
+}
32  uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/LegacyUaaUserDatabaseTests.java
... ...
@@ -0,0 +1,32 @@
  1
+/*
  2
+ * Copyright 2006-2011 the original author or authors.
  3
+ * 
  4
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5
+ * the License. You may obtain a copy of the License at
  6
+ * 
  7
+ * http://www.apache.org/licenses/LICENSE-2.0
  8
+ * 
  9
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11
+ * specific language governing permissions and limitations under the License.
  12
+ */
  13
+package org.cloudfoundry.identity.uaa.authentication;
  14
+
  15
+import static org.junit.Assert.assertNotNull;
  16
+
  17
+import org.cloudfoundry.identity.uaa.user.UaaUser;
  18
+import org.junit.Test;
  19
+
  20
+/**
  21
+ * @author Dave Syer
  22
+ *
  23
+ */
  24
+public class LegacyUaaUserDatabaseTests {
  25
+
  26
+	@Test
  27
+	public void testRetrieveUserByName() {
  28
+		UaaUser user = new LegacyUaaUserDatabase().retrieveUserByName("foo@bar.com");
  29
+		assertNotNull(user);
  30
+	}
  31
+
  32
+}

Git Notes

review

Verified+1: cftestbuild <cftestbuild@gmail.com>
Code-Review+2: Dave Syer <dsyer@vmware.com>
Submitted-by: Dave Syer <dsyer@vmware.com>
Submitted-at: Tue, 03 Jan 2012 13:49:48 +0000
Reviewed-on: http://cloudfoundry-codereview.qa.mozycloud.com/gerrit/2648
Project: uaa
Branch: refs/heads/master

0 notes on commit 3313107

Please sign in to comment.
Something went wrong with that request. Please try again.