This repository has been archived by the owner on Apr 15, 2019. It is now read-only.
forked from gwallet/keycloak-sms-authenticator
/
KeycloakSmsAuthenticator.java
239 lines (197 loc) · 10.6 KB
/
KeycloakSmsAuthenticator.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
package six.six.keycloak.authenticator;
import org.jboss.logging.Logger;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.Authenticator;
import org.keycloak.credential.CredentialModel;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.AuthenticatorConfigModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import six.six.keycloak.KeycloakSmsConstants;
import six.six.keycloak.requiredaction.action.required.KeycloakSmsMobilenumberRequiredAction;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.List;
/**
* Created by joris on 11/11/2016.
*/
public class KeycloakSmsAuthenticator implements Authenticator {
private static Logger logger = Logger.getLogger(KeycloakSmsAuthenticator.class);
public static final String CREDENTIAL_TYPE = "sms_validation";
private enum CODE_STATUS {
VALID,
INVALID,
EXPIRED
}
private boolean isOnlyForVerificationMode(boolean onlyForVerification,String mobileNumber,String mobileNumberVerified){
return (mobileNumber ==null || onlyForVerification==true && !mobileNumber.equals(mobileNumberVerified) );
}
private String getMobileNumber(UserModel user){
List<String> mobileNumberCreds = user.getAttribute(KeycloakSmsConstants.ATTR_MOBILE);
String mobileNumber = null;
if (mobileNumberCreds != null && !mobileNumberCreds.isEmpty()) {
mobileNumber = mobileNumberCreds.get(0);
}
return mobileNumber;
}
private String getMobileNumberVerified(UserModel user){
List<String> mobileNumberVerifieds = user.getAttribute(KeycloakSmsConstants.ATTR_MOBILE_VERIFIED);
String mobileNumberVerified = null;
if (mobileNumberVerifieds != null && !mobileNumberVerifieds.isEmpty()) {
mobileNumberVerified = mobileNumberVerifieds.get(0);
}
return mobileNumberVerified;
}
@Override
public void authenticate(AuthenticationFlowContext context) {
logger.debug("authenticate called ... context = " + context);
UserModel user = context.getUser();
AuthenticatorConfigModel config = context.getAuthenticatorConfig();
boolean onlyForVerification=KeycloakSmsAuthenticatorUtil.getConfigBoolean(config, KeycloakSmsConstants.MOBILE_VERIFICATION_ENABLED);
String mobileNumber =getMobileNumber(user);
String mobileNumberVerified = getMobileNumberVerified(user);
if (onlyForVerification==false || isOnlyForVerificationMode(onlyForVerification, mobileNumber,mobileNumberVerified)){
if (mobileNumber != null) {
// The mobile number is configured --> send an SMS
long nrOfDigits = KeycloakSmsAuthenticatorUtil.getConfigLong(config, KeycloakSmsConstants.CONF_PRP_SMS_CODE_LENGTH, 8L);
logger.debug("Using nrOfDigits " + nrOfDigits);
long ttl = KeycloakSmsAuthenticatorUtil.getConfigLong(config, KeycloakSmsConstants.CONF_PRP_SMS_CODE_TTL, 10 * 60L); // 10 minutes in s
logger.debug("Using ttl " + ttl + " (s)");
String code = KeycloakSmsAuthenticatorUtil.getSmsCode(nrOfDigits);
storeSMSCode(context, code, new Date().getTime() + (ttl * 1000)); // s --> ms
if (KeycloakSmsAuthenticatorUtil.sendSmsCode(mobileNumber, code, context)) {
Response challenge = context.form().createForm("sms-validation.ftl");
context.challenge(challenge);
} else {
Response challenge = context.form()
.setError("sms-auth.not.send")
.createForm("sms-validation-error.ftl");
context.failureChallenge(AuthenticationFlowError.INTERNAL_ERROR, challenge);
}
} else {
boolean isAskingFor=KeycloakSmsAuthenticatorUtil.getConfigBoolean(config, KeycloakSmsConstants.MOBILE_ASKFOR_ENABLED);
if(isAskingFor){
//Enable access and ask for mobilenumber
user.addRequiredAction(KeycloakSmsMobilenumberRequiredAction.PROVIDER_ID);
context.success();
}else {
// The mobile number is NOT configured --> complain
Response challenge = context.form()
.setError("sms-auth.not.mobile")
.createForm("sms-validation-error.ftl");
context.failureChallenge(AuthenticationFlowError.CLIENT_CREDENTIALS_SETUP_REQUIRED, challenge);
}
}
}else{
logger.debug("Skip SMS code because onlyForVerification " + onlyForVerification + " or mobileNumber==mobileNumberVerified");
context.success();
}
}
@Override
public void action(AuthenticationFlowContext context) {
logger.debug("action called ... context = " + context);
CODE_STATUS status = validateCode(context);
Response challenge = null;
switch (status) {
case EXPIRED:
challenge = context.form()
.setError("sms-auth.code.expired")
.createForm("sms-validation.ftl");
context.failureChallenge(AuthenticationFlowError.EXPIRED_CODE, challenge);
break;
case INVALID:
if (context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.OPTIONAL ||
context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.ALTERNATIVE) {
logger.debug("Calling context.attempted()");
context.attempted();
} else if (context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.REQUIRED) {
challenge = context.form()
.setError("sms-auth.code.invalid")
.createForm("sms-validation.ftl");
context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge);
} else {
// Something strange happened
logger.warn("Undefined execution ...");
}
break;
case VALID:
context.success();
updateVerifiedMobilenumber(context);
break;
}
}
/**
* If necessary update verified mobilenumber
* @param context
*/
private void updateVerifiedMobilenumber(AuthenticationFlowContext context){
AuthenticatorConfigModel config = context.getAuthenticatorConfig();
UserModel user = context.getUser();
boolean onlyForVerification=KeycloakSmsAuthenticatorUtil.getConfigBoolean(config, KeycloakSmsConstants.MOBILE_VERIFICATION_ENABLED);
if(onlyForVerification){
//Only verification mode
List<String> mobileNumberCreds = user.getAttribute(KeycloakSmsConstants.ATTR_MOBILE);
if (mobileNumberCreds != null && !mobileNumberCreds.isEmpty()) {
user.setAttribute(KeycloakSmsConstants.ATTR_MOBILE_VERIFIED,mobileNumberCreds);
}
}
}
// Store the code + expiration time in a UserCredential. Keycloak will persist these in the DB.
// When the code is validated on another node (in a clustered environment) the other nodes have access to it's values too.
private void storeSMSCode(AuthenticationFlowContext context, String code, Long expiringAt) {
UserCredentialModel credentials = new UserCredentialModel();
credentials.setType(KeycloakSmsConstants.USR_CRED_MDL_SMS_CODE);
credentials.setValue(code);
context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), credentials);
credentials.setType(KeycloakSmsConstants.USR_CRED_MDL_SMS_EXP_TIME);
credentials.setValue((expiringAt).toString());
context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), credentials);
}
protected CODE_STATUS validateCode(AuthenticationFlowContext context) {
CODE_STATUS result = CODE_STATUS.INVALID;
logger.debug("validateCode called ... ");
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
String enteredCode = formData.getFirst(KeycloakSmsConstants.ANSW_SMS_CODE);
KeycloakSession session = context.getSession();
List codeCreds = session.userCredentialManager().getStoredCredentialsByType(context.getRealm(), context.getUser(), KeycloakSmsConstants.USR_CRED_MDL_SMS_CODE);
/*List timeCreds = session.userCredentialManager().getStoredCredentialsByType(context.getRealm(), context.getUser(), KeycloakSmsAuthenticatorConstants.USR_CRED_MDL_SMS_EXP_TIME);*/
CredentialModel expectedCode = (CredentialModel) codeCreds.get(0);
/*CredentialModel expTimeString = (CredentialModel) timeCreds.get(0);*/
logger.debug("Expected code = " + expectedCode + " entered code = " + enteredCode);
if (expectedCode != null) {
result = enteredCode.equals(expectedCode.getValue()) ? CODE_STATUS.VALID : CODE_STATUS.INVALID;
/*long now = new Date().getTime();
logger.debug("Valid code expires in " + (Long.parseLong(expTimeString.getValue()) - now) + " ms");
if (result == CODE_STATUS.VALID) {
if (Long.parseLong(expTimeString.getValue()) < now) {
logger.debug("Code is expired !!");
result = CODE_STATUS.EXPIRED;
}
}*/
}
logger.debug("result : " + result);
return result;
}
@Override
public boolean requiresUser() {
logger.debug("requiresUser called ... returning true");
return true;
}
@Override
public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
logger.debug("configuredFor called ... session=" + session + ", realm=" + realm + ", user=" + user);
return true;
}
@Override
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
logger.debug("setRequiredActions called ... session=" + session + ", realm=" + realm + ", user=" + user);
}
@Override
public void close() {
logger.debug("close called ...");
}
}