Search in sources :

Example 1 with MD5Generator

use of org.apache.oltu.oauth2.as.issuer.MD5Generator 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()) {
            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 2 with MD5Generator

use of org.apache.oltu.oauth2.as.issuer.MD5Generator 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()) {
            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 3 with MD5Generator

use of org.apache.oltu.oauth2.as.issuer.MD5Generator in project entando-core by entando.

the class TokenEndpointServlet method registerToken.

private OAuthResponse registerToken(HttpServletRequest request, final String clientId, final String oauthType, final String localUser) throws OAuthSystemException, ApsSystemException {
    int expires = 3600;
    IApiOAuth2TokenManager tokenManager = (IApiOAuth2TokenManager) ApsWebApplicationUtils.getBean(IApiOAuth2TokenManager.BEAN_NAME, request);
    OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
    final String accessToken = oauthIssuerImpl.accessToken();
    final String refreshToken = oauthIssuerImpl.refreshToken();
    OAuth2Token oAuth2Token = new OAuth2Token();
    oAuth2Token.setAccessToken(accessToken);
    oAuth2Token.setRefreshToken(refreshToken);
    oAuth2Token.setClientId(clientId);
    // gets a calendar using the default time zone and locale.
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, expires);
    oAuth2Token.setExpiresIn(calendar.getTime());
    oAuth2Token.setGrantType(oauthType);
    if (localUser == null) {
        tokenManager.addApiOAuth2Token(oAuth2Token, false);
    } else {
        oAuth2Token.setLocalUser(localUser);
        tokenManager.addApiOAuth2Token(oAuth2Token, true);
    }
    return OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setExpiresIn(Long.toString(expires)).setRefreshToken(refreshToken).buildJSONMessage();
}
Also used : OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) Calendar(java.util.Calendar) OAuth2Token(org.entando.entando.aps.system.services.oauth2.model.OAuth2Token) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthIssuer(org.apache.oltu.oauth2.as.issuer.OAuthIssuer) IApiOAuth2TokenManager(org.entando.entando.aps.system.services.oauth2.IApiOAuth2TokenManager)

Example 4 with MD5Generator

use of org.apache.oltu.oauth2.as.issuer.MD5Generator in project entando-core by entando.

the class AuthenticationProviderManager method registerToken.

private void registerToken(final UserDetails user) {
    OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
    try {
        final String accessToken = oauthIssuerImpl.accessToken();
        final String refreshToken = oauthIssuerImpl.refreshToken();
        user.setAccessToken(accessToken);
        user.setRefreshToken(refreshToken);
        final OAuth2Token oAuth2Token = new OAuth2Token();
        oAuth2Token.setAccessToken(accessToken);
        oAuth2Token.setRefreshToken(refreshToken);
        oAuth2Token.setClientId("LOCAL_USER");
        oAuth2Token.setLocalUser(user.getUsername());
        // gets a calendar using the default time zone and locale.
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 3600);
        oAuth2Token.setExpiresIn(calendar.getTime());
        oAuth2Token.setGrantType(GrantType.IMPLICIT.toString());
        tokenManager.addApiOAuth2Token(oAuth2Token, true);
    } catch (OAuthSystemException e) {
        _logger.error("OAuthSystemException {} ", e.getMessage());
        _logger.debug("OAuthSystemException {} ", e);
    } catch (ApsSystemException e) {
        _logger.error("ApsSystemException {} ", e.getMessage());
        _logger.debug("ApsSystemException {} ", e);
    }
}
Also used : OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Calendar(java.util.Calendar) OAuth2Token(org.entando.entando.aps.system.services.oauth2.model.OAuth2Token) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) ApsSystemException(com.agiletec.aps.system.exception.ApsSystemException) OAuthIssuer(org.apache.oltu.oauth2.as.issuer.OAuthIssuer)

Example 5 with MD5Generator

use of org.apache.oltu.oauth2.as.issuer.MD5Generator 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

MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)5 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)4 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)4 IOException (java.io.IOException)3 Calendar (java.util.Calendar)3 OAuthIssuer (org.apache.oltu.oauth2.as.issuer.OAuthIssuer)3 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)3 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)3 ServletException (javax.servlet.ServletException)2 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)2 DatabaseSession (org.bimserver.database.DatabaseSession)2 OAuth2Token (org.entando.entando.aps.system.services.oauth2.model.OAuth2Token)2 ApsSystemException (com.agiletec.aps.system.exception.ApsSystemException)1 PrintWriter (java.io.PrintWriter)1 URL (java.net.URL)1 GregorianCalendar (java.util.GregorianCalendar)1 OAuthAuthzRequest (org.apache.oltu.oauth2.as.request.OAuthAuthzRequest)1 OAuthTokenRequest (org.apache.oltu.oauth2.as.request.OAuthTokenRequest)1 OAuthASResponse (org.apache.oltu.oauth2.as.response.OAuthASResponse)1 OAuthTokenResponseBuilder (org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder)1