Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,17 @@ public void doGet(HttpServletRequest originalRequest, HttpServletResponse respon
session.setAttribute(Constants.DISPLAY_SCOPES,
Boolean.parseBoolean(getServletContext().getInitParameter(Constants.DISPLAY_SCOPES)));

// Store userId in session for OTP verification (extracted from consent retrieval response)
// The userId (SCIM ID) is now added to the response JSON by ConsentAuthorizeEndpoint
if (dataSet.has(Constants.USER_ID)) {
String userId = dataSet.getString(Constants.USER_ID);
session.setAttribute(Constants.USER_ID, userId);
log.debug("Stored userId in session: " + userId);
} else {
log.warn("userId not found in consent data response");
}
Comment on lines +144 to +152
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 1

Suggested change
// Store userId in session for OTP verification (extracted from consent retrieval response)
// The userId (SCIM ID) is now added to the response JSON by ConsentAuthorizeEndpoint
if (dataSet.has(Constants.USER_ID)) {
String userId = dataSet.getString(Constants.USER_ID);
session.setAttribute(Constants.USER_ID, userId);
log.debug("Stored userId in session: " + userId);
} else {
log.warn("userId not found in consent data response");
}
// The userId (SCIM ID) is now added to the response JSON by ConsentAuthorizeEndpoint
if (dataSet.has(Constants.USER_ID)) {
String userId = dataSet.getString(Constants.USER_ID);
session.setAttribute(Constants.USER_ID, userId);
if (log.isDebugEnabled()) {
log.debug("Stored userId in session for OTP verification");
}
} else {
log.warn("userId not found in consent data response");
}

// s

// set strings to request
ResourceBundle resourceBundle = AuthenticationUtils.getResourceBundle(request.getLocale());

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
* <p>
* WSO2 LLC. licenses this file to you 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 org.wso2.financial.services.accelerator.authentication.endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.identity.smsotp.common.SMSOTPServiceImpl;
import org.wso2.carbon.identity.smsotp.common.dto.FailureReasonDTO;
import org.wso2.carbon.identity.smsotp.common.dto.GenerationResponseDTO;
import org.wso2.carbon.identity.smsotp.common.dto.ValidationResponseDTO;
import org.wso2.carbon.identity.smsotp.common.exception.SMSOTPException;
import org.wso2.financial.services.accelerator.authentication.endpoint.util.Constants;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
* FSVerifyServlet handles OTP generation and verification for user consent.
* Flow:
* - POST with otpAction=init: saves form parameters in session as pendingConsent (removes otpAction), calls
* placeholder SMS-OTP generate API, stores an otpToken in session, forwards to consent_smsotp.jsp
*
* - POST with otpAction=verify: verifies the provided otp against the placeholder API, if ok forwards to
* submit_consent.jsp (which posts to /oauth2_authz_confirm.do), otherwise redisplay consent_smsotp.jsp with error
*/
public class FSVerifyServlet extends HttpServlet {

private static final String SESSION_PENDING_CONSENT = "pendingConsent";
private static final String SESSION_OTP_TRANSACTION_ID = "otpTransactionId";
private static final String SESSION_USER_ID = "userId";
private static final String SESSION_OTP_VERIFIED = "otpVerified";
private static final String OTP_ACTION = "otpAction";
private static final String OTP_INIT = "init";
private static final String OTP_VERIFY = "verify";
private static final String CONSENT_SMSOTP_PAGE = "/consent_smsotp.jsp";
private static final String SUBMIT_CONSENT_PAGE = "/submit_consent.jsp";
private static Logger log = LoggerFactory.getLogger(FSVerifyServlet.class);
private static SMSOTPServiceImpl smsotpService = new SMSOTPServiceImpl();

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String otpAction = req.getParameter(OTP_ACTION);
if (otpAction == null) {
otpAction = OTP_INIT;
}

if (OTP_INIT.equalsIgnoreCase(otpAction)) {
handleInit(req, resp);
} else if (OTP_VERIFY.equalsIgnoreCase(otpAction)) {
handleVerify(req, resp);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown otpAction");
}
}

/**
* Handle the init action: store pending consent in session, call OTP generate API, forward to consent_smsotp.jsp.
*
* @param req - HttpServletRequest
* @param resp - HttpServletResponse
* @throws ServletException - ServletException
* @throws IOException - IOException
*/
private void handleInit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();

/* Collect all parameters from the form and store in a map as the pending consent.
This will be submitted if the otp verification is successful.*/
Map<String, List<String>> params = new HashMap<>();
req.getParameterMap().forEach((k, v) -> params.put(k, Arrays.asList(v)));
params.remove(OTP_ACTION);
session.setAttribute(SESSION_PENDING_CONSENT, params);

// Get userId (SCIM ID) from HTTP session (stored by FSConsentServlet from consent retrieval response)
String userIdFromSession = (String) session.getAttribute(Constants.USER_ID);
if (userIdFromSession == null || userIdFromSession.isEmpty()) {
req.setAttribute("otpError", "Unable to resolve user identifier. Please start over.");
req.getRequestDispatcher(CONSENT_SMSOTP_PAGE).forward(req, resp);
return;
}

// Extract SCIM ID from the format "[email protected]"
String userId = userIdFromSession;
if (userIdFromSession.contains("@")) {
userId = userIdFromSession.substring(0, userIdFromSession.indexOf("@"));
}
session.setAttribute(SESSION_USER_ID, userId);

try {

GenerationResponseDTO otpResponse = smsotpService.generateSMSOTP(userId);
Comment on lines +112 to +116
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 2

Suggested change
session.setAttribute(SESSION_USER_ID, userId);
try {
GenerationResponseDTO otpResponse = smsotpService.generateSMSOTP(userId);
try {
GenerationResponseDTO otpResponse = smsotpService.generateSMSOTP(userId);
log.info("OTP generation initiated for user ID: {}", userId);
String transactionId = otpResponse.getTransactionId();

String transactionId = otpResponse.getTransactionId();
session.setAttribute(SESSION_OTP_TRANSACTION_ID, transactionId);
req.getRequestDispatcher(CONSENT_SMSOTP_PAGE).forward(req, resp);
} catch (IOException | SMSOTPException e) {
req.setAttribute("otpError", "Error generating OTP. Please try again later.");
req.getRequestDispatcher(CONSENT_SMSOTP_PAGE).forward(req, resp);
}
}

private void handleVerify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session == null) {
req.setAttribute("otpError", "Session expired. Please start over.");
req.getRequestDispatcher(CONSENT_SMSOTP_PAGE).forward(req, resp);
return;
}

String userId = (String) session.getAttribute(SESSION_USER_ID);
String transactionId = (String) session.getAttribute(SESSION_OTP_TRANSACTION_ID);
String providedOtp = req.getParameter("smsOtp");

if (userId == null || transactionId == null) {
req.setAttribute("otpError", "No pending OTP transaction found. Please start over.");
req.getRequestDispatcher(CONSENT_SMSOTP_PAGE).forward(req, resp);
return;
}

try {
ValidationResponseDTO validationResponse = smsotpService.validateSMSOTP(transactionId, userId, providedOtp);
Comment on lines +142 to +145
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 3

Suggested change
}
try {
ValidationResponseDTO validationResponse = smsotpService.validateSMSOTP(transactionId, userId, providedOtp);
ValidationResponseDTO validationResponse = smsotpService.validateSMSOTP(transactionId, userId, providedOtp);
if (validationResponse.isValid()) {
log.info("OTP verified successfully for user ID: {}", userId);
session.removeAttribute(SESSION_OTP_TRANSACTION_ID);

if (validationResponse.isValid()) {
session.removeAttribute(SESSION_OTP_TRANSACTION_ID);
session.removeAttribute(SESSION_USER_ID);
// Set flag indicating OTP was successfully verified
session.setAttribute(SESSION_OTP_VERIFIED, Boolean.TRUE);
req.getRequestDispatcher(SUBMIT_CONSENT_PAGE).forward(req, resp);
} else {
FailureReasonDTO failureReason = validationResponse.getFailureReason();
String message = "Invalid OTP. Please try again.";
if (failureReason != null) {
log.error("OTP verification failed: {} - {} - {}",
failureReason.getCode(), failureReason.getMessage(), failureReason.getDescription());
message = failureReason.getMessage();
}
req.setAttribute("otpError", message);
req.getRequestDispatcher(CONSENT_SMSOTP_PAGE).forward(req, resp);
}
} catch (IOException | SMSOTPException e) {
// Log the error
req.setAttribute("otpError", "Error verifying OTP. Please try again later.");
req.getRequestDispatcher(CONSENT_SMSOTP_PAGE).forward(req, resp);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package org.wso2.financial.services.accelerator.authentication.endpoint.impl.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.json.JSONObject;
import org.wso2.financial.services.accelerator.common.util.HTTPClientUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
* HTTP client for calling the SMS OTP service.
*/
Comment on lines +12 to +16
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 4

Suggested change
import java.nio.charset.StandardCharsets;
/**
* HTTP client for calling the SMS OTP service.
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* HTTP client for calling the SMS OTP service.
*/
public class OTPAPIClient {
private static final Log log = LogFactory.getLog(OTPAPIClient.class);

public class OTPAPIClient {

private static final String GENERATE_URL = "https://localhost:9446/api/identity/sms-otp/v1/smsotp/generate";
private static final String VERIFY_URL = "https://localhost:9446/api/identity/sms-otp/v1/smsotp/validate";

public static JSONObject generateOtp(String userId) throws IOException {
JSONObject payload = new JSONObject();
payload.put("userId", userId);

CloseableHttpClient client = HTTPClientUtils.getHttpsClient();
HttpPost post = new HttpPost(GENERATE_URL);
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(payload.toString()));

try (CloseableHttpResponse response = client.execute(post)) {
String json = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
return new JSONObject(json);
}
Comment on lines +22 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 5

Suggested change
public static JSONObject generateOtp(String userId) throws IOException {
JSONObject payload = new JSONObject();
payload.put("userId", userId);
CloseableHttpClient client = HTTPClientUtils.getHttpsClient();
HttpPost post = new HttpPost(GENERATE_URL);
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(payload.toString()));
try (CloseableHttpResponse response = client.execute(post)) {
String json = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
return new JSONObject(json);
}
public static JSONObject generateOtp(String userId) throws IOException {
if (log.isDebugEnabled()) {
log.debug("Generating OTP for user: " + userId);
}
JSONObject payload = new JSONObject();
payload.put("userId", userId);
CloseableHttpClient client = HTTPClientUtils.getHttpsClient();
HttpPost post = new HttpPost(GENERATE_URL);
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(payload.toString()));
try (CloseableHttpResponse response = client.execute(post)) {
int statusCode = response.getStatusLine().getStatusCode();
String json = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
if (statusCode == 200) {
log.info("OTP generated successfully for user: " + userId);
} else {
log.error("Failed to generate OTP. Status code: " + statusCode);
}
return new JSONObject(json);
}

}

public static JSONObject verifyOtp(String userId, String transactionId, String otp) throws IOException {
JSONObject payload = new JSONObject();
payload.put("userId", userId);
payload.put("transactionId", transactionId);
payload.put("smsOTP", otp);

CloseableHttpClient client = HTTPClientUtils.getHttpsClient();
HttpPost post = new HttpPost(VERIFY_URL);
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(payload.toString()));

try (CloseableHttpResponse response = client.execute(post)) {
String json = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
return new JSONObject(json);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,15 @@
<url-pattern>/fs_default.do</url-pattern>
</servlet-mapping>

<!-- Verify consent page - shows a review & verify step before submitting the consent form -->
<servlet>
<servlet-name>FSVerifyServlet</servlet-name>
<servlet-class>org.wso2.financial.services.accelerator.authentication.endpoint.FSVerifyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FSVerifyServlet</servlet-name>
<url-pattern>/consent_smsotp.do</url-pattern>
</servlet-mapping>

</web-app>
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<%@ page import="static org.wso2.financial.services.accelerator.consent.mgt.extensions.authservlet.utils.Utils.i18n" %><%--
~ Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
~
~ WSO2 LLC. licenses this file to you 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.
--%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.util.*" %>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<base href="${pageContext.request.contextPath}/">
<jsp:include page="includes/head.jsp"/>
<script src="js/auth-functions.js"></script>
</head>
<body dir="${textDirection}">
<div class="page-content-wrapper" style="position: relative; min-height: 100vh;">
<div class="container-fluid" style="padding-bottom: 40px">
<div class="container">
<div class="login-form-wrapper">
<jsp:include page="includes/logo.jsp"/>

<div class="row">
<div class="col-md-5 col-md-offset-3">
<div class="row data-container">
<div class="clearfix"></div>
<div class="login-form">
<div class="form-group">
<div class="col-md-12">
<h3 class="section-heading-3" style="color: white; text-align: center;">SMS OTP Verification</h3>

<c:if test="${not empty otpError}">
<div class="alert alert-danger" role="alert">${otpError}</div>
</c:if>

<p style="color: white; text-align: left;">An SMS containing a one-time code was sent to your registered phone number. Enter it below to continue.</p>

<form method="post" action="consent_smsotp.do" class="form-horizontal" id="otpForm">
<input type="hidden" name="otpAction" value="verify"/>
<div class="form-group" style="text-align: center; padding: 0 20px;">
<input id="smsOtp" name="smsOtp" type="text" class="form-control" placeholder="Enter OTP" maxlength="6" required style="background-color: white; color: black; width: 100%;" />
</div>
<div class="form-group" style="text-align: right; padding: 0 20px;">
<button class="btn btn-primary" type="submit" style="margin: 5px;">Verify</button>
<button class="btn btn-default" type="button" onclick="denyConsent();" style="margin: 5px;">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>

<!-- Hidden form for consent denial (used by denyConsent() function) -->
<form id="oauth2_authz_confirm" method="post" action="oauth2_authz_confirm.do" style="display: none;">
<input type="hidden" id="consent" name="consent" value="deny"/>
<input type="hidden" name="sessionDataKeyConsent" value="${sessionDataKeyConsent}"/>
<input type="hidden" name="type" value="${type}"/>
<input type="hidden" name="hasApprovedAlways" value="false"/>
</form>
</div>
</div>
</div>
<jsp:include page="includes/footer.jsp"/>
</div>
</body>
</html>

Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,18 @@ function denyConsent() {
// Confirm sharing data
function approvedConsent() {
updateAccountNamesFromPermissions();
// Submit the consent form to the verify servlet for OTP generation
var consentForm = document.getElementById('oauth2_authz_confirm');
document.getElementById('consent').value = true;
document.getElementById("oauth2_authz_confirm").submit();
consentForm.action = 'consent_smsotp.do';
consentForm.method = 'post';
// Include an action marker so servlet knows this is initial step
var otpMarker = document.createElement('input');
otpMarker.type = 'hidden';
otpMarker.name = 'otpAction';
otpMarker.value = 'init';
consentForm.appendChild(otpMarker);
consentForm.submit();
}

// Confirm accounts selected
Expand Down
Loading