Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

In this page you can find the example usage for java.lang SecurityException SecurityException.

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.onecmdb.core.utils.wsdl.OneCMDBWebServiceImpl.java

public int searchCount(String auth, QueryCriteria criteria) {
    long start = System.currentTimeMillis();
    log.info("WSDL: searchCount(" + auth + ", " + criteria + ")");

    ISession session = onecmdb.getSession(auth);
    if (session == null) {
        throw new SecurityException("No Session found! Try to do auth() first!");
    }//from   w w  w. j  a v  a 2s.c  om
    IModelService mService = (IModelService) session.getService(IModelService.class);
    int count = mService.queryCount(criteria);

    long stop = System.currentTimeMillis();
    log.info("WSDL: searchCount completed in " + (stop - start) + "ms returned + " + count);

    return (count);
}

From source file:org.dhatim.dropwizard.jwt.cookie.authentication.JwtCookieAuthBundle.java

private static KeyGenerator getHmacSha256KeyGenerator() {
    try {// w  w  w. ja  v  a2 s .c  o m
        return KeyGenerator.getInstance(HS256.getJcaName());
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(e);
    }
}

From source file:org.jactr.tools.async.controller.RemoteIOHandler.java

final public void allowsCommands(IoSession session) {
    if (!isOwner(session)) {
        String message = session + " is not allowed to send commands, disconnecting ";
        SecurityException e = new SecurityException(message);
        if (LOGGER.isWarnEnabled())
            LOGGER.warn(message, e);/*www.  j  a  v a 2s . co  m*/
        throw e;
    }
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * ?//from  w w  w.  ja va 2 s  .c  o  m
 * 
 * @param ctx
 *            
 * @return key
 */
public static Key generateSecretKey(SecurityContext ctx) {
    try {
        KeyGenerator skg = KeyGenerator.getInstance(ctx.getSymmetryKeyAlgorithm(), ctx.getJceProvider());
        SecureRandom secureRandom = SecureRandom.getInstance(ctx.getSecureRandomAlgorithm());
        skg.init(ctx.getSymmetryKeySize(), secureRandom);
        SecretKey key = skg.generateKey();
        return key;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}

From source file:org.kawanfw.file.servlet.ServerCallAction.java

/**
 * /* w w w  . j  av  a2  s  .  c  o m*/
 * Calls a remote method from the client side <br>
 * Please note that all invocation are trapped and routed as code string to
 * the client side.
 * 
 * @param request
 *            the http request
 * @param commonsConfigurator
 *            the commons configurator defined by the user
 * @param fileConfigurator
 *            the file configurator defined by the user
 * @param out
 *            the servlet output stream
 * @param username
 *            the client login (for security check)
 * 
 * 
 * @throws IOException
 *             all framework, network, etc. errors
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException
 */
public void call(HttpServletRequest request, CommonsConfigurator commonsConfigurator,
        FileConfigurator fileConfigurator, OutputStream out, String username) throws SQLException, IOException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,
        IllegalArgumentException, InvocationTargetException, Exception {

    Connection connection = null;

    try {

        debug("in actionCall");

        // The method name
        String methodName = request.getParameter(Parameter.METHOD_NAME);

        // The parms name
        String paramsTypes = request.getParameter(Parameter.PARAMS_TYPES);
        String paramsValues = request.getParameter(Parameter.PARAMS_VALUES);

        // Make sure all values are not null and trimed

        methodName = StringUtil.getTrimValue(methodName);
        paramsTypes = StringUtil.getTrimValue(paramsTypes);
        paramsValues = StringUtil.getTrimValue(paramsValues);

        if (request instanceof HttpServletRequestConvertor) {
            debug("request instanceof HttpServletRequestConvertor");
        } else {
            debug("request NOT instanceof HttpServletRequestConvertor");
        }

        debug("methodName: " + methodName);
        debug("username  : " + username);

        String className = StringUtils.substringBeforeLast(methodName, ".");
        Class<?> c = Class.forName(className);
        CallUtil callUtil = new CallUtil(c, fileConfigurator);
        boolean callAllowed = callUtil.isCallable();

        if (!callAllowed) {
            throw new SecurityException(
                    Tag.PRODUCT_SECURITY + " Class is forbiden for remote call: " + className);
        }

        String action = request.getParameter(Parameter.ACTION);

        // Legacy Action.CALL_ACTION call with Base64 conversion
        // Corresponds to RemoteSession.setUseBase64EncodingForCall()
        // setting
        // on client side
        if (action.equals(Action.CALL_ACTION)) {
            paramsTypes = StringUtil.fromBase64(paramsTypes);
            paramsValues = StringUtil.fromBase64(paramsValues);
        }

        debug("paramsTypes     : " + paramsTypes);
        debug("paramsValues    : " + paramsValues);

        List<String> listParamsTypes = ListOfStringTransport.fromJson(paramsTypes);
        List<String> listParamsValues = ListOfStringTransport.fromJson(paramsValues);

        debug("actionInvokeRemoteMethod:listParamsTypes      : " + listParamsTypes);
        debug("actionInvokeRemoteMethod:listParamsValues     : " + listParamsValues);

        Class<?>[] argTypes = new Class[listParamsTypes.size()];
        Object[] values = new Object[listParamsValues.size()];

        List<Object> valuesList = new Vector<Object>();
        for (int i = 0; i < listParamsTypes.size(); i++) {

            String value = listParamsValues.get(i);
            String javaType = listParamsTypes.get(i);

            JavaValueBuilder javaValueBuilder = new JavaValueBuilder(javaType, value);
            argTypes[i] = javaValueBuilder.getClassOfValue();
            values[i] = javaValueBuilder.getValue();

            // Special treatement if argTypes[i] is a Connection
            if (argTypes[i] == Connection.class) {
                connection = commonsConfigurator.getConnection();
                values[i] = connection;
            }

            valuesList.add(values[i]);
        }

        // Try to get A connection. Will be null if user has not configured a Connection
        try {
            if (connection == null) {
                connection = commonsConfigurator.getConnection();
            }

        } catch (Exception e) {
            debug("commonsConfigurator.getConnection() exception: " + e.toString());
            if (connection != null)
                connection.close();
            connection = null;
        }

        boolean isAllowed = fileConfigurator.allowCallAfterAnalysis(username, connection, methodName,
                valuesList);

        if (!isAllowed) {

            String ipAddress = request.getRemoteAddr();

            // Run the runIfCallDisallowed() configured by the user
            fileConfigurator.runIfCallRefused(username, connection, ipAddress, methodName, valuesList);

            throw new SecurityException(
                    Tag.PRODUCT_SECURITY + " Method not authorized for execution by Security Checker: "
                            + methodName + " parameters: " + valuesList.toString());
        }

        String rawMethodName = StringUtils.substringAfterLast(methodName, ".");

        // Invoke the method
        Object resultObj = null;

        debug("Before  Object theObject = c.newInstance()");
        Object theObject = c.newInstance();

        debug("Before  c.getDeclaredMethod(rawMethodName, argTypes)");
        Method main = c.getDeclaredMethod(rawMethodName, argTypes);

        debug("Before  main.invoke(theObject, values)");
        resultObj = main.invoke(theObject, values);

        String result = null;
        if (resultObj != null)
            result = resultObj.toString();

        debug("result before conversion: " + result);

        if (result != null) {

            // Legacy Action.CALL_ACTION call with Base64 conversion
            // Corresponds to RemoteSession.setUseBase64EncodingForCall()
            // setting on client side
            if (action.equals(Action.CALL_ACTION)) {
                result = StringUtil.toBase64(result);
            } else if (action.equals(Action.CALL_ACTION_HTML_ENCODED)) {
                result = HtmlConverter.toHtml(result);
            } else {
                throw new IllegalArgumentException("call action is invalid: " + action);
            }
        }

        debug("actionInvokeRemoteMethod:result: " + result);

        writeLine(out, TransferStatus.SEND_OK);
        writeLine(out, result);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:it.greenvulcano.gvesb.gviamx.service.internal.EmailChangeManager.java

public EmailChangeRequest retrieveEmailChangeRequest(String email, String token) {

    EmailChangeRequest request = repository.get(email.toLowerCase(), EmailChangeRequest.class)
            .orElseThrow(() -> new IllegalArgumentException("No password reset request found for this email"));

    if (DigestUtils.sha256Hex(token).equals(request.getToken())) {

        if (System.currentTimeMillis() > request.getIssueTime().getTime() + request.getExpireTime()) {
            repository.remove(request);/*from  w ww. ja v  a  2s. c  o  m*/
            throw new SecurityException("No password reset request found for this email");
        }

        return request;

    } else {
        throw new SecurityException("Token missmatch");
    }

}

From source file:be.fedict.trust.xkms2.WSSecurityServerHandler.java

/**
 * Handles the inbound SOAP message. If a WS-Security header is present,
 * will validate body and timestamp being signed. No validation of the
 * embedded certificate will be done./*from w w  w  .j  a  va 2s  .  c o  m*/
 */
@SuppressWarnings("unchecked")
private void handleInboundDocument(SOAPPart document, SOAPMessageContext soapMessageContext) {

    LOG.debug("handle inbound document");

    WSSecurityEngine securityEngine = new WSSecurityEngine();
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    securityEngine.setWssConfig(wssConfig);

    List<WSSecurityEngineResult> wsSecurityEngineResults;
    try {
        wsSecurityEngineResults = securityEngine.processSecurityHeader(document, null, null, null);
    } catch (WSSecurityException e) {
        LOG.debug("WS-Security error: " + e.getMessage(), e);
        throw createSOAPFaultException("The signature or decryption was invalid", "FailedCheck");
    }
    LOG.debug("results: " + wsSecurityEngineResults);
    if (null == wsSecurityEngineResults) {
        LOG.debug("No WS-Security header present");
        return;
    }

    LOG.debug("WS-Security header validation");
    // WS-Security timestamp validation
    WSSecurityEngineResult timeStampActionResult = WSSecurityUtil.fetchActionResult(wsSecurityEngineResults,
            WSConstants.TS);
    if (null == timeStampActionResult) {
        throw new SecurityException("no WS-Security timestamp result");
    }
    Timestamp receivedTimestamp = (Timestamp) timeStampActionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        throw new SecurityException("missing WS-Security timestamp");
    }

    Date created = receivedTimestamp.getCreated();
    DateTime createdDateTime = new DateTime(created);
    Instant createdInstant = createdDateTime.toInstant();
    Instant nowInstant = new DateTime().toInstant();
    long offset = Math.abs(createdInstant.getMillis() - nowInstant.getMillis());
    if (offset > maxWsSecurityTimestampOffset) {
        LOG.debug("timestamp offset: " + offset);
        LOG.debug("maximum allowed offset: " + maxWsSecurityTimestampOffset);
        throw createSOAPFaultException("WS-Security Created Timestamp offset exceeded", "FailedCheck");
    }
}

From source file:org.apache.spark.network.server.OneForOneStreamManager.java

@Override
public void checkAuthorization(TransportClient client, long streamId) {
    if (client.getClientId() != null) {
        StreamState state = streams.get(streamId);
        Preconditions.checkArgument(state != null, "Unknown stream ID.");
        if (!client.getClientId().equals(state.appId)) {
            throw new SecurityException(String.format("Client %s not authorized to read stream %d (app %s).",
                    client.getClientId(), streamId, state.appId));
        }/* w  w w.j  av  a  2 s  .c  o  m*/
    }
}

From source file:cn.newgxu.lab.info.controller.AuthController.java

/**
 * REST APIPUT??/*from  ww w . j  a  va2  s  .  c o  m*/
 * @param session
 * @param uid
 * @param type 
 * @param password
 * @param pwd1
 * @param pwd2
 * @param about
 * @param contact
 * @return only json
 */
@RequestMapping(value = "/users/{uid}", method = RequestMethod.PUT, params = { "modifying_type" })
@ResponseBody
public String modify(HttpSession session, @PathVariable("uid") long uid,
        @RequestParam("password") String password, @RequestParam("modifying_type") String type,
        @RequestParam(value = "pwd1", required = false) String pwd1,
        @RequestParam(value = "pwd2", required = false) String pwd2,
        @RequestParam(value = "about", required = false) String about,
        @RequestParam(value = "contact", required = false) String contact) {
    AuthorizedUser sau = checkLogin(session);
    //      ???
    if (sau.getId() != uid) {
        throw new SecurityException("????");
    }
    //      ????
    authService.login(sau.getAccount(), password, null);

    if (type.equals("password")) {
        sau.setPassword(pwd1);
        authService.resetPassword(sau, pwd2);
    } else if (type.equals("profile")) {
        sau.setContact(contact);
        sau.setAbout(about);
        authService.update(sau);
    } else {
        throw new UnsupportedOperationException("????");
    }
    return ViewConstants.JSON_STATUS_OK;
}

From source file:es.caib.seycon.ng.servei.PuntEntradaServiceImpl.java

/**
 * @see es.caib.seycon.ng.servei.PuntEntradaService#create(es.caib.seycon.ng.comu.PuntEntrada)
 *///w w  w .jav a 2 s  .  c om
protected es.caib.seycon.ng.comu.PuntEntrada handleCreate(es.caib.seycon.ng.comu.PuntEntrada puntEntrada)
        throws java.lang.Exception {
    //
    // VERIFICACIONS:
    //
    Long idPare = puntEntrada.getIdPare();

    // Verificamos que el padre sea de tipo men:
    if (puntEntrada.getIdPare() == null)
        throw new SeyconException(Messages.getString("PuntEntradaServiceImpl.ObtaintParentPointEntryError")); //$NON-NLS-1$

    PuntEntradaEntity pareE = getPuntEntradaEntityDao().findById(puntEntrada.getIdPare());

    if (pareE == null)
        throw new CreateException(Messages.getString("PuntEntradaServiceImpl.ParentMenuNotFounded")); //$NON-NLS-1$
    if (!"S".equals(pareE.getMenu())) { //$NON-NLS-1$
        throw new CreateException(Messages.getString("PuntEntradaServiceImpl.ParentNotAMenu")); //$NON-NLS-1$
    }
    // Verificamos autorizacin del padre
    PuntEntrada pare = getPuntEntradaEntityDao().toPuntEntrada(pareE);
    if (!canAdmin(pare)) {
        throw new SecurityException(
                Messages.getString("PuntEntradaServiceImpl.UnauthorizedtForAdminParentMenu")); //$NON-NLS-1$
    }

    // Si el nou node s de tipus men, verifiquem que tinga indicat el
    // tipus de menu
    // i esborrem les execucions (si existeixen)
    if ("S".equals(puntEntrada.getMenu())) { //$NON-NLS-1$
        if (puntEntrada.getTipusMenu() == null)
            throw new CreateException(Messages.getString("PuntEntradaServiceImpl.MenuTypeMessage")); //$NON-NLS-1$
        puntEntrada.setExecucions(new HashSet()); // esborrem execucions
                                                  // abans de crear entitat
    }

    // Validem el XML si no s buit
    if (puntEntrada.getXmlPUE() != null && !"".equals(puntEntrada.getXmlPUE())) { //$NON-NLS-1$
        String resValida = validaXMLPUE(puntEntrada);
        if (resValida != null && !"".equals(resValida.trim())) //$NON-NLS-1$
            throw new SeyconException(
                    String.format(Messages.getString("PuntEntradaServiceImpl.XMLValidationError"), //$NON-NLS-1$
                            puntEntrada.getNom(), resValida));
    }

    //
    // OBTENIM L'ENTITAT
    //
    PuntEntradaEntity entity = getPuntEntradaEntityDao().puntEntradaToEntity(puntEntrada);

    // CREEM L'ENTITAT (!!)
    getPuntEntradaEntityDao().create(entity);

    // Creem l'ARBRE del punt d'entrada
    int ordre = 0; //$NON-NLS-1$   //String ordre = "0";
    // Obtenim L'ORDRE DE L'ARBRE des dels fills del pare (estan ordenats
    // per ordre ascendent)
    List fills = (List) getArbrePuntEntradaEntityDao().findByPare(puntEntrada.getIdPare());
    if (fills != null) {// Ens quedem en el fill de major ordre
        if (fills.size() == 0) // Para nodes men sense fills
            ordre = 0; //$NON-NLS-1$   //ordre = "0";
        else { // Obtenim el seu fill "major"
            ArbrePuntEntradaEntity fill = (ArbrePuntEntradaEntity) fills.get(fills.size() - 1);
            int ordreFillMajor = fill.getOrdre(); //Integer.parseInt(fill.getOrdre());
            ordre = ordreFillMajor + 1; //$NON-NLS-1$   //"" + (ordreFillMajor + 1);
        }
    }
    ArbrePuntEntradaEntity arbre = getArbrePuntEntradaEntityDao().newArbrePuntEntradaEntity();
    arbre.setOrdre(ordre);
    arbre.setFill(entity);
    arbre.setPare(pareE);
    HashSet<ArbrePuntEntradaEntity> monArbre = new HashSet<ArbrePuntEntradaEntity>();
    monArbre.add(arbre);
    // Establim l'arbre
    entity.setArbrePuntEntradaSocFill(monArbre);

    // Creem les relacions del punt d'entrada
    // Arbre
    getArbrePuntEntradaEntityDao().create(arbre);

    // Creem les icones
    IconaEntity icona1 = null;
    if (puntEntrada.getImgIcona1() != null && puntEntrada.getImgIcona1().length != 0) {
        // Creem l'icona
        icona1 = createIcona(puntEntrada.getImgIcona1());
        entity.setIcona1(icona1.getId());
    }
    IconaEntity icona2 = null;
    if (puntEntrada.getImgIcona2() != null && puntEntrada.getImgIcona2().length != 0) {
        // S'ha actualitzat l'icona: creem una nova
        icona2 = createIcona(puntEntrada.getImgIcona2());
        entity.setIcona2(icona2.getId());
    }

    // Actualitzem l'entitat (amb les relacions)
    getPuntEntradaEntityDao().update(entity);

    // Afegim id del pare (per poder moure'l ara mateix)
    PuntEntrada res = getPuntEntradaEntityDao().toPuntEntrada(entity);
    res.setIdPare(idPare);

    // Assignem iconas (en el toVO encara no poden estar en la BD)
    if (icona1 != null) {
        res.setIdIcona1(icona1.getId());
        res.setImgIcona1(icona1.getIcona());
    }
    if (icona2 != null) {
        res.setIdIcona2(icona2.getId());
        res.setImgIcona2(icona2.getIcona());
    }

    // Posem la ruta que s'ha obtingut en el ZUL a partir del pare
    if (puntEntrada.getRutaArbre() != null)
        res.setRutaArbre(puntEntrada.getRutaArbre());

    auditarPuntEntrada("C", res.getNom() + Messages.getString("PuntEntradaServiceImpl.15") + pareE.getNom()); //$NON-NLS-1$ //$NON-NLS-2$

    return res;
}