use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException in project airavata by apache.
the class SecureClient method main.
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
// register client or use existing client
System.out.println("");
System.out.println("Please select from the following options:");
System.out.println("1. Register the client as an OAuth application.");
System.out.println("2. Client is already registered. Use the existing credentials.");
String opInput = scanner.next();
int option = Integer.valueOf(opInput.trim());
String consumerId = null;
String consumerSecret = null;
if (option == 1) {
// register OAuth application - this happens once during initialization of the gateway.
/**
**********************Start obtaining input from user****************************
*/
System.out.println("");
System.out.println("Registering an OAuth application representing the client....");
System.out.println("Please enter following information as you prefer, or use defaults.");
System.out.println("OAuth application name: (default:" + Properties.appName + ", press 'd' to use default value.)");
String appNameInput = scanner.next();
String appName = null;
if (appNameInput.trim().equals("d")) {
appName = Properties.appName;
} else {
appName = appNameInput.trim();
}
System.out.println("Consumer Id: (default:" + Properties.consumerID + ", press 'd' to use default value.)");
String consumerIdInput = scanner.next();
if (consumerIdInput.trim().equals("d")) {
consumerId = Properties.consumerID;
} else {
consumerId = consumerIdInput.trim();
}
System.out.println("Consumer Secret: (default:" + Properties.consumerSecret + ", press 'd' to use default value.)");
String consumerSecInput = scanner.next();
if (consumerSecInput.trim().equals("d")) {
consumerSecret = Properties.consumerSecret;
} else {
consumerSecret = consumerSecInput.trim();
}
/**
********************* Perform registration of the client as an OAuth app**************************
*/
try {
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
OAuthAppRegisteringClient authAppRegisteringClient = new OAuthAppRegisteringClient(Properties.oauthAuthzServerURL, Properties.adminUserName, Properties.adminPassword, configContext);
OAuthConsumerAppDTO appDTO = authAppRegisteringClient.registerApplication(appName, consumerId, consumerSecret);
/**
******************* Complete registering the client **********************************************
*/
System.out.println("");
System.out.println("Registered OAuth app successfully. Following is app's details:");
System.out.println("App Name: " + appDTO.getApplicationName());
System.out.println("Consumer ID: " + appDTO.getOauthConsumerKey());
System.out.println("Consumer Secret: " + appDTO.getOauthConsumerSecret());
System.out.println("");
} catch (AiravataSecurityException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else if (option == 2) {
System.out.println("");
System.out.println("Enter Consumer Id: ");
consumerId = scanner.next().trim();
System.out.println("Enter Consumer Secret: ");
consumerSecret = scanner.next().trim();
}
// obtain OAuth access token
/**
**********************Start obtaining input from user****************************
*/
System.out.println("");
System.out.println("Please select the preferred grant type: (or press d to use the default option" + Properties.grantType + ")");
System.out.println("1. Resource Owner Password Credential.");
System.out.println("2. Client Credential.");
String grantTypeInput = scanner.next().trim();
int grantType = 0;
if (grantTypeInput.equals("d")) {
grantType = Properties.grantType;
} else {
grantType = Integer.valueOf(grantTypeInput);
}
String userName = null;
String password = null;
if (grantType == 1) {
System.out.println("Obtaining OAuth access token via 'Resource Owner Password' grant type....");
System.out.println("Please enter following information as you prefer, or use defaults.");
System.out.println("End user's name: (default:" + Properties.userName + ", press 'd' to use default value.)");
String userNameInput = scanner.next();
if (userNameInput.trim().equals("d")) {
userName = Properties.userName;
} else {
userName = userNameInput.trim();
}
System.out.println("End user's password: (default:" + Properties.password + ", press 'd' to use default value.)");
String passwordInput = scanner.next();
if (passwordInput.trim().equals("d")) {
password = Properties.password;
} else {
password = passwordInput.trim();
}
} else if (grantType == 2) {
System.out.println("");
System.out.println("Please enter the user name to be passed: ");
String userNameInput = scanner.next();
userName = userNameInput.trim();
System.out.println("");
System.out.println("Obtaining OAuth access token via 'Client Credential' grant type...' grant type....");
}
/**
*************************** Finish obtaining input from user******************************************
*/
try {
// obtain the OAuth token for the specified end user.
String accessToken = new OAuthTokenRetrievalClient().retrieveAccessToken(consumerId, consumerSecret, userName, password, grantType);
System.out.println("");
System.out.println("OAuth access token is: " + accessToken);
// invoke Airavata API by the SecureClient, on behalf of the user.
System.out.println("");
System.out.println("Invoking Airavata API...");
System.out.println("Enter the access token to be used: (default:" + accessToken + ", press 'd' to use default value.)");
String accessTokenInput = scanner.next();
String acTk = null;
if (accessTokenInput.trim().equals("d")) {
acTk = accessToken;
} else {
acTk = accessTokenInput.trim();
}
// obtain as input, the method to be invoked
System.out.println("");
System.out.println("Enter the number corresponding to the method to be invoked: ");
System.out.println("1. getAPIVersion");
System.out.println("2. getAllAppModules");
System.out.println("3. addGateway");
String methodNumberString = scanner.next();
int methodNumber = Integer.valueOf(methodNumberString.trim());
Airavata.Client client = createAiravataClient(Properties.SERVER_HOST, Properties.SERVER_PORT);
AuthzToken authzToken = new AuthzToken();
authzToken.setAccessToken(acTk);
Map<String, String> claimsMap = new HashMap<>();
claimsMap.put("userName", userName);
claimsMap.put("email", "hasini@gmail.com");
authzToken.setClaimsMap(claimsMap);
if (methodNumber == 1) {
String version = client.getAPIVersion(authzToken);
System.out.println("");
System.out.println("Airavata API version: " + version);
System.out.println("");
} else if (methodNumber == 2) {
System.out.println("");
System.out.println("Enter the gateway id: ");
String gatewayId = scanner.next().trim();
List<ApplicationModule> appModules = client.getAllAppModules(authzToken, gatewayId);
System.out.println("Output of getAllAppModuels: ");
for (ApplicationModule appModule : appModules) {
System.out.println(appModule.getAppModuleName());
}
System.out.println("");
System.out.println("");
} else if (methodNumber == 3) {
System.out.println("");
System.out.println("Enter the gateway id: ");
String gatewayId = scanner.next().trim();
Gateway gateway = new Gateway(gatewayId, GatewayApprovalStatus.REQUESTED);
gateway.setDomain("airavata.org");
gateway.setEmailAddress("airavata@apache.org");
gateway.setGatewayName("airavataGW");
String output = client.addGateway(authzToken, gateway);
System.out.println("");
System.out.println("Output of addGateway: " + output);
System.out.println("");
}
} catch (InvalidRequestException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} catch (AiravataSecurityException e) {
e.printStackTrace();
}
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method populateOauthParameters.
private String populateOauthParameters(OAuth2Parameters params, OAuthMessage oAuthMessage, OAuth2ClientValidationResponseDTO validationResponse, OAuthAuthzRequest oauthRequest) throws OAuthSystemException, InvalidRequestException {
String clientId = oAuthMessage.getClientId();
params.setClientId(clientId);
params.setRedirectURI(validationResponse.getCallbackURL());
params.setResponseType(oauthRequest.getResponseType());
params.setResponseMode(oauthRequest.getParam(RESPONSE_MODE));
params.setScopes(oauthRequest.getScopes());
if (params.getScopes() == null) {
// to avoid null pointers
Set<String> scopeSet = new HashSet<String>();
scopeSet.add("");
params.setScopes(scopeSet);
}
params.setState(oauthRequest.getState());
params.setApplicationName(validationResponse.getApplicationName());
String spDisplayName = getSpDisplayName(clientId);
if (StringUtils.isNotBlank(spDisplayName)) {
params.setDisplayName(spDisplayName);
}
// OpenID Connect specific request parameters
params.setNonce(oauthRequest.getParam(OAuthConstants.OAuth20Params.NONCE));
params.setDisplay(oauthRequest.getParam(OAuthConstants.OAuth20Params.DISPLAY));
params.setIDTokenHint(oauthRequest.getParam(OAuthConstants.OAuth20Params.ID_TOKEN_HINT));
params.setLoginHint(oauthRequest.getParam(OAuthConstants.OAuth20Params.LOGIN_HINT));
// Set the service provider tenant domain.
params.setTenantDomain(getSpTenantDomain(clientId));
// Set the login tenant domain.
String loginTenantDomain = getLoginTenantDomain(oAuthMessage, clientId);
params.setLoginTenantDomain(loginTenantDomain);
if (StringUtils.isNotBlank(oauthRequest.getParam(ACR_VALUES)) && !"null".equals(oauthRequest.getParam(ACR_VALUES))) {
List acrValuesList = Arrays.asList(oauthRequest.getParam(ACR_VALUES).split(" "));
LinkedHashSet acrValuesHashSet = new LinkedHashSet<>(acrValuesList);
params.setACRValues(acrValuesHashSet);
oAuthMessage.getRequest().setAttribute(ACR_VALUES, acrValuesList);
}
if (StringUtils.isNotBlank(oauthRequest.getParam(CLAIMS))) {
params.setEssentialClaims(oauthRequest.getParam(CLAIMS));
}
handleMaxAgeParameter(oauthRequest, params);
/*
OIDC Request object will supersede parameters sent in the OAuth Authorization request. So handling the
OIDC Request object needs to done after processing all request parameters.
*/
if (OAuth2Util.isOIDCAuthzRequest(oauthRequest.getScopes())) {
try {
handleOIDCRequestObject(oAuthMessage, oauthRequest, params);
} catch (RequestObjectException e) {
if (log.isDebugEnabled()) {
log.debug("Request Object Handling failed due to : " + e.getErrorCode() + " for client_id: " + clientId + " of tenantDomain: " + params.getTenantDomain(), e);
}
if (StringUtils.isNotBlank(oAuthMessage.getRequest().getParameter(REQUEST_URI))) {
return EndpointUtil.getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_REQUEST_URI, e.getErrorCode(), e.getErrorMessage(), null, params);
} else {
return EndpointUtil.getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_REQUEST_OBJECT, e.getErrorCode(), e.getErrorMessage(), null, params);
}
}
}
if (isPkceSupportEnabled()) {
String pkceChallengeCode = getPkceCodeChallenge(oAuthMessage, params);
String pkceChallengeMethod = getPkceCodeChallengeMethod(oAuthMessage, params);
String redirectURI = validatePKCEParameters(oAuthMessage, validationResponse, pkceChallengeCode, pkceChallengeMethod);
if (redirectURI != null) {
return redirectURI;
}
params.setPkceCodeChallenge(pkceChallengeCode);
params.setPkceCodeChallengeMethod(pkceChallengeMethod);
}
return null;
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleRequestObject.
private void handleRequestObject(OAuthMessage oAuthMessage, OAuthAuthzRequest oauthRequest, OAuth2Parameters parameters) throws RequestObjectException, InvalidRequestException {
RequestObject requestObject = OIDCRequestObjectUtil.buildRequestObject(oauthRequest, parameters);
if (requestObject == null) {
throw new RequestObjectException(OAuth2ErrorCodes.INVALID_REQUEST, "Unable to build a valid Request " + "Object from the authorization request.");
}
/*
When the request parameter is used, the OpenID Connect request parameter values contained in the JWT
supersede those passed using the OAuth 2.0 request syntax
*/
overrideAuthzParameters(oAuthMessage, parameters, oauthRequest.getParam(REQUEST), oauthRequest.getParam(REQUEST_URI), requestObject);
// so validating if the registered redirect uri is a single uri that can be properly redirected.
if (StringUtils.isBlank(parameters.getRedirectURI()) || StringUtils.startsWith(parameters.getRedirectURI(), REGEX_PATTERN)) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "Redirect URI is not present in the authorization request.", "validate-input-parameters", null);
throw new InvalidRequestException("Redirect URI is not present in the authorization request.", OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_REDIRECT_URI);
}
persistRequestObject(parameters, requestObject);
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2CibaEndpoint method validateAuthenticationRequest.
/**
* Validate whether Request JWT is in proper formatting.
*
* @param authRequest CIBA Authentication Request as a String.
* @throws CibaAuthFailureException CIBA Authentication Failed Exception.
*/
private void validateAuthenticationRequest(String authRequest, String clientId) throws CibaAuthFailureException {
// Validation for the proper formatting of signedJWT.
cibaAuthRequestValidator.validateRequest(authRequest);
// Validation for the client.
cibaAuthRequestValidator.validateClient(authRequest, clientId);
// Validation for the userHint.
cibaAuthRequestValidator.validateUserHint(authRequest);
// Validate Authentication request.
cibaAuthRequestValidator.validateAuthRequestParams(authRequest);
try {
RequestObject requestObject;
RequestObjectBuilder requestObjectBuilder;
requestObjectBuilder = OAuthServerConfiguration.getInstance().getRequestObjectBuilders().get(REQUEST_PARAM_VALUE_BUILDER);
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.setClientId(clientId);
parameters.setTenantDomain(getSpTenantDomain(clientId));
if (requestObjectBuilder == null) {
String error = "Unable to build the OIDC Request Object";
throw new CibaAuthFailureException(OAuth2ErrorCodes.SERVER_ERROR, error);
}
requestObject = requestObjectBuilder.buildRequestObject(authRequest, parameters);
RequestObjectValidator requestObjectValidator = OAuthServerConfiguration.getInstance().getCIBARequestObjectValidator();
OIDCRequestObjectUtil.validateRequestObjectSignature(parameters, requestObject, requestObjectValidator);
if (!requestObjectValidator.validateRequestObject(requestObject, parameters)) {
throw new CibaAuthFailureException(OAuth2ErrorCodes.INVALID_REQUEST, "Invalid parameters " + "found in the Request Object.");
}
} catch (InvalidRequestException | RequestObjectException e) {
if (log.isDebugEnabled()) {
log.debug(OAuth2ErrorCodes.INVALID_REQUEST, e);
}
throw new CibaAuthFailureException(OAuth2ErrorCodes.INVALID_REQUEST, e.getMessage());
}
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuthRequestStateValidator method validateRequest.
private void validateRequest(OAuthMessage oAuthMessage) throws InvalidRequestParentException {
validateRepeatedParameters(oAuthMessage);
if (oAuthMessage.getResultFromLogin() != null && oAuthMessage.getResultFromConsent() != null) {
if (log.isDebugEnabled()) {
log.debug("Invalid authorization request.\'SessionDataKey\' found in request as parameter and " + "attribute, and both have non NULL objects in cache");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "invalid 'SessionDataKey' parameter in authorization request", "validate-input-parameters", null);
}
throw new InvalidRequestException("Invalid authorization request", OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_AUTHORIZATION_REQUEST);
} else if (oAuthMessage.getClientId() == null && oAuthMessage.getResultFromLogin() == null && oAuthMessage.getResultFromConsent() == null) {
if (log.isDebugEnabled()) {
log.debug("Invalid authorization request.\'SessionDataKey\' not found in request as parameter or " + "attribute, and client_id parameter cannot be found in request");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "invalid 'client_id' and 'SessionDataKey' parameters cannot be found in request", "validate-input-parameters", null);
}
throw new InvalidRequestException("Invalid authorization request", OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_CLIENT);
} else if (oAuthMessage.getSessionDataKeyFromLogin() != null && oAuthMessage.getResultFromLogin() == null) {
if (log.isDebugEnabled()) {
log.debug("Session data not found in SessionDataCache for " + oAuthMessage.getSessionDataKeyFromLogin());
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Access denied since user session has timed-out.", "validate-input-parameters", null);
}
throw new AccessDeniedException("Session Timed Out", OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ErrorCodes.OAuth2SubErrorCodes.SESSION_TIME_OUT);
} else if (oAuthMessage.getSessionDataKeyFromConsent() != null && oAuthMessage.getResultFromConsent() == null) {
if (oAuthMessage.getResultFromLogin() == null) {
if (log.isDebugEnabled()) {
log.debug("Session data not found in SessionDataCache for " + oAuthMessage.getSessionDataKeyFromConsent());
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Access denied since user session has timed-out.", "validate-input-parameters", null);
}
throw new AccessDeniedException("Session Timed Out", OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ErrorCodes.OAuth2SubErrorCodes.SESSION_TIME_OUT);
} else {
// if the sessionDataKeyFromConsent parameter present in the login request, skip it and allow login
// since result from login is there.
oAuthMessage.setSessionDataKeyFromConsent(null);
}
}
}
Aggregations