-
Notifications
You must be signed in to change notification settings - Fork 160
/
UserPassAuthenticatingRealm.java
239 lines (210 loc) · 10.2 KB
/
UserPassAuthenticatingRealm.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*******************************************************************************
* Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.service.authentication.shiro.realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials;
import org.eclipse.kapua.service.authentication.credential.Credential;
import org.eclipse.kapua.service.authentication.credential.CredentialListResult;
import org.eclipse.kapua.service.authentication.credential.CredentialService;
import org.eclipse.kapua.service.authentication.credential.CredentialType;
import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService;
import org.eclipse.kapua.service.authentication.shiro.UsernamePasswordCredentialsImpl;
import org.eclipse.kapua.service.user.User;
import org.eclipse.kapua.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* {@link UsernamePasswordCredentials} based {@link AuthenticatingRealm} implementation.
*
* @since 1.0.0
*/
public class UserPassAuthenticatingRealm extends KapuaAuthenticatingRealm {
private static final Logger LOG = LoggerFactory.getLogger(UserPassAuthenticatingRealm.class);
private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
/**
* Realm name.
*/
public static final String REALM_NAME = "userPassAuthenticatingRealm";
/**
* Constructor.
*
* @since 1.0.0
*/
public UserPassAuthenticatingRealm() {
setName(REALM_NAME);
CredentialsMatcher credentialsMather = new UserPassCredentialsMatcher();
setCredentialsMatcher(credentialsMather);
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
//
// Extract credentials
UsernamePasswordCredentialsImpl token = (UsernamePasswordCredentialsImpl) authenticationToken;
String tokenUsername = token.getUsername();
//
// Get Services
UserService userService;
CredentialService credentialService;
try {
userService = LOCATOR.getService(UserService.class);
credentialService = LOCATOR.getService(CredentialService.class);
} catch (KapuaRuntimeException kre) {
throw new ShiroException("Unexpected error while loading KapuaServices!", kre);
}
//
// Get the associated user by name
final User user;
try {
user = KapuaSecurityUtils.doPrivileged(() -> userService.findByName(tokenUsername));
} catch (AuthenticationException ae) {
throw ae;
} catch (Exception e) {
throw new ShiroException("Unexpected error while looking for the user!", e);
}
//
// Check user
checkUser(user);
//
// Check account
Account account = checkAccount(user.getScopeId());
//
// Find credentials
// FIXME: manage multiple credentials and multiple credentials type
Credential credential;
try {
credential = KapuaSecurityUtils.doPrivileged(() -> {
CredentialListResult userCredentialList = credentialService.findByUserId(user.getScopeId(), user.getId());
List<Credential> passwordCredentialList = userCredentialList.getItems(c -> CredentialType.PASSWORD.equals(c.getCredentialType()));
return passwordCredentialList.isEmpty() ? null : passwordCredentialList.get(0);
});
} catch (AuthenticationException ae) {
throw ae;
} catch (Exception e) {
throw new ShiroException("Unexpected error while looking for the credentials!", e);
}
//
// Check credential
checkCredential(credential);
//
// Get CredentialService config
Map<String, Object> credentialServiceConfig = getCredentialServiceConfig(credential.getScopeId());
//
// Check credential lockout
checkCredentialLockout(credential, credentialServiceConfig);
//
// BuildAuthenticationInfo
return new LoginAuthenticationInfo(getName(),
account,
user,
credential,
credentialServiceConfig);
}
@Override
protected void assertCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info)
throws AuthenticationException {
LoginAuthenticationInfo kapuaInfo = (LoginAuthenticationInfo) info;
CredentialService credentialService = LOCATOR.getService(CredentialService.class);
MfaOptionService mfaOptionService = LOCATOR.getService(MfaOptionService.class);
KapuaId userId = kapuaInfo.getUser().getId();
KapuaId scopeId = kapuaInfo.getUser().getScopeId();
boolean hasMfa = false;
boolean checkedUsernameAndPasswordMatch = false;
boolean userPasswordMatch = true;
try {
if (KapuaSecurityUtils.doPrivileged(() -> mfaOptionService.findByUserId(scopeId, userId) != null)) {
hasMfa = true;
}
} catch (KapuaException e) {
LOG.warn("Unexpected error while looking for the User. Error: {}", e.getMessage());
throw new ShiroException("Unexpected error while looking for the user!", e);
}
try {
if (hasMfa) {
super.assertCredentialsMatch(authcToken, info);
} else {
userPasswordMatch = ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info);
checkedUsernameAndPasswordMatch = true;
if (!userPasswordMatch) {
String msg = "Submitted credentials for token [" + authcToken + "] did not match the expected credentials.";
throw new IncorrectCredentialsException(msg);
}
}
} catch (AuthenticationException authenticationEx) {
try {
Credential failedCredential = (Credential) kapuaInfo.getCredentials();
userPasswordMatch = checkedUsernameAndPasswordMatch ?
userPasswordMatch : ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info);
final boolean hasMfaAndUserPasswordMatch = hasMfa && userPasswordMatch;
KapuaSecurityUtils.doPrivileged(() -> {
Map<String, Object> credentialServiceConfig = kapuaInfo.getCredentialServiceConfig();
boolean lockoutPolicyEnabled = (boolean) credentialServiceConfig.get("lockoutPolicy.enabled");
if (lockoutPolicyEnabled) {
Date now = new Date();
int resetAfterSeconds = (int) credentialServiceConfig.get("lockoutPolicy.resetAfter");
Date firstLoginFailure;
boolean resetAttempts = failedCredential.getFirstLoginFailure() == null ||
now.after(failedCredential.getLoginFailuresReset()) ||
hasMfaAndUserPasswordMatch;
if (resetAttempts) {
firstLoginFailure = now;
failedCredential.setLoginFailures(1);
} else {
firstLoginFailure = failedCredential.getFirstLoginFailure();
failedCredential.setLoginFailures(failedCredential.getLoginFailures() + 1);
}
Date loginFailureWindowExpiration = new Date(firstLoginFailure.getTime() + (resetAfterSeconds * 1000L));
failedCredential.setFirstLoginFailure(firstLoginFailure);
failedCredential.setLoginFailuresReset(loginFailureWindowExpiration);
int maxLoginFailures = (int) credentialServiceConfig.get("lockoutPolicy.maxFailures");
if (failedCredential.getLoginFailures() >= maxLoginFailures) {
long lockoutDuration = (int) credentialServiceConfig.get("lockoutPolicy.lockDuration");
Date resetDate = new Date(now.getTime() + (lockoutDuration * 1000));
failedCredential.setLockoutReset(resetDate);
}
}
credentialService.update(failedCredential);
});
} catch (KapuaException kex) {
throw new ShiroException("Unexpected error while updating the lockout policy", kex);
}
throw authenticationEx;
}
//
// Reset Credential lockout policy after successful login
resetCredentialLockout((Credential) kapuaInfo.getCredentials());
//
// Populate Session with info
populateSession(SecurityUtils.getSubject(), kapuaInfo);
}
@Override
public boolean supports(AuthenticationToken authenticationToken) {
return authenticationToken instanceof UsernamePasswordCredentialsImpl;
}
}