-
Notifications
You must be signed in to change notification settings - Fork 824
/
LoginAuthenticationManager.java
183 lines (162 loc) · 7.88 KB
/
LoginAuthenticationManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/*******************************************************************************
* Cloud Foundry
* Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
*******************************************************************************/
package org.cloudfoundry.identity.uaa.authentication.manager;
import java.util.Date;
import java.util.Map;
import org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest;
import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication;
import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails;
import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal;
import org.cloudfoundry.identity.uaa.authentication.event.IdentityProviderAuthenticationSuccessEvent;
import org.cloudfoundry.identity.uaa.constants.OriginKeys;
import org.cloudfoundry.identity.uaa.user.UaaAuthority;
import org.cloudfoundry.identity.uaa.user.UaaUser;
import org.cloudfoundry.identity.uaa.user.UaaUserDatabase;
import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
public class LoginAuthenticationManager implements AuthenticationManager, ApplicationEventPublisherAware {
public static final String NotANumber = OriginKeys.NotANumber;
private final Log logger = LogFactory.getLog(getClass());
private ApplicationEventPublisher eventPublisher;
private UaaUserDatabase userDatabase;
private RandomValueStringGenerator generator = new RandomValueStringGenerator();
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
/**
* @param userDatabase the userDatabase to set
*/
public void setUserDatabase(UaaUserDatabase userDatabase) {
this.userDatabase = userDatabase;
}
@Override
public Authentication authenticate(Authentication request) throws AuthenticationException {
if (!(request instanceof AuthzAuthenticationRequest)) {
logger.debug("Cannot process request of type: " + request.getClass().getName());
return null;
}
AuthzAuthenticationRequest req = (AuthzAuthenticationRequest) request;
Map<String, String> info = req.getInfo();
logger.debug("Processing authentication request for " + req.getName());
SecurityContext context = SecurityContextHolder.getContext();
if (context.getAuthentication() instanceof OAuth2Authentication) {
OAuth2Authentication authentication = (OAuth2Authentication) context.getAuthentication();
if (authentication.isClientOnly()) {
UaaUser user = getUser(req, info);
UaaAuthenticationDetails authdetails = (UaaAuthenticationDetails) req.getDetails();
boolean addNewAccounts = authdetails != null && authdetails.isAddNew();
try {
if (NotANumber.equals(user.getId())) {
user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin());
} else {
//we should never add new accounts if we specify user_id
addNewAccounts = false;
user = userDatabase.retrieveUserById(user.getId());
}
} catch (UsernameNotFoundException e) {
// Not necessarily fatal
if (addNewAccounts) {
// Register new users automatically
publish(new NewUserAuthenticatedEvent(user));
try {
user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin());
} catch (UsernameNotFoundException ex) {
throw new BadCredentialsException("Bad credentials");
}
} else {
//if add_new=false then this is a bad user ID
throw new BadCredentialsException("Bad Credentials");
}
}
Authentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), authdetails);
publish(new IdentityProviderAuthenticationSuccessEvent(user, success));
return success;
}
}
logger.debug("Did not locate login credentials");
return null;
}
protected void publish(ApplicationEvent event) {
if (eventPublisher != null) {
eventPublisher.publishEvent(event);
}
}
protected UaaUser getUser(AuthzAuthenticationRequest req, Map<String, String> info) {
String name = req.getName();
String email = info.get("email");
String userId = info.get("user_id")!=null?info.get("user_id"):NotANumber;
if(info.get(OriginKeys.ORIGIN)!=null && info.get(OriginKeys.ORIGIN).equals(OriginKeys.UAA)){
throw new BadCredentialsException("uaa origin not allowed for external login server");
}
String origin = info.get(OriginKeys.ORIGIN)!=null?info.get(OriginKeys.ORIGIN): OriginKeys.LOGIN_SERVER;
if (name == null && email != null) {
name = email;
}
if (name == null && NotANumber.equals(userId)) {
throw new BadCredentialsException("Cannot determine username from credentials supplied");
} else if (name==null) {
//we have user_id, name is irrelevant
name="unknown";
}
if (email == null) {
if (name.contains("@")) {
if (name.split("@").length == 2 && !name.startsWith("@") && !name.endsWith("@")) {
email = name;
} else {
email = name.replaceAll("@", "") + "@unknown.org";
}
}
else {
email = name + "@unknown.org";
}
}
String givenName = info.get("given_name");
if (givenName == null) {
givenName = email.split("@")[0];
}
String familyName = info.get("family_name");
if (familyName == null) {
familyName = (email.split("@").length > 1 ? email.split("@")[1] : email);
}
return new UaaUser(
userId,
name,
"" /*zero length password for login server */,
email,
UaaAuthority.USER_AUTHORITIES,
givenName,
familyName,
new Date(),
new Date(),
origin,
name,
false,
IdentityZoneHolder.get().getId(),
null,
null);
}
}