Search in sources :

Example 6 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-test-integration by wso2-incubator.

the class LoginProxy method handleCallback.

/**
 * this is the method, which gets fired when the identity server returns back the authorization code, after
 * authenticating the user. in addition to the authorization code, the response from the identity server must also
 * include the state parameter, which contains the value we set when we initiate the authorization grant.
 *
 * @param code the authorization code generated by the identity server. the proxy application will exchange this
 *            token to get an access token from the identity server.
 * @param state this is the same value we set as state, when we initiate the authorization grant request to the
 *            identity server.
 * @return
 */
@Path("callback")
@GET
public Response handleCallback(@QueryParam("code") String code, @QueryParam("state") String state) {
    if (code == null || code.isEmpty()) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "The value of the code cannot be null.");
    }
    if (state == null || state.isEmpty()) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "The value of the state cannot be null.");
    }
    HttpServletResponse resp = context.getHttpServletResponse();
    HttpServletRequest req = context.getHttpServletRequest();
    Cookie[] cookies = req.getCookies();
    String spaName = null;
    // try to load the cookie corresponding to the value of the state.
    if (cookies != null && cookies.length > 0) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(state)) {
                spaName = cookies[i].getValue();
                break;
            }
        }
    }
    if (spaName == null) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "No valid cookie found.");
    }
    // loads the client key corresponding to the SPA. you do not need to have SPA specific consumer keys, rather
    // can use one client key for all the SPAs. you get the consumer key from the identity server, at the time you
    // register the service provider, and configure it in oauth_proxy.properties file.
    String consumerKey = ProxyUtils.getConsumerKey(spaName);
    // loads the client secret corresponding to the SPA. you do not need to have SPA specific client secret, rather
    // can use one client secret for all the SPAs. you get the client secret from the identity server, at the time
    // you register the service provider, and configure it in oauth_proxy.properties file.
    String consumerSecret = ProxyUtils.getConsumerSecret(spaName);
    // this is the OAuth 2.0 token end-point of the identity server.
    String tokenEndpoint = ProxyUtils.getTokenEp();
    // load the callback URL of the proxy. there is only one callback URL. even when you create multiple service
    // providers in identity server to get multiple client key/client secret pairs, the callback URL would be the
    // same.
    String callbackUrl = ProxyUtils.getCallbackUrl();
    OAuthClientRequest accessRequest = null;
    try {
        // create an OAuth 2.0 token request.
        accessRequest = OAuthClientRequest.tokenLocation(tokenEndpoint).setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(consumerKey).setClientSecret(consumerSecret).setRedirectURI(callbackUrl).setCode(code).buildBodyMessage();
    } catch (OAuthSystemException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    // create an OAuth 2.0 client that uses custom HTTP client under the hood
    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
    OAuthClientResponse oAuthResponse = null;
    try {
        // talk to the OAuth token end-point of identity server to get the OAuth access token, refresh token and id
        // token.
        oAuthResponse = oAuthClient.accessToken(accessRequest);
    } catch (OAuthSystemException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (OAuthProblemException e) {
        log.error(e);
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    // read the access token from the OAuth token end-point response.
    String accessToken = oAuthResponse.getParam(ProxyUtils.ACCESS_TOKEN);
    // read the refresh token from the OAuth token end-point response.
    String refreshToken = oAuthResponse.getParam(ProxyUtils.REFRESH_TOKEN);
    // read the expiration from the OAuth token endpoint response.
    long expiration = Long.parseLong(oAuthResponse.getParam(ProxyUtils.EXPIRATION));
    // read the id token from the OAuth token end-point response.
    String idToken = oAuthResponse.getParam(ProxyUtils.ID_TOKEN);
    if (idToken != null) {
        // extract out the content of the JWT, which comes in the id token.
        String[] idTkElements = idToken.split(Pattern.quote("."));
        idToken = idTkElements[1];
    }
    // create a JSON object aggregating OAuth access token, refresh token and id token
    JSONObject json = new JSONObject();
    try {
        json.put(ProxyUtils.ID_TOKEN, idToken);
        json.put(ProxyUtils.ACCESS_TOKEN, accessToken);
        json.put(ProxyUtils.REFRESH_TOKEN, refreshToken);
        json.put(ProxyUtils.SPA_NAME, spaName);
        json.put(ProxyUtils.EXPIRATION, new Long(expiration));
    } catch (JSONException e) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    try {
        // encrypt the JSON message.
        String encryptedCookieValue = ProxyUtils.encrypt(json.toString());
        // create a cookie under the proxy domain with the encrypted message. cookie name is set to the value of the
        // code, initially passed by the SPA.
        Cookie cookie = new Cookie(state, encryptedCookieValue);
        // the cookie is only accessible by the HTTPS transport.
        cookie.setSecure(true);
        // add cookie to the response.
        resp.addCookie(cookie);
        // get the SPA callback URL. each SPA has its own callback URL, which is defined in the
        // oauth_proxy.properties file
        resp.sendRedirect(ProxyUtils.getSpaCallbackUrl(spaName));
        return null;
    } catch (Exception e) {
        return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Also used : Cookie(javax.servlet.http.Cookie) OAuthClient(org.apache.amber.oauth2.client.OAuthClient) OAuthSystemException(org.apache.amber.oauth2.common.exception.OAuthSystemException) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONException(org.codehaus.jettison.json.JSONException) OAuthClientResponse(org.apache.amber.oauth2.client.response.OAuthClientResponse) OAuthSystemException(org.apache.amber.oauth2.common.exception.OAuthSystemException) OAuthProblemException(org.apache.amber.oauth2.common.exception.OAuthProblemException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthProblemException(org.apache.amber.oauth2.common.exception.OAuthProblemException) URLConnectionClient(org.apache.amber.oauth2.client.URLConnectionClient) JSONObject(org.codehaus.jettison.json.JSONObject) OAuthClientRequest(org.apache.amber.oauth2.client.request.OAuthClientRequest) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 7 with OAuthSystemException

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

the class OAuthAccessTokenServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    OAuthTokenRequest oauthRequest = null;
    OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
    if (!request.getContentType().equals("application/x-www-form-urlencoded")) {
        response.setStatus(405);
        PrintWriter pw = response.getWriter();
        pw.print("ContentType must be application/x-www-form-urlencoded");
        pw.flush();
        pw.close();
        return;
    }
    try {
        oauthRequest = new OAuthTokenRequest(request);
        OAuthAuthorizationCode code = null;
        try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY)) {
            String codeAsString = oauthRequest.getCode();
            code = session.querySingle(StorePackage.eINSTANCE.getOAuthAuthorizationCode_Code(), codeAsString);
            validateClient(oauthRequest);
            String resourceUrl = "";
            Authorization auth = code.getAuthorization();
            org.bimserver.webservices.authorization.Authorization authorization = null;
            if (auth instanceof SingleProjectAuthorization) {
                SingleProjectAuthorization singleProjectAuthorization = (SingleProjectAuthorization) auth;
                authorization = new org.bimserver.webservices.authorization.SingleProjectAuthorization(getBimServer(), code.getUser().getOid(), singleProjectAuthorization.getProject().getOid());
            } else if (auth instanceof RunServiceAuthorization) {
                RunServiceAuthorization runServiceAuthorization = (RunServiceAuthorization) auth;
                authorization = new org.bimserver.webservices.authorization.RunServiceAuthorization(getBimServer(), code.getUser().getOid(), runServiceAuthorization.getService().getOid());
                resourceUrl = getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress() + "/services/" + runServiceAuthorization.getService().getOid();
            } else {
                throw new Exception("Unknown auth");
            }
            String accessToken = authorization.asHexToken(getBimServer().getEncryptionKey());
            String refreshToken = oauthIssuerImpl.refreshToken();
            OAuthTokenResponseBuilder builder = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setExpiresIn("3600").setRefreshToken(refreshToken);
            builder.setParam("resource_url", resourceUrl);
            if (auth instanceof SingleProjectAuthorization) {
                builder.setParam("poid", "" + ((SingleProjectAuthorization) code.getAuthorization()).getProject().getOid());
            } else if (auth instanceof RunServiceAuthorization) {
                builder.setParam("soid", "" + ((RunServiceAuthorization) code.getAuthorization()).getService().getOid());
            }
            OAuthResponse r = builder.buildJSONMessage();
            response.setStatus(r.getResponseStatus());
            response.setContentType("application/json");
            PrintWriter pw = response.getWriter();
            pw.print(r.getBody());
            pw.flush();
            pw.close();
        } catch (BimserverDatabaseException e) {
            LOGGER.error("", e);
        }
    } catch (OAuthProblemException ex) {
        LOGGER.error("", ex);
        try {
            OAuthResponse r = OAuthResponse.errorResponse(401).error(ex).buildJSONMessage();
            response.setStatus(r.getResponseStatus());
            PrintWriter pw = response.getWriter();
            pw.print(r.getBody());
            pw.flush();
            pw.close();
        } catch (OAuthSystemException e) {
            LOGGER.error("", ex);
        }
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}
Also used : DatabaseSession(org.bimserver.database.DatabaseSession) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthTokenRequest(org.apache.oltu.oauth2.as.request.OAuthTokenRequest) SingleProjectAuthorization(org.bimserver.models.store.SingleProjectAuthorization) RunServiceAuthorization(org.bimserver.models.store.RunServiceAuthorization) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) Authorization(org.bimserver.models.store.Authorization) RunServiceAuthorization(org.bimserver.models.store.RunServiceAuthorization) SingleProjectAuthorization(org.bimserver.models.store.SingleProjectAuthorization) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) OAuthTokenResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthIssuer(org.apache.oltu.oauth2.as.issuer.OAuthIssuer) OAuthAuthorizationCode(org.bimserver.models.store.OAuthAuthorizationCode) PrintWriter(java.io.PrintWriter)

Example 8 with OAuthSystemException

use of org.apache.amber.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 9 with OAuthSystemException

use of org.apache.amber.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 10 with OAuthSystemException

use of org.apache.amber.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)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)100 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)47 IOException (java.io.IOException)37 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)36 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)20 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)17 Map (java.util.Map)15 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)15 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)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)11 Path (javax.ws.rs.Path)10 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)9 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)9 HashMap (java.util.HashMap)8