use of org.wso2.mdm.qsg.dto.HTTPResponse in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticatorTest method testGetConfigurationProperties.
@Test
public void testGetConfigurationProperties() {
List<Property> configProperties = new ArrayList<Property>();
Property smsUrl = new Property();
configProperties.add(smsUrl);
Property httpMethod = new Property();
configProperties.add(httpMethod);
Property headers = new Property();
configProperties.add(headers);
Property payload = new Property();
configProperties.add(payload);
Property httpResponse = new Property();
configProperties.add(httpResponse);
Assert.assertEquals(configProperties.size(), smsotpAuthenticator.getConfigurationProperties().size());
}
use of org.wso2.mdm.qsg.dto.HTTPResponse in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticator method proceedWithOTP.
/**
* Proceed with One Time Password.
*
* @param response the HttpServletResponse
* @param context the AuthenticationContext
* @param errorPage the errorPage
* @param mobileNumber the mobile number
* @param queryParams the queryParams
* @param username the Username
* @throws AuthenticationFailedException
*/
private void proceedWithOTP(HttpServletResponse response, AuthenticationContext context, String errorPage, String mobileNumber, String queryParams, String username) throws AuthenticationFailedException {
String screenValue;
Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
boolean isEnableResendCode = SMSOTPUtils.isEnableResendCode(context, getName());
String loginPage = getLoginPage(context);
String tenantDomain = MultitenantUtils.getTenantDomain(username);
String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
UserRealm userRealm = SMSOTPUtils.getUserRealm(tenantDomain);
try {
// One time password is generated and stored in the context.
OneTimePassword token = new OneTimePassword();
String secret = OneTimePassword.getRandomNumber(SMSOTPConstants.SECRET_KEY_LENGTH);
String otpToken = token.generateToken(secret, String.valueOf(SMSOTPConstants.NUMBER_BASE), SMSOTPConstants.NUMBER_DIGIT);
context.setProperty(SMSOTPConstants.OTP_TOKEN, otpToken);
if (log.isDebugEnabled()) {
log.debug("Generated OTP successfully and set to the context.");
}
// Get the values of the sms provider related api parameters.
String smsUrl = authenticatorProperties.get(SMSOTPConstants.SMS_URL);
String httpMethod = authenticatorProperties.get(SMSOTPConstants.HTTP_METHOD);
String headerString = authenticatorProperties.get(SMSOTPConstants.HEADERS);
String payload = authenticatorProperties.get(SMSOTPConstants.PAYLOAD);
String httpResponse = authenticatorProperties.get(SMSOTPConstants.HTTP_RESPONSE);
if (!sendRESTCall(context, smsUrl, httpMethod, headerString, payload, httpResponse, mobileNumber, otpToken)) {
String retryParam;
context.setProperty(SMSOTPConstants.STATUS_CODE, SMSOTPConstants.UNABLE_SEND_CODE);
if (context.getProperty(SMSOTPConstants.ERROR_CODE) != null) {
retryParam = SMSOTPConstants.UNABLE_SEND_CODE_PARAM + context.getProperty(SMSOTPConstants.ERROR_CODE).toString();
} else {
retryParam = SMSOTPConstants.UNABLE_SEND_CODE_PARAM + SMSOTPConstants.UNABLE_SEND_CODE_VALUE;
}
String redirectUrl = getURL(errorPage, queryParams);
response.sendRedirect(redirectUrl + SMSOTPConstants.RESEND_CODE + isEnableResendCode + retryParam);
} else {
String url = getURL(loginPage, queryParams);
boolean isUserExists = FederatedAuthenticatorUtil.isUserExistInUserStore(username);
if (isUserExists) {
screenValue = getScreenAttribute(context, userRealm, tenantAwareUsername);
if (screenValue != null) {
url = url + SMSOTPConstants.SCREEN_VALUE + screenValue;
}
}
response.sendRedirect(url);
}
} catch (IOException e) {
throw new AuthenticationFailedException("Error while sending the HTTP request. ", e);
} catch (UserStoreException e) {
throw new AuthenticationFailedException("Failed to get the user from user store. ", e);
}
}
use of org.wso2.mdm.qsg.dto.HTTPResponse in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticator method getConfigurationProperties.
/**
* Get the configuration properties of UI
*/
@Override
public List<Property> getConfigurationProperties() {
List<Property> configProperties = new ArrayList<Property>();
Property smsUrl = new Property();
smsUrl.setName(SMSOTPConstants.SMS_URL);
smsUrl.setDisplayName("SMS URL");
smsUrl.setRequired(true);
smsUrl.setDescription("Enter client sms url value. If the phone number and text message are in URL, " + "specify them as $ctx.num and $ctx.msg");
smsUrl.setDisplayOrder(0);
configProperties.add(smsUrl);
Property httpMethod = new Property();
httpMethod.setName(SMSOTPConstants.HTTP_METHOD);
httpMethod.setDisplayName("HTTP Method");
httpMethod.setRequired(true);
httpMethod.setDescription("Enter the HTTP Method used by the SMS API");
httpMethod.setDisplayOrder(1);
configProperties.add(httpMethod);
Property headers = new Property();
headers.setName(SMSOTPConstants.HEADERS);
headers.setDisplayName("HTTP Headers");
headers.setRequired(false);
headers.setDescription("Enter the headers used by the API separated by comma, with the Header name and value " + "separated by \":\". If the phone number and text message are in Headers, specify them as $ctx.num and $ctx.msg");
headers.setDisplayOrder(2);
configProperties.add(headers);
Property payload = new Property();
payload.setName(SMSOTPConstants.PAYLOAD);
payload.setDisplayName("HTTP Payload");
payload.setRequired(false);
payload.setDescription("Enter the HTTP Payload used by the SMS API. If the phone number and text message are " + "in Payload, specify them as $ctx.num and $ctx.msg");
payload.setDisplayOrder(3);
configProperties.add(payload);
Property httpResponse = new Property();
httpResponse.setName(SMSOTPConstants.HTTP_RESPONSE);
httpResponse.setDisplayName("HTTP Response Code");
httpResponse.setRequired(false);
httpResponse.setDescription("Enter the HTTP response code the API sends upon successful call. Leave empty if unknown");
httpResponse.setDisplayOrder(4);
configProperties.add(httpResponse);
return configProperties;
}
use of org.wso2.mdm.qsg.dto.HTTPResponse in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticator method getConnection.
/**
* Get the connection and proceed with SMS API's rest call.
*
* @param httpConnection the connection
* @param context the authenticationContext
* @param headerString the header string
* @param payload the payload
* @param httpResponse the http response
* @param encodedMobileNo the encoded mobileNo
* @param smsMessage the sms message
* @param otpToken the token
* @param httpMethod the http method
* @return true or false
* @throws AuthenticationFailedException
*/
private boolean getConnection(HttpURLConnection httpConnection, AuthenticationContext context, String headerString, String payload, String httpResponse, String encodedMobileNo, String smsMessage, String otpToken, String httpMethod) throws AuthenticationFailedException {
try {
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
String[] headerArray;
if (StringUtils.isNotEmpty(headerString)) {
if (log.isDebugEnabled()) {
log.debug("Processing HTTP headers since header string is available");
}
headerString = headerString.trim().replaceAll("\\$ctx.num", encodedMobileNo).replaceAll("\\$ctx.msg", smsMessage + otpToken);
headerArray = headerString.split(",");
for (String header : headerArray) {
String[] headerElements = header.split(":");
if (headerElements.length > 1) {
httpConnection.setRequestProperty(headerElements[0], headerElements[1]);
} else {
log.info("Either header name or value not found. Hence not adding header which contains " + headerElements[0]);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("No configured headers found. Header string is empty");
}
}
// Processing HTTP Method
if (log.isDebugEnabled()) {
log.debug("Configured http method is " + httpMethod);
}
if (SMSOTPConstants.GET_METHOD.equalsIgnoreCase(httpMethod)) {
httpConnection.setRequestMethod(SMSOTPConstants.GET_METHOD);
} else if (SMSOTPConstants.POST_METHOD.equalsIgnoreCase(httpMethod)) {
httpConnection.setRequestMethod(SMSOTPConstants.POST_METHOD);
if (StringUtils.isNotEmpty(payload)) {
payload = payload.replaceAll("\\$ctx.num", encodedMobileNo).replaceAll("\\$ctx.msg", smsMessage + otpToken);
}
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(httpConnection.getOutputStream(), SMSOTPConstants.CHAR_SET);
writer.write(payload);
} catch (IOException e) {
throw new AuthenticationFailedException("Error while posting payload message ", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
if (StringUtils.isNotEmpty(httpResponse)) {
if (httpResponse.trim().equals(String.valueOf(httpConnection.getResponseCode()))) {
if (log.isDebugEnabled()) {
log.debug("Code is successfully sent to the mobile and recieved expected response code : " + httpResponse);
}
return true;
}
} else {
if (httpConnection.getResponseCode() == 200 || httpConnection.getResponseCode() == 201 || httpConnection.getResponseCode() == 202) {
if (log.isDebugEnabled()) {
log.debug("Code is successfully sent to the mobile. Relieved HTTP response code is : " + httpConnection.getResponseCode());
}
return true;
} else {
context.setProperty(SMSOTPConstants.ERROR_CODE, httpConnection.getResponseCode() + " : " + httpConnection.getResponseMessage());
log.error("Error while sending SMS: error code is " + httpConnection.getResponseCode() + " and error message is " + httpConnection.getResponseMessage());
return false;
}
}
} catch (MalformedURLException e) {
throw new AuthenticationFailedException("Invalid URL ", e);
} catch (ProtocolException e) {
throw new AuthenticationFailedException("Error while setting the HTTP method ", e);
} catch (IOException e) {
throw new AuthenticationFailedException("Error while setting the HTTP response ", e);
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
return false;
}
use of org.wso2.mdm.qsg.dto.HTTPResponse in project product-iots by wso2.
the class OAuthUtil method getOAuthTokenPair.
public static JSONObject getOAuthTokenPair(String backendHTTPURL, String backendHTTPSURL) throws Exception {
String AuthString = "Basic YWRtaW46YWRtaW4=";
RestClient client = new RestClient(backendHTTPURL, Constants.APPLICATION_JSON, AuthString);
HttpResponse oAuthData = client.post(Constants.APIApplicationRegistration.API_APP_REGISTRATION_ENDPOINT, Constants.APIApplicationRegistration.API_APP_REGISTRATION_PAYLOAD);
JSONObject jsonObj = new JSONObject(oAuthData.getData());
String clientId = jsonObj.get(Constants.OAUTH_CLIENT_ID).toString();
String clientSecret = jsonObj.get(Constants.OAUTH_CLIENT_SECRET).toString();
byte[] bytesEncoded = Base64.encodeBase64((clientId + ":" + clientSecret).getBytes());
String basicAuthString = "Basic " + new String(bytesEncoded);
// Initiate a RestClient to get OAuth token
client = new RestClient(backendHTTPSURL, Constants.APPLICATION_URL_ENCODED, basicAuthString);
oAuthData = client.post(Constants.APIApplicationRegistration.TOKEN_ENDPOINT, Constants.APIApplicationRegistration.OAUTH_TOKEN_PAYLOAD);
jsonObj = new JSONObject(oAuthData.getData());
return jsonObj;
}
Aggregations