Example usage for org.apache.shiro ShiroException ShiroException

List of usage examples for org.apache.shiro ShiroException ShiroException

Introduction

In this page you can find the example usage for org.apache.shiro ShiroException ShiroException.

Prototype

public ShiroException(String message, Throwable cause) 

Source Link

Document

Constructs a new ShiroException.

Usage

From source file:org.apache.zeppelin.realm.LdapRealm.java

License:Apache License

static String getSystemPassword(String hadoopSecurityCredentialPath, String keystorePass) {
    String password = "";
    try {/*from   ww  w .  j  a v  a2  s.  c o  m*/
        Configuration configuration = new Configuration();
        configuration.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, hadoopSecurityCredentialPath);
        CredentialProvider provider = CredentialProviderFactory.getProviders(configuration).get(0);
        CredentialProvider.CredentialEntry credEntry = provider.getCredentialEntry(keystorePass);
        if (credEntry != null) {
            password = new String(credEntry.getCredential());
        }
    } catch (IOException e) {
        throw new ShiroException("Error from getting credential entry from keystore", e);
    }
    if (org.apache.commons.lang.StringUtils.isEmpty(password)) {
        throw new ShiroException("Error getting SystemPassword from the provided keystore:" + keystorePass
                + ", in path:" + hadoopSecurityCredentialPath);
    }
    return password;
}

From source file:org.eclipse.kapua.broker.core.plugin.KapuaSecurityBrokerFilter.java

License:Open Source License

private void addExternalConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
    // Clean-up credentials possibly associated with the current thread by previous connection.
    ThreadContext.unbindSubject();/*from   w ww.  j  av a  2 s.  c  o  m*/

    Context loginTotalContext = metricLoginAddConnectionTime.time();

    String username = info.getUserName();
    String password = info.getPassword();
    String clientId = info.getClientId();
    String clientIp = info.getClientIp();
    ConnectionId connectionId = info.getConnectionId();

    List<String> authDestinations = null;
    if (logger.isDebugEnabled()) {
        authDestinations = new ArrayList<>();
    }
    try {
        // Build KapuaUsername
        // User username = User.parse(username);//KapuaUserName

        logger.info("User name {} - client id {}", new Object[] { username, clientId });

        Context loginPreCheckTimeContext = metricLoginPreCheckTime.time();
        // 1) validate client id
        // Check the device Mqtt ClientId

        // TODO move to deviceservice
        // MqttUtils.checkDeviceClientId(clientId);
        loginPreCheckTimeContext.stop();

        Context loginShiroLoginTimeContext = metricLoginShiroLoginTime.time();
        AuthenticationCredentials credentials = credentialsFactory.newInstance(username,
                password.toCharArray());
        AccessToken accessToken = authenticationService.login(credentials);

        KapuaId scopeId = accessToken.getScopeId();
        KapuaId userId = accessToken.getUserId();

        final Account account;
        try {
            account = KapuaSecurityUtils.doPriviledge(() -> accountService.find(scopeId));
        } catch (Exception e) {
            // to preserve the original exception message (if possible)
            if (e instanceof AuthenticationException) {
                throw (AuthenticationException) e;
            } else {
                throw new ShiroException("Error while find account!", e);
            }
        }

        String accountName = account.getName();
        loginShiroLoginTimeContext.stop();

        // if a user acts as a child MOVED INSIDE KapuaAuthorizingRealm otherwise through REST API and console this @accountName won't work

        // get account id and name from kapua session methods that check for the run as
        //
        // String accountName = kapuaSession.getSessionAccountName();
        // long accountId = kapuaSession.getSessionAccountId();

        // multiple account stealing link fix
        String fullClientId = MessageFormat.format(AclConstants.MULTI_ACCOUNT_CLIENT_ID,
                scopeId.getId().longValue(), clientId);

        KapuaPrincipal principal = new KapuaPrincipalImpl(accessToken, username, clientId, clientIp);
        DeviceConnection deviceConnection = null;
        // 3) check authorization
        DefaultAuthorizationMap authMap = null;
        if (isAdminUser(username)) {
            metricLoginKapuasysTokenAttempt.inc();
            // 3-1) admin authMap
            authMap = buildAdminAuthMap(authDestinations, principal, fullClientId);
            metricClientConnectedKapuasys.inc();
        } else {
            Context loginNormalUserTimeContext = metricLoginNormalUserTime.time();
            metricLoginNormalUserAttempt.inc();
            // 3-3) check permissions

            Context loginCheckAccessTimeContext = metricLoginCheckAccessTime.time();
            boolean[] hasPermissions = new boolean[] {
                    // TODO check the permissions... move them to a constants class?
                    authorizationService.isPermitted(permissionFactory
                            .newPermission(DeviceLifecycleDomain.DEVICE_LIFECYCLE, Actions.connect, scopeId)),
                    authorizationService.isPermitted(permissionFactory
                            .newPermission(DeviceManagementDomain.DEVICE_MANAGEMENT, Actions.write, scopeId)),
                    authorizationService.isPermitted(
                            permissionFactory.newPermission(DatastoreDomain.DATA_STORE, Actions.read, scopeId)),
                    authorizationService.isPermitted(permissionFactory.newPermission(DatastoreDomain.DATA_STORE,
                            Actions.write, scopeId)) };
            if (!hasPermissions[AclConstants.BROKER_CONNECT_IDX]) {
                throw new KapuaIllegalAccessException(permissionFactory
                        .newPermission(DeviceLifecycleDomain.DEVICE_LIFECYCLE, Actions.connect, scopeId)
                        .toString());
            }
            loginCheckAccessTimeContext.stop();

            // 3-4) build authMap
            authMap = buildAuthMap(authDestinations, principal, hasPermissions, accountName, clientId,
                    fullClientId);

            // 4) find device
            Context loginFindClientIdTimeContext = metricLoginFindClientIdTime.time();
            deviceConnection = deviceConnectionService.findByClientId(scopeId, clientId);
            loginFindClientIdTimeContext.stop();

            Context loginFindDevTimeContext = metricLoginFindDevTime.time();

            // send connect message
            ConnectionId previousConnectionId = connectionMap.get(fullClientId);
            boolean stealingLinkDetected = (previousConnectionId != null);
            // Update map for stealing link detection on disconnect
            connectionMap.put(fullClientId, info.getConnectionId());
            if (deviceConnection == null) {
                DeviceConnectionCreator deviceConnectionCreator = deviceConnectionFactory.newCreator(scopeId);
                deviceConnectionCreator.setClientId(clientId);
                deviceConnectionCreator.setClientIp(clientIp);
                deviceConnectionCreator.setProtocol("MQTT");
                deviceConnectionCreator.setServerIp(null);// TODO to be filled with the proper value
                deviceConnectionCreator.setUserId(userId);
                deviceConnection = deviceConnectionService.create(deviceConnectionCreator);
            } else {
                deviceConnection.setClientIp(clientIp);
                deviceConnection.setProtocol("MQTT");
                deviceConnection.setServerIp(null);// TODO to be filled with the proper value
                deviceConnection.setUserId(userId);
                deviceConnection.setStatus(DeviceConnectionStatus.CONNECTED);
                deviceConnectionService.update(deviceConnection);
                // TODO implement the banned status
                // if (DeviceStatus.DISABLED.equals(device.getStatus())) {
                // throw new KapuaIllegalAccessException("clientId - This client ID is disabled and cannot connect");
                // }
                // TODO manage the stealing link event (may be a good idea to use different connect status (connect -stealing)?
                if (stealingLinkDetected) {
                    metricLoginStealingLinkConnect.inc();

                    // stealing link detected, skip info
                    logger.warn(
                            "Detected Stealing link for cliend id {} - account - last connection id was {} - current connection id is {} - IP: {} - No connection status changes!",
                            new Object[] { clientId, accountName, previousConnectionId, info.getConnectionId(),
                                    info.getClientIp() });
                }
            }
            loginFindDevTimeContext.stop();

            loginNormalUserTimeContext.stop();
            Context loginSendLogingUpdateMsgTimeContex = metricLoginSendLoginUpdateMsgTime.time();

            loginSendLogingUpdateMsgTimeContex.stop();
            metricClientConnectedClient.inc();
        }
        logAuthDestinationToLog(authDestinations);

        ConnectorDescriptor connectorDescriptor = connectorsDescriptorMap
                .get((((TransportConnector) context.getConnector()).getName()));
        KapuaSecurityContext securityCtx = new KapuaSecurityContext(principal, authMap,
                (deviceConnection != null ? deviceConnection.getId() : null), connectionId,
                connectorDescriptor);
        context.setSecurityContext(securityCtx);

        // multiple account stealing link fix
        info.setClientId(fullClientId);
        context.setClientId(fullClientId);
    } catch (Exception e) {
        metricLoginFailure.inc();

        // fix ENTMQ-731
        if (e instanceof KapuaAuthenticationException) {
            KapuaAuthenticationException kapuaException = (KapuaAuthenticationException) e;
            KapuaErrorCode errorCode = kapuaException.getCode();
            if (errorCode.equals(KapuaAuthenticationErrorCodes.INVALID_USERNAME)
                    || errorCode.equals(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS)
                    || errorCode.equals(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS_TOKEN_PROVIDED)) {
                logger.warn("Invalid username or password for user {} ({})", username, e.getMessage());
                // activeMQ will map CredentialException into a CONNECTION_REFUSED_BAD_USERNAME_OR_PASSWORD message (see javadoc on top of this method)
                CredentialException ce = new CredentialException(
                        "Invalid username and/or password or disabled or expired account!");
                ce.setStackTrace(e.getStackTrace());
                metricLoginInvalidUserPassword.inc();
                throw ce;
            } else if (errorCode.equals(KapuaAuthenticationErrorCodes.LOCKED_USERNAME)
                    || errorCode.equals(KapuaAuthenticationErrorCodes.DISABLED_USERNAME)
                    || errorCode.equals(KapuaAuthenticationErrorCodes.EXPIRED_CREDENTIALS)) {
                logger.warn("User {} not authorized ({})", username, e.getMessage());
                // activeMQ-MQ will map SecurityException into a CONNECTION_REFUSED_NOT_AUTHORIZED message (see javadoc on top of this method)
                SecurityException se = new SecurityException("User not authorized!");
                se.setStackTrace(e.getStackTrace());
                throw se;
            }

        }
        // Excluded CredentialException, InvalidClientIDException, SecurityException all others exceptions will be mapped by activeMQ to a CONNECTION_REFUSED_SERVER_UNAVAILABLE message (see
        // javadoc on top of this method)
        // Not trapped exception now:
        // KapuaException
        logger.info("@@ error", e);
        throw e;
    } finally {
        // 7) logout
        Context loginShiroLogoutTimeContext = metricLoginShiroLogoutTime.time();
        authenticationService.logout();
        ThreadContext.unbindSubject();
        loginShiroLogoutTimeContext.stop();
        loginTotalContext.stop();
    }
}

From source file:org.eclipse.kapua.broker.core.plugin.KapuaSecurityBrokerFilter.java

License:Open Source License

@Override
public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
    if (!isPassThroughConnection(context)) {
        Context loginRemoveConnectionTimeContext = metricLoginRemoveConnectionTime.time();
        try {/* w ww .  j  av a2  s .c o  m*/

            KapuaSecurityContext kapuaSecurityContext = getKapuaSecurityContext(context);

            // TODO fix the kapua session when run as feature will be implemented
            KapuaPrincipal kapuaPrincipal = ((KapuaPrincipal) kapuaSecurityContext.getMainPrincipal());
            KapuaSession kapuaSession = new KapuaSession(null, kapuaPrincipal.getAccountId(),
                    kapuaPrincipal.getAccountId(), kapuaPrincipal.getUserId(), kapuaPrincipal.getName());
            KapuaSecurityUtils.setSession(kapuaSession);

            String clientId = kapuaPrincipal.getClientId();
            KapuaId accountId = kapuaPrincipal.getAccountId();
            String username = kapuaSecurityContext.getUserName();
            String remoteAddress = (context.getConnection() != null)
                    ? context.getConnection().getRemoteAddress()
                    : "";

            KapuaId scopeId = ((KapuaPrincipal) kapuaSecurityContext.getMainPrincipal()).getAccountId();

            // multiple account stealing link fix
            String fullClientId = MessageFormat.format(AclConstants.MULTI_ACCOUNT_CLIENT_ID, accountId,
                    clientId);

            if (!isAdminUser(username)) {
                // Stealing link check
                ConnectionId connectionId = connectionMap.get(fullClientId);

                boolean stealingLinkDetected = false;
                if (connectionId != null) {
                    stealingLinkDetected = !connectionId.equals(info.getConnectionId());
                } else {
                    logger.error(
                            "Cannot find connection id for client id {} on connection map. Currect connection id is {} - IP: {}",
                            new Object[] { clientId, info.getConnectionId(), info.getClientIp() });
                }
                if (stealingLinkDetected) {
                    metricLoginStealingLinkDisconnect.inc();

                    // stealing link detected, skip info
                    logger.warn(
                            "Detected Stealing link for cliend id {} - account id {} - last connection id was {} - current connection id is {} - IP: {} - No disconnection info will be added!",
                            new Object[] { clientId, accountId, connectionId, info.getConnectionId(),
                                    info.getClientIp() });
                } else {
                    KapuaId deviceConnectionId = kapuaSecurityContext.getConnectionId();

                    DeviceConnection deviceConnection = null;
                    try {
                        deviceConnection = KapuaSecurityUtils.doPriviledge(new Callable<DeviceConnection>() {

                            @Override
                            public DeviceConnection call() throws Exception {
                                return deviceConnectionService.findByClientId(scopeId, clientId);
                            }
                        });
                    } catch (Exception e) {
                        throw new ShiroException("Error while updating the device connection!", e);
                    }
                    // the device connection must be not null

                    // cleanup stealing link detection map
                    connectionMap.remove(fullClientId);

                    final DeviceConnection deviceConnectionToUpdate = deviceConnection;
                    if (error == null) {
                        // update device connection
                        deviceConnectionToUpdate.setStatus(DeviceConnectionStatus.DISCONNECTED);

                        try {
                            KapuaSecurityUtils.doPriviledge(() -> {
                                deviceConnectionService.update(deviceConnectionToUpdate);
                                return null;
                            });
                        } catch (Exception e) {
                            throw new ShiroException("Error while updating the device connection status!", e);
                        }
                    } else {
                        // send missing message
                        // update device connection
                        deviceConnectionToUpdate.setStatus(DeviceConnectionStatus.MISSING);

                        try {
                            KapuaSecurityUtils.doPriviledge(() -> {
                                deviceConnectionService.update(deviceConnectionToUpdate);
                                return null;
                            });
                        } catch (Exception e) {
                            throw new ShiroException("Error while updating the device connection status!", e);
                        }

                    }
                }
                metricClientDisconnectionClient.inc();
            } else {
                metricClientDisconnectionKapuasys.inc();
            }
            // multiple account stealing link fix
            info.setClientId(fullClientId);
            context.setClientId(fullClientId);
        } finally {
            loginRemoveConnectionTimeContext.stop();
            authenticationService.logout();
        }
    }
    super.removeConnection(context, info, error);
    context.setSecurityContext(null);
}

From source file:org.eclipse.kapua.service.authentication.shiro.KapuaAuthenticatingRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
        throws AuthenticationException {
    ////from   ww  w  .  j a  v  a2s.  c  o m
    // Extract credentials
    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    String tokenUsername = token.getUsername();
    // char[] tokenPassword = token.getPassword();

    //
    // Get Services
    KapuaLocator locator;
    UserService userService;
    AccountService accountService;
    CredentialService credentialService;

    try {
        locator = KapuaLocator.getInstance();
        userService = locator.getService(UserService.class);
        accountService = locator.getService(AccountService.class);
        credentialService = locator.getService(CredentialService.class);
    } catch (KapuaRuntimeException kre) {
        throw new ShiroException("Error while getting services!", kre);
    }

    //
    // Get the associated user by name
    final User user;
    try {
        user = KapuaSecurityUtils.doPriviledge(new Callable<User>() {

            @Override
            public User call() throws Exception {
                return userService.findByName(tokenUsername);
            }
        });
    } catch (Exception e) {
        //to preserve the original exception message (if possible)
        if (e instanceof AuthenticationException) {
            throw (AuthenticationException) e;
        } else {
            throw new ShiroException("Error while find user!", e);
        }
    }

    // Check existence
    if (user == null) {
        throw new UnknownAccountException();
    }

    // Check disabled
    if (UserStatus.DISABLED.equals(user.getStatus())) {
        throw new DisabledAccountException();
    }

    //
    // Find account
    final Account account;
    try {
        account = KapuaSecurityUtils.doPriviledge(new Callable<Account>() {

            @Override
            public Account call() throws Exception {
                return accountService.find(user.getScopeId());
            }
        });
    } catch (Exception e) {
        //to preserve the original exception message (if possible)
        if (e instanceof AuthenticationException) {
            throw (AuthenticationException) e;
        } else {
            throw new ShiroException("Error while find account!", e);
        }
    }

    // Check existence
    if (account == null) {
        throw new UnknownAccountException();
    }

    //
    // Find credentials
    // FIXME: manage multiple credentials and multiple credentials type
    Credential credential = null;
    try {
        credential = KapuaSecurityUtils.doPriviledge(new Callable<Credential>() {

            @Override
            public Credential call() throws Exception {
                CredentialListResult credentialList = credentialService.findByUserId(user.getScopeId(),
                        user.getId());
                // TODO may be better to filter by credential type?
                if (credentialList != null && !credentialList.isEmpty()) {
                    return credentialList.getItem(0);
                } else {
                    throw new UnknownAccountException();
                }
            }
        });
    } catch (Exception e) {
        if (e instanceof AuthenticationException) {
            throw (AuthenticationException) e;
        } else {
            throw new ShiroException("Error while find credentials!", e);
        }
    }

    //
    // BuildAuthenticationInfo8
    KapuaSimpleAuthenticationInfo info = new KapuaSimpleAuthenticationInfo(user, credential, account,
            getName());

    return info;
}

From source file:org.eclipse.kapua.service.authorization.shiro.KapuaAuthorizingRealm.java

License:Open Source License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
        throws AuthenticationException {
    ///*www  .java 2s. c  o  m*/
    // Extract principal
    String username = (String) principals.getPrimaryPrincipal();
    logger.debug("Getting authorization info for: {}", username);

    //
    // Get Services
    KapuaLocator locator = KapuaLocator.getInstance();
    UserService userService = locator.getService(UserService.class);
    UserPermissionService userPermissionService = locator.getService(UserPermissionService.class);
    UserPermissionFactory userPermissionFactory = locator.getFactory(UserPermissionFactory.class);
    PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class);

    //
    // Get the associated user by name
    final User user;
    try {
        user = KapuaSecurityUtils.doPriviledge(new Callable<User>() {

            @Override
            public User call() throws Exception {
                return userService.findByName(username);
            }
        });
    } catch (Exception e) {
        //to preserve the original exception message (if possible)
        if (e instanceof AuthenticationException) {
            throw (AuthenticationException) e;
        } else {
            throw new ShiroException("Error while find user!", e);
        }
    }

    //
    // Check existence
    if (user == null) {
        throw new UnknownAccountException();
    }

    //
    // Get user permissions set
    UserPermissionQuery query = userPermissionFactory.newQuery(user.getScopeId());
    KapuaPredicate predicate = new AttributePredicate<KapuaId>(UserPermissionPredicates.USER_ID, user.getId());
    query.setPredicate(predicate);

    final KapuaListResult<UserPermission> userPermissions;
    try {
        userPermissions = KapuaSecurityUtils.doPriviledge(new Callable<KapuaListResult<UserPermission>>() {

            @Override
            public KapuaListResult<UserPermission> call() throws Exception {
                return userPermissionService.query(query);
            }
        });
    } catch (Exception e) {
        //to preserve the original exception message (if possible)
        if (e instanceof AuthenticationException) {
            throw (AuthenticationException) e;
        } else {
            throw new ShiroException("Error while find permissions!", e);
        }
    }

    //
    // Create SimpleAuthorizationInfo with principals permissions
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    for (UserPermission userPermission : userPermissions.getItems()) {

        Permission p = permissionFactory.newPermission(userPermission.getPermission().getDomain(),
                userPermission.getPermission().getAction(), userPermission.getPermission().getTargetScopeId());

        logger.trace("Username: {} has permission: {}", username, p);
        info.addStringPermission(p.toString());
    }

    return info;
}

From source file:org.ow2.proactive.iam.core.realms.PamRealm.java

License:Open Source License

@Override
protected void onInit() {
    super.onInit();
    try {/*  w w w.  j a  v a2  s  .c  om*/
        // Tests PAM "connectivity"
        getPam();
    } catch (PAMException e) {
        throw new ShiroException("Cannot obtain PAM subsystem.", e);
    }
}

From source file:org.sonatype.nexus.plugins.crowd.client.DefaultCrowdClientHolder.java

License:Open Source License

@Override
public void init() throws ShiroException {
    configuration = crowdPluginConfiguration.getConfiguration();
    if (configuration != null) {
        basicCache = new AuthBasicCacheImpl(60 * configuration.getSessionValidationInterval());
        try {//from   ww  w  .j a  va 2s.  c o  m
            restClient = new CachingRestClient(configuration);
        } catch (URISyntaxException use) {
            throw new ShiroException("Rest client init failed", use);
        }
        authManager = new CachingAuthenticationManager(restClient, basicCache);
        configured = true;
    }
}