Search in sources :

Example 26 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project mbed-cloud-sdk-java by ARMmbed.

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(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : Builder(okhttp3.Request.Builder) 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 27 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project mbed-cloud-sdk-java by ARMmbed.

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(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : Builder(okhttp3.Request.Builder) 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 28 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project mbed-cloud-sdk-java by ARMmbed.

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(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : Builder(okhttp3.Request.Builder) 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 29 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project entando-core by entando.

the class ApiRestServer method extractOAuthParameters.

protected void extractOAuthParameters(HttpServletRequest request, String permission) throws ApiException {
    try {
        _logger.info("Permission required: {}", permission);
        OAuthAccessResourceRequest requestMessage = new OAuthAccessResourceRequest(request, ParameterStyle.HEADER);
        // Get the access token
        String accessToken = requestMessage.getAccessToken();
        IApiOAuth2TokenManager tokenManager = (IApiOAuth2TokenManager) ApsWebApplicationUtils.getBean(IApiOAuth2TokenManager.BEAN_NAME, request);
        final OAuth2Token token = tokenManager.getApiOAuth2Token(accessToken);
        if (token != null) {
            // Validate the access token
            if (!token.getAccessToken().equals(accessToken)) {
                throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Token does not match", Response.Status.UNAUTHORIZED);
            } else // check if access token is expired
            if (token.getExpiresIn().getTime() < System.currentTimeMillis()) {
                throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Token expired", Response.Status.UNAUTHORIZED);
            }
            String username = token.getClientId();
            IUserManager userManager = (IUserManager) ApsWebApplicationUtils.getBean(SystemConstants.USER_MANAGER, request);
            UserDetails user = userManager.getUser(username);
            if (user != null) {
                _logger.info("User {} requesting resource that requires {} permission ", username, permission);
                request.getSession().setAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER, user);
                if (permission != null) {
                    IAuthorizationManager authManager = (IAuthorizationManager) ApsWebApplicationUtils.getBean(SystemConstants.AUTHORIZATION_SERVICE, request);
                    user.addAuthorizations(authManager.getUserAuthorizations(username));
                    if (!authManager.isAuthOnPermission(user, permission)) {
                        List<Role> roles = authManager.getUserRoles(user);
                        for (Role role : roles) {
                            _logger.info("User {} requesting resource has {} permission ", username, role.getPermissions().toArray()[0]);
                        }
                        _logger.info("User {} requesting resource has {} permission ", username, "none");
                        throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Authentication Required", Response.Status.UNAUTHORIZED);
                    }
                }
            }
        } else {
            if (accessToken != null) {
                throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Token not found, request new one", Response.Status.UNAUTHORIZED);
            }
            throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Authentication Required", Response.Status.UNAUTHORIZED);
        }
    } catch (OAuthSystemException | ApsSystemException | OAuthProblemException ex) {
        _logger.error("System exception {}", ex);
        throw new ApiException(IApiErrorCodes.SERVER_ERROR, ex.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : OAuthAccessResourceRequest(org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest) IUserManager(com.agiletec.aps.system.services.user.IUserManager) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2Token(org.entando.entando.aps.system.services.oauth2.model.OAuth2Token) ApsSystemException(com.agiletec.aps.system.exception.ApsSystemException) IAuthorizationManager(com.agiletec.aps.system.services.authorization.IAuthorizationManager) Role(com.agiletec.aps.system.services.role.Role) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) UserDetails(com.agiletec.aps.system.services.user.UserDetails) IApiOAuth2TokenManager(org.entando.entando.aps.system.services.oauth2.IApiOAuth2TokenManager)

Example 30 with OAuthProblemException

use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project entando-core by entando.

the class AuthEndpointServlet method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    OAuthAuthzRequest oauthRequest = null;
    OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
    IApiOAuthorizationCodeManager codeManager = (IApiOAuthorizationCodeManager) ApsWebApplicationUtils.getBean(SystemConstants.OAUTH2_AUTHORIZATION_CODE_MANAGER, request);
    try {
        oauthRequest = new OAuthAuthzRequest(request);
        if (validateClient(oauthRequest, request, response)) {
            // build response according to response_type
            String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE) == null ? OAuth.OAUTH_RESPONSE_TYPE : oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
            OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
            final String authorizationCode = oauthIssuerImpl.authorizationCode();
            final int expires = 3;
            AuthorizationCode authCode = new AuthorizationCode();
            authCode.setAuthorizationCode(authorizationCode);
            // gets a calendar using the default time zone and locale.
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND, expires);
            authCode.setExpires(calendar.getTimeInMillis());
            authCode.setClientId(oauthRequest.getClientId());
            authCode.setSource(request.getRemoteAddr());
            codeManager.addAuthorizationCode(authCode);
            if (responseType.equals(ResponseType.CODE.toString())) {
                builder.setCode(authorizationCode);
            }
            if (responseType.equals(ResponseType.TOKEN.toString())) {
                builder.setAccessToken(authorizationCode);
                builder.setExpiresIn((long) expires);
            }
            String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
            final OAuthResponse resp = builder.location(redirectURI).buildQueryMessage();
            final int status = resp.getResponseStatus();
            response.setStatus(status);
            response.sendRedirect(resp.getLocationUri());
        } else {
            logger.warn("OAuth2 authentication failed");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (OAuthSystemException ex) {
        logger.error("System exception {} ", ex.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (OAuthProblemException ex) {
        logger.error("OAuth2 error {} ", ex.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (IOException e) {
        logger.error("IOException {} ", e);
    }
}
Also used : AuthorizationCode(org.entando.entando.aps.system.services.oauth2.model.AuthorizationCode) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Calendar(java.util.Calendar) IOException(java.io.IOException) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) IApiOAuthorizationCodeManager(org.entando.entando.aps.system.services.oauth2.IApiOAuthorizationCodeManager) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)24 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)20 IOException (java.io.IOException)15 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)15 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)12 MediaType (okhttp3.MediaType)9 Request (okhttp3.Request)9 RequestBody (okhttp3.RequestBody)9 Response (okhttp3.Response)9 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)9 Builder (okhttp3.Request.Builder)8 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)8 URI (java.net.URI)6 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)5 OAuthAccessResourceRequest (org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest)5 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)4 OAuthAuthzResponse (org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)4 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)4 AccessToken (io.github.tesla.authz.domain.AccessToken)3 ServletException (javax.servlet.ServletException)3