use of org.apache.oltu.oauth2.common.OAuth in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleOAuthAuthorizationRequest.
/**
* http://tools.ietf.org/html/rfc6749#section-4.1.2
* <p/>
* 4.1.2.1. Error Response
* <p/>
* If the request fails due to a missing, invalid, or mismatching
* redirection URI, or if the client identifier is missing or invalid,
* the authorization server SHOULD inform the resource owner of the
* error and MUST NOT automatically redirect the user-agent to the
* invalid redirection URI.
* <p/>
* If the resource owner denies the access request or if the request
* fails for reasons other than a missing or invalid redirection URI,
* the authorization server informs the client by adding the following
* parameters to the query component of the redirection URI using the
* "application/x-www-form-urlencoded" format
*
* @param oAuthMessage oAuthMessage
* @return String redirectURL
* @throws OAuthSystemException OAuthSystemException
* @throws OAuthProblemException OAuthProblemException
*/
private String handleOAuthAuthorizationRequest(OAuthMessage oAuthMessage) throws OAuthSystemException, OAuthProblemException, InvalidRequestException {
OAuth2ClientValidationResponseDTO validationResponse = validateClient(oAuthMessage);
if (!validationResponse.isValidClient()) {
EndpointUtil.triggerOnRequestValidationFailure(oAuthMessage, validationResponse);
return getErrorPageURL(oAuthMessage.getRequest(), validationResponse.getErrorCode(), OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_CLIENT, validationResponse.getErrorMsg(), null);
} else {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> logParams = new HashMap<>();
logParams.put("clientId", oAuthMessage.getClientId());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, logParams, OAuthConstants.LogConstants.SUCCESS, "OAuth client validation is successful.", "validate-oauth-client", null);
}
String tenantDomain = EndpointUtil.getSPTenantDomainFromClientId(oAuthMessage.getClientId());
setSPAttributeToRequest(oAuthMessage.getRequest(), validationResponse.getApplicationName(), tenantDomain);
}
OAuthAuthzRequest oauthRequest = new CarbonOAuthAuthzRequest(oAuthMessage.getRequest());
OAuth2Parameters params = new OAuth2Parameters();
String sessionDataKey = UUIDGenerator.generateUUID();
params.setSessionDataKey(sessionDataKey);
String redirectURI = populateOauthParameters(params, oAuthMessage, validationResponse, oauthRequest);
if (redirectURI != null) {
return redirectURI;
}
String prompt = oauthRequest.getParam(OAuthConstants.OAuth20Params.PROMPT);
params.setPrompt(prompt);
redirectURI = analyzePromptParameter(oAuthMessage, params, prompt);
if (redirectURI != null) {
return redirectURI;
}
if (isNonceMandatory(params.getResponseType())) {
validateNonceParameter(params.getNonce());
}
addDataToSessionCache(oAuthMessage, params, sessionDataKey);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.SUCCESS, "OIDC request input parameter validation is successful.", "validate-input-parameters", null);
try {
oAuthMessage.getRequest().setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
oAuthMessage.getRequest().setAttribute(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
return getLoginPageURL(oAuthMessage.getClientId(), sessionDataKey, oAuthMessage.isForceAuthenticate(), oAuthMessage.isPassiveAuthentication(), oauthRequest.getScopes(), oAuthMessage.getRequest().getParameterMap(), oAuthMessage.getRequest());
} catch (IdentityOAuth2Exception e) {
return handleException(e);
}
}
use of org.apache.oltu.oauth2.common.OAuth in project javlo by Javlo.
the class AbstractSocialNetwork method performRedirect.
@Override
public void performRedirect(HttpServletRequest request, HttpServletResponse response, boolean admin) {
HttpClient httpClient = null;
try {
httpClient = new URLConnectionClient();
OAuthClient oAuthClient = new OAuthClient(httpClient);
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
String accessToken = getAccessToken(code, oAuthClient);
TransientUserInfo.getInstance(request.getSession()).setToken(accessToken);
SocialUser user = getSocialUser(accessToken, oAuthClient);
if (user == null || user.getEmail() == null || user.getEmail().isEmpty()) {
logger.warning("OAuth login failed with provider: " + getName());
return;
}
ContentContext ctx = ContentContext.getContentContext(request, response);
login(ctx, user, admin);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
httpClient.shutdown();
}
}
}
use of org.apache.oltu.oauth2.common.OAuth in project javlo by Javlo.
the class OauthServlet method doGet.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
logger.info("oauth url = " + request.getRequestURL() + '?' + request.getQueryString());
String socialNetworkName;
boolean admin = servletPath.contains("admin");
boolean poppup = servletPath.endsWith(ISocialNetwork.POPUP_URI_SUFFIX);
if (request.getParameter("state") != null) {
Map<String, String> params = StringHelper.stringToMap(request.getParameter("state"));
socialNetworkName = params.get("name");
logger.info("socialNetworkName = " + socialNetworkName + " admin=" + admin);
try {
ContentContext ctx = ContentContext.getContentContext(request, response);
MenuElement targetPage = NavigationHelper.getPageById(ctx, params.get("page"));
if (targetPage == null) {
ContentService contentService = ContentService.getInstance(ctx.getRequest());
targetPage = contentService.getNavigation(ctx);
}
ISocialNetwork social = SocialService.getInstance(ctx).getNetwork(socialNetworkName);
if (social == null || targetPage == null) {
if (social == null) {
logger.warning("social network not found : " + socialNetworkName);
}
if (targetPage == null) {
logger.warning("page not found : " + params.get("page"));
}
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else {
social.performRedirect(request, response, admin);
params = new HashMap<String, String>();
if (admin) {
params.put("oauth", "true");
ctx = ctx.getContextWithOtherRenderMode(ContentContext.EDIT_MODE);
AdminUserFactory userFactory = AdminUserFactory.createUserFactory(ctx.getGlobalContext(), request.getSession());
User adminUser = userFactory.getCurrentUser(request.getSession());
if (adminUser == null) {
I18nAccess i18nAccess = I18nAccess.getInstance(ctx.getRequest());
params.put("err", i18nAccess.getText("user.error.msg"));
} else {
if (StringHelper.isEmpty(adminUser.getUserInfo().getPassword())) {
SocialUser socialUser = social.getSocialUser(request);
if (socialUser != null) {
logger.info("oauth login : " + socialUser.getFirstName());
IUserInfo userInfo = adminUser.getUserInfo();
userInfo.setFirstName(socialUser.getFirstName());
userInfo.setLastName(socialUser.getLastName());
userInfo.setAvatarURL(socialUser.getAvatarURL());
userInfo.setPassword(StringHelper.getRandomId());
userFactory.updateUserInfo(userInfo);
userFactory.store();
} else {
logger.warning("socialUser not found.");
}
}
}
} else {
// SocialUser socialUser = social.getSocialUser(request);
// if (socialUser != null) {
// logger.info("oauth login : "+socialUser.getFirstName());
// IUserFactory userFactory = UserFactory.createUserFactory(ctx.getRequest());
// IUserInfo userInfo = userFactory.createUserInfos();
// userInfo.setFirstName(socialUser.getFirstName());
// userInfo.setLastName(socialUser.getLastName());
// userInfo.setAvatarURL(socialUser.getAvatarURL());
// userInfo.setPassword(StringHelper.getRandomId());
// userFactory.updateUserInfo(userInfo);
// userFactory.store();
// } else {
// logger.warning("socialUser not found.");
// }
}
if (poppup) {
response.setContentType("text/html; charset=" + ContentContext.CHARACTER_ENCODING);
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream()));
out.println("<script type=\"text/javascript\">");
out.println("window.close();");
out.println("</script>");
out.close();
return;
} else {
response.sendRedirect(URLHelper.createURL(ctx, targetPage, params));
}
}
} catch (Exception e) {
throw new ServletException(e);
}
} else {
logger.info("no state");
OAuthAuthzResponse oar;
try {
oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
} catch (OAuthProblemException e) {
e.printStackTrace();
}
}
}
use of org.apache.oltu.oauth2.common.OAuth in project pyramus by otavanopisto.
the class TokenEndpointRESTService method authorize.
@Unsecure
@Path("/token")
@POST
public Response authorize(@Context HttpServletResponse res, @Context HttpServletRequest req) throws OAuthSystemException {
OAuthTokenRequest oauthRequest;
boolean refreshing = false;
OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
try {
oauthRequest = new OAuthTokenRequest(req);
ClientApplication clientApplication = oauthController.findByClientIdAndClientSecret(oauthRequest.getClientId(), oauthRequest.getClientSecret());
if (clientApplication == null) {
logger.severe("Invalid client application");
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FORBIDDEN).setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription("Invalid client").buildJSONMessage();
return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
}
ClientApplicationAuthorizationCode clientApplicationAuthorizationCode = null;
if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
clientApplicationAuthorizationCode = oauthController.findByClientApplicationAndAuthorizationCode(clientApplication, oauthRequest.getParam(OAuth.OAUTH_CODE));
if (clientApplicationAuthorizationCode == null) {
logger.severe(String.format("Client application authorization code not found for token %s", oauthRequest.getParam(OAuth.OAUTH_CODE)));
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FORBIDDEN).setError(OAuthError.TokenResponse.INVALID_GRANT).setErrorDescription("invalid authorization code").buildJSONMessage();
return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
}
} else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.toString())) {
refreshing = true;
} else {
return Response.status(HttpServletResponse.SC_NOT_IMPLEMENTED).build();
}
String accessToken = oauthIssuerImpl.accessToken();
String refreshToken = oauthIssuerImpl.refreshToken();
ClientApplicationAccessToken clientApplicationAccessToken;
Long expires = (System.currentTimeMillis() / 1000L) + TOKEN_LIFETIME;
if (refreshing) {
// New access token and expiration time but refresh token remains unchanged
refreshToken = oauthRequest.getParam(OAuth.OAUTH_REFRESH_TOKEN);
clientApplicationAccessToken = oauthController.findByRefreshToken(refreshToken);
if (clientApplicationAccessToken != null) {
oauthController.refresh(clientApplicationAccessToken, expires, accessToken);
} else {
logger.severe(String.format("Invalid refresh token %s", refreshToken));
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FORBIDDEN).setError("Invalid refresh token").buildJSONMessage();
return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
}
} else {
clientApplicationAccessToken = oauthController.findByClientApplicationAuthorizationCode(clientApplicationAuthorizationCode);
if (clientApplicationAccessToken == null) {
oauthController.createAccessToken(accessToken, refreshToken, expires, clientApplication, clientApplicationAuthorizationCode);
} else {
oauthController.renewAccessToken(clientApplicationAccessToken, expires, accessToken, refreshToken);
}
}
OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setRefreshToken(refreshToken).setExpiresIn(String.valueOf(TOKEN_LIFETIME)).buildJSONMessage();
return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
} catch (OAuthProblemException e) {
logger.log(Level.SEVERE, "Oauth problem", e);
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildJSONMessage();
return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
}
}
use of org.apache.oltu.oauth2.common.OAuth in project pyramus by otavanopisto.
the class AbstractRESTServiceTest method createAccessToken.
@Before
public void createAccessToken() {
OAuthClientRequest tokenRequest = null;
try {
tokenRequest = OAuthClientRequest.tokenLocation("https://dev.pyramus.fi:8443/1/oauth/token").setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(fi.otavanopisto.pyramus.Common.CLIENT_ID).setClientSecret(fi.otavanopisto.pyramus.Common.CLIENT_SECRET).setRedirectURI(fi.otavanopisto.pyramus.Common.REDIRECT_URL).setCode(fi.otavanopisto.pyramus.Common.AUTH_CODE).buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
}
Response response = given().contentType("application/x-www-form-urlencoded").body(tokenRequest.getBody()).post("/oauth/token");
String accessToken = response.body().jsonPath().getString("access_token");
setAccessToken(accessToken);
setUserId(new Long(given().headers(getAuthHeaders()).contentType("application/json").get("/system/whoami").body().jsonPath().getInt("id")));
}
Aggregations