Search in sources :

Example 1 with OAuthIssuerImpl

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

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

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

use of org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl in project dq-easy-cloud by dq-open-cloud.

the class EcAuthorizeController method token.

@RequestMapping("/accessToken")
public HttpEntity token(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    // http://localhost:8100/authorize/accessToken?code=4d9e143db54db03d215161f207346cb6&grant_type=authorization_code&redirect_uri=https://www.baidu.com&client_secret=1&client_id=2
    try {
        // 构建OAuth请求
        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
        boolean checkClient = false;
        // 检查提交的客户端id是否正确
        if (checkClient) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription("异常").buildJSONMessage();
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        // 检查客户端安全KEY是否正确
        // checkClient = !oAuthService.checkClientSecret(oauthRequest.getClientSecret())
        String clientSecret = oauthRequest.getClientSecret();
        if ("".equals(clientSecret)) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT).setErrorDescription("secret有误").buildJSONMessage();
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
        // 检查验证类型,此处只检查AUTHORIZATION_CODE类型,其他的还有PASSWORD或REFRESH_TOKEN
        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            // if (!oAuthService.checkAuthCode(authCode)) {
            if (!codeCache.containsKey(authCode)) {
                OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_GRANT).setErrorDescription("错误的授权码").buildJSONMessage();
                return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
            }
        }
        // 生成Access Token
        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        final String accessToken = oauthIssuerImpl.accessToken();
        final String refreshToken = oauthIssuerImpl.refreshToken();
        // oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));
        tokenCache.put(accessToken, codeCache.get(authCode));
        // 生成OAuth响应
        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setRefreshToken(refreshToken).setExpiresIn(String.valueOf(7200)).setTokenType(TokenType.BEARER.toString()).buildJSONMessage();
        // 根据OAuthResponse生成ResponseEntity
        return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        logger.error(e.getMessage(), e);
        // 构建错误响应
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildJSONMessage();
        return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) ResponseEntity(org.springframework.http.ResponseEntity) OAuthTokenRequest(org.apache.oltu.oauth2.as.request.OAuthTokenRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthIssuer(org.apache.oltu.oauth2.as.issuer.OAuthIssuer) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with OAuthIssuerImpl

use of org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl 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)6 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)6 OAuthIssuer (org.apache.oltu.oauth2.as.issuer.OAuthIssuer)4 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)4 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)4 Calendar (java.util.Calendar)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)3 IOException (java.io.IOException)2 OAuthAuthzRequest (org.apache.oltu.oauth2.as.request.OAuthAuthzRequest)2 OAuthTokenRequest (org.apache.oltu.oauth2.as.request.OAuthTokenRequest)2 OAuthASResponse (org.apache.oltu.oauth2.as.response.OAuthASResponse)2 OAuth2Token (org.entando.entando.aps.system.services.oauth2.model.OAuth2Token)2 ResponseEntity (org.springframework.http.ResponseEntity)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 ApsSystemException (com.agiletec.aps.system.exception.ApsSystemException)1 PrintWriter (java.io.PrintWriter)1 URI (java.net.URI)1 ServletException (javax.servlet.ServletException)1 OAuthTokenResponseBuilder (org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder)1 Subject (org.apache.shiro.subject.Subject)1