Search in sources :

Example 36 with OAuth

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);
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CarbonOAuthAuthzRequest(org.wso2.carbon.identity.oauth2.model.CarbonOAuthAuthzRequest) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) CarbonOAuthAuthzRequest(org.wso2.carbon.identity.oauth2.model.CarbonOAuthAuthzRequest)

Example 37 with OAuth

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();
        }
    }
}
Also used : URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) HttpClient(org.apache.oltu.oauth2.client.HttpClient) OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse) ContentContext(org.javlo.context.ContentContext) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) IOException(java.io.IOException) UserAllreadyExistException(org.javlo.user.exception.UserAllreadyExistException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException)

Example 38 with OAuth

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();
        }
    }
}
Also used : SocialUser(org.javlo.service.social.SocialUser) User(org.javlo.user.User) I18nAccess(org.javlo.i18n.I18nAccess) SocialUser(org.javlo.service.social.SocialUser) AdminUserFactory(org.javlo.user.AdminUserFactory) ContentService(org.javlo.service.ContentService) MenuElement(org.javlo.navigation.MenuElement) OAuthAuthzResponse(org.apache.oltu.oauth2.client.response.OAuthAuthzResponse) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ISocialNetwork(org.javlo.service.social.ISocialNetwork) ServletException(javax.servlet.ServletException) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) IUserInfo(org.javlo.user.IUserInfo) OutputStreamWriter(java.io.OutputStreamWriter) ContentContext(org.javlo.context.ContentContext) PrintWriter(java.io.PrintWriter)

Example 39 with OAuth

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();
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) ClientApplication(fi.otavanopisto.pyramus.domainmodel.clientapplications.ClientApplication) ClientApplicationAccessToken(fi.otavanopisto.pyramus.domainmodel.clientapplications.ClientApplicationAccessToken) OAuthTokenRequest(org.apache.oltu.oauth2.as.request.OAuthTokenRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthIssuer(org.apache.oltu.oauth2.as.issuer.OAuthIssuer) ClientApplicationAuthorizationCode(fi.otavanopisto.pyramus.domainmodel.clientapplications.ClientApplicationAuthorizationCode) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Unsecure(fi.otavanopisto.pyramus.rest.annotation.Unsecure)

Example 40 with OAuth

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")));
}
Also used : Response(io.restassured.response.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) Before(org.junit.Before)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)22 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)17 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)14 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 URI (java.net.URI)9 HashMap (java.util.HashMap)7 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)6 OAuthASResponse (org.apache.oltu.oauth2.as.response.OAuthASResponse)6 ResponseEntity (org.springframework.http.ResponseEntity)6 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)5 OAuthAuthzRequest (org.apache.oltu.oauth2.as.request.OAuthAuthzRequest)5 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 OAuthAuthzResponse (org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)4 HttpHeaders (org.springframework.http.HttpHeaders)4 ServletException (javax.servlet.ServletException)3