Search in sources :

Example 16 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project BIMserver by opensourceBIM.

the class OAuthRegistrationServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse httpResponse) throws ServletException, IOException {
    OAuthServerRegistrationRequest oauthRequest = null;
    try {
        oauthRequest = new OAuthServerRegistrationRequest(new JSONHttpServletRequestWrapper(request));
        oauthRequest.discover();
        oauthRequest.getClientUrl();
        oauthRequest.getClientDescription();
        oauthRequest.getRedirectURI();
        try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.POSSIBLY_WRITE)) {
            OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_RedirectUrl(), oauthRequest.getRedirectURI());
            GregorianCalendar now = new GregorianCalendar();
            if (oAuthServer == null) {
                oAuthServer = session.create(OAuthServer.class);
                oAuthServer.setClientName(oauthRequest.getClientName());
                oAuthServer.setClientUrl(oauthRequest.getClientUrl());
                oAuthServer.setClientDescription(oauthRequest.getClientDescription());
                if (oauthRequest.getClientIcon() != null) {
                    try {
                        byte[] icon = NetUtils.getContentAsBytes(new URL(oauthRequest.getClientIcon()), 5000);
                        oAuthServer.setClientIcon(icon);
                    } catch (Exception e) {
                    // 
                    }
                }
                oAuthServer.setRedirectUrl(oauthRequest.getRedirectURI());
                // DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
                GregorianCalendar expires = new GregorianCalendar();
                expires.add(Calendar.YEAR, 1);
                String secret = new MD5Generator().generateValue();
                oAuthServer.setIssuedAt(now.getTime());
                oAuthServer.setExpiresAt(expires.getTime());
                oAuthServer.setClientSecret(secret);
                oAuthServer.setClientId(oauthRequest.getClientName().replace(" ", "").toLowerCase());
                oAuthServer.setIncoming(true);
                session.commit();
            }
            OAuthResponse response = OAuthServerRegistrationResponse.status(HttpServletResponse.SC_OK).setClientId(oAuthServer.getClientId()).setClientSecret(oAuthServer.getClientSecret()).setIssuedAt("" + oAuthServer.getIssuedAt().getTime()).setExpiresIn(oAuthServer.getExpiresAt().getTime() - now.getTimeInMillis()).setParam("message", "OK").buildJSONMessage();
            httpResponse.setStatus(response.getResponseStatus());
            httpResponse.setContentType(response.getHeaders().get("Content-Type"));
            httpResponse.getWriter().write(response.getBody());
        } catch (BimserverDatabaseException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    } catch (OAuthProblemException e) {
        OAuthResponse response;
        try {
            response = OAuthServerRegistrationResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildJSONMessage();
            httpResponse.setStatus(response.getResponseStatus());
            httpResponse.getWriter().write(response.getBody());
        } catch (OAuthSystemException e1) {
            e1.printStackTrace();
        }
    } catch (OAuthSystemException e) {
        e.printStackTrace();
    }
}
Also used : DatabaseSession(org.bimserver.database.DatabaseSession) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) GregorianCalendar(java.util.GregorianCalendar) OAuthServer(org.bimserver.models.store.OAuthServer) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) URL(java.net.URL) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) ServletException(javax.servlet.ServletException) ServiceException(org.bimserver.shared.exceptions.ServiceException) IOException(java.io.IOException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) JSONHttpServletRequestWrapper(org.apache.oltu.oauth2.ext.dynamicreg.server.request.JSONHttpServletRequestWrapper) ServiceException(org.bimserver.shared.exceptions.ServiceException) OAuthServerRegistrationRequest(org.apache.oltu.oauth2.ext.dynamicreg.server.request.OAuthServerRegistrationRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator)

Example 17 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project BIMserver by opensourceBIM.

the class OAuthAuthorizationServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    OAuthAuthzRequest oauthRequest = null;
    String authType = request.getParameter("auth_type");
    if (request.getParameter("token") == null) {
        String location = "/apps/bimviews/?page=OAuth&auth_type=" + authType + "&client_id=" + request.getParameter("client_id") + "&response_type=" + request.getParameter("response_type") + "&redirect_uri=" + request.getParameter("redirect_uri");
        if (request.getParameter("state") != null) {
            String state = request.getParameter("state");
            LOGGER.info("Incoming state: " + state);
            String encodedState = UrlEscapers.urlFragmentEscaper().escape(state);
            LOGGER.info("Encoded state: " + encodedState);
            location += "&state=" + encodedState;
        }
        LOGGER.info("Redirecting to " + location);
        httpServletResponse.sendRedirect(location);
        return;
    }
    OAuthAuthorizationCode oauthCode = null;
    String token = request.getParameter("token");
    try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY)) {
        OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_ClientId(), request.getParameter("client_id"));
        org.bimserver.webservices.authorization.Authorization realAuth = org.bimserver.webservices.authorization.Authorization.fromToken(getBimServer().getEncryptionKey(), token);
        long uoid = realAuth.getUoid();
        User user = session.get(uoid, OldQuery.getDefault());
        for (OAuthAuthorizationCode oAuthAuthorizationCode : user.getOAuthIssuedAuthorizationCodes()) {
            if (oAuthAuthorizationCode.getOauthServer() == oAuthServer) {
                if (oAuthAuthorizationCode.getAuthorization() != null) {
                    oauthCode = oAuthAuthorizationCode;
                }
            }
        }
        try {
            if (oauthCode == null) {
                throw new ServletException("No auth found for token " + token);
            }
            oauthRequest = new OAuthAuthzRequest(request);
            String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
            OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
            if (responseType.equals(ResponseType.CODE.toString())) {
                builder.setCode(oauthCode.getCode());
            // } else if (responseType.equals(ResponseType.TOKEN))) {
            // builder.setAccessToken(oauthCode.get)
            }
            // if (responseType.equals(ResponseType.TOKEN.toString())) {
            // builder.setAccessToken(oauthIssuerImpl.accessToken());
            // // builder.setTokenType(OAuth.DEFAULT_TOKEN_TYPE.toString());
            // builder.setExpiresIn(3600l);
            // }
            String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
            if (redirectURI != null && !redirectURI.equals("")) {
                if (redirectURI.equals("SHOW_CODE")) {
                    httpServletResponse.getWriter().write("Service token (copy&paste this into your application): <br/><br/><input type=\"text\" style=\"width: 1000px\" value=\"" + oauthCode.getCode() + "\"/><br/><br/>");
                    RunServiceAuthorization auth = (RunServiceAuthorization) oauthCode.getAuthorization();
                    String siteAddress = getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress();
                    httpServletResponse.getWriter().write("Service address: <br/><br/><input type=\"text\" style=\"width: 1000px\" value=\"" + siteAddress + "/services/" + auth.getService().getOid() + "\"/><br/><br/>");
                } else {
                    URI uri = makeUrl(redirectURI, oauthCode, builder);
                    LOGGER.info("Redirecting to " + uri);
                    httpServletResponse.sendRedirect(uri.toString());
                }
            } else {
                URI uri = makeUrl("http://fakeaddress", oauthCode, builder);
                httpServletResponse.getWriter().println("No redirectURI provided");
                httpServletResponse.getWriter().println("Would have redirected to: " + uri);
            }
        } catch (OAuthProblemException e) {
            final Response.ResponseBuilder responseBuilder = Response.status(HttpServletResponse.SC_FOUND);
            String redirectUri = e.getRedirectUri();
            if (OAuthUtils.isEmpty(redirectUri)) {
                throw new WebApplicationException(responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build());
            }
            try {
                OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
                // final URI location = new URI(response.getLocationUri());
                httpServletResponse.sendRedirect(response.getLocationUri());
            } catch (OAuthSystemException e1) {
                e1.printStackTrace();
            }
        }
    } catch (OAuthSystemException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (BimserverLockConflictException e2) {
        e2.printStackTrace();
    } catch (BimserverDatabaseException e2) {
        e2.printStackTrace();
    } catch (AuthenticationException e2) {
        e2.printStackTrace();
    }
}
Also used : User(org.bimserver.models.store.User) WebApplicationException(javax.ws.rs.WebApplicationException) DatabaseSession(org.bimserver.database.DatabaseSession) AuthenticationException(org.bimserver.webservices.authorization.AuthenticationException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) RunServiceAuthorization(org.bimserver.models.store.RunServiceAuthorization) URISyntaxException(java.net.URISyntaxException) OAuthServer(org.bimserver.models.store.OAuthServer) OAuthAuthorizationResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthAuthorizationResponseBuilder) URI(java.net.URI) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) ServletException(javax.servlet.ServletException) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) OAuthAuthorizationResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthAuthorizationResponseBuilder) BimserverLockConflictException(org.bimserver.database.BimserverLockConflictException) OAuthAuthorizationCode(org.bimserver.models.store.OAuthAuthorizationCode)

Example 18 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project BIMserver by opensourceBIM.

the class URLConnectionClient method execute.

public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
    InputStream responseBody = null;
    URLConnection c;
    Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
    int responseCode;
    try {
        URL url = new URL(request.getLocationUri());
        c = url.openConnection();
        responseCode = -1;
        if (c instanceof HttpURLConnection) {
            HttpURLConnection httpURLConnection = (HttpURLConnection) c;
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> header : headers.entrySet()) {
                    httpURLConnection.addRequestProperty(header.getKey(), header.getValue());
                }
            }
            if (request.getHeaders() != null) {
                for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
                    httpURLConnection.addRequestProperty(header.getKey(), header.getValue());
                }
            }
            if (OAuthUtils.isEmpty(requestMethod)) {
                httpURLConnection.setRequestMethod(OAuth.HttpMethod.GET);
            } else {
                httpURLConnection.setRequestMethod(requestMethod);
                setRequestBody(request, requestMethod, httpURLConnection);
            }
            httpURLConnection.connect();
            InputStream inputStream;
            responseCode = httpURLConnection.getResponseCode();
            if (responseCode == SC_BAD_REQUEST || responseCode == SC_UNAUTHORIZED) {
                inputStream = httpURLConnection.getErrorStream();
            } else {
                inputStream = httpURLConnection.getInputStream();
            }
            responseHeaders = httpURLConnection.getHeaderFields();
            responseBody = inputStream;
        }
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
    return OAuthClientResponseFactory.createCustomResponse(responseBody, c.getContentType(), responseCode, responseHeaders, responseClass);
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 19 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project android-client by GenesisVision.

the class OAuthOkHttpClient method execute.

public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);
    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), response.headers().toMultimap(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : OAuthClientResponse(org.apache.oltu.oauth2.client.response.OAuthClientResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) MediaType(okhttp3.MediaType) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 20 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project incubator-gobblin by apache.

the class SalesforceRestWriter method onConnect.

/**
 * Retrieve access token, if needed, retrieve instance url, and set server host URL
 * {@inheritDoc}
 * @see org.apache.gobblin.writer.http.HttpWriter#onConnect(org.apache.http.HttpHost)
 */
@Override
public void onConnect(URI serverHost) throws IOException {
    if (!StringUtils.isEmpty(accessToken)) {
        // No need to be called if accessToken is active.
        return;
    }
    try {
        getLog().info("Getting Oauth2 access token.");
        OAuthClientRequest request = OAuthClientRequest.tokenLocation(serverHost.toString()).setGrantType(GrantType.PASSWORD).setClientId(clientId).setClientSecret(clientSecret).setUsername(userId).setPassword(password + securityToken).buildQueryMessage();
        OAuthClient client = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse response = client.accessToken(request, OAuth.HttpMethod.POST);
        accessToken = response.getAccessToken();
        setCurServerHost(new URI(response.getParam("instance_url")));
    } catch (OAuthProblemException e) {
        throw new NonTransientException("Error while authenticating with Oauth2", e);
    } catch (OAuthSystemException e) {
        throw new RuntimeException("Failed getting access token", e);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Failed due to invalid instance url", e);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) NonTransientException(org.apache.gobblin.exception.NonTransientException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) URISyntaxException(java.net.URISyntaxException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)57 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)50 IOException (java.io.IOException)37 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)32 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)21 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)16 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)14 MediaType (okhttp3.MediaType)13 RequestBody (okhttp3.RequestBody)13 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)13 Map (java.util.Map)12 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 URI (java.net.URI)11 URLConnectionClient (org.apache.oltu.oauth2.client.URLConnectionClient)10 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)10