Search in sources :

Example 16 with AuthenticationException

use of org.apache.shiro.authc.AuthenticationException in project killbill by killbill.

the class TenantFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    // Lookup tenant information in the headers
    String apiKey = null;
    String apiSecret = null;
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        apiKey = httpServletRequest.getHeader(JaxrsResource.HDR_API_KEY);
        apiSecret = httpServletRequest.getHeader(JaxrsResource.HDR_API_SECRET);
    }
    // Multi-tenancy is enabled if this filter is installed, we can't continue without credentials
    if (apiKey == null || apiSecret == null) {
        final String errorMessage = String.format("Make sure to set the %s and %s headers", JaxrsResource.HDR_API_KEY, JaxrsResource.HDR_API_SECRET);
        handleAuthenticationError(errorMessage, chain, request, response);
        return;
    }
    // Verify the apiKey/apiSecret combo
    final AuthenticationToken token = new UsernamePasswordToken(apiKey, apiSecret);
    try {
        modularRealmAuthenticator.authenticate(token);
    } catch (final AuthenticationException e) {
        final String errorMessage = e.getLocalizedMessage();
        handleAuthenticationError(errorMessage, chain, request, response);
        return;
    }
    try {
        // Load the tenant in the request object (apiKey is unique across tenants)
        final Tenant tenant = tenantUserApi.getTenantByApiKey(apiKey);
        request.setAttribute(TENANT, tenant);
        // Create a dummy context, to set the MDC very early for LoggingFilter
        context.createContext(request);
        chain.doFilter(request, response);
    } catch (final TenantApiException e) {
        // Should never happen since Shiro validated the credentials?
        log.error("Couldn't find the tenant? - should never happen!", e);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) Tenant(org.killbill.billing.tenant.api.Tenant) AuthenticationException(org.apache.shiro.authc.AuthenticationException) TenantApiException(org.killbill.billing.tenant.api.TenantApiException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 17 with AuthenticationException

use of org.apache.shiro.authc.AuthenticationException in project graylog2-server by Graylog2.

the class LdapUserAuthenticator method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authtoken) throws AuthenticationException {
    // safe, we only handle this type
    final UsernamePasswordToken token = (UsernamePasswordToken) authtoken;
    final LdapSettings ldapSettings = ldapSettingsService.load();
    if (ldapSettings == null || !ldapSettings.isEnabled()) {
        LOG.trace("LDAP is disabled, skipping");
        return null;
    }
    final LdapConnectionConfig config = new LdapConnectionConfig();
    config.setLdapHost(ldapSettings.getUri().getHost());
    config.setLdapPort(ldapSettings.getUri().getPort());
    config.setUseSsl(ldapSettings.getUri().getScheme().startsWith("ldaps"));
    config.setUseTls(ldapSettings.isUseStartTls());
    if (ldapSettings.isTrustAllCertificates()) {
        config.setTrustManagers(new TrustAllX509TrustManager());
    }
    config.setName(ldapSettings.getSystemUserName());
    config.setCredentials(ldapSettings.getSystemPassword());
    final String principal = (String) token.getPrincipal();
    final char[] tokenPassword = firstNonNull(token.getPassword(), new char[0]);
    final String password = String.valueOf(tokenPassword);
    // do not try to look a token up in LDAP if there is no principal or password
    if (isNullOrEmpty(principal) || isNullOrEmpty(password)) {
        LOG.debug("Principal or password were empty. Not trying to look up a token in LDAP.");
        return null;
    }
    try (final LdapNetworkConnection connection = ldapConnector.connect(config)) {
        if (null == connection) {
            LOG.error("Couldn't connect to LDAP directory");
            return null;
        }
        final LdapEntry userEntry = ldapConnector.search(connection, ldapSettings.getSearchBase(), ldapSettings.getSearchPattern(), ldapSettings.getDisplayNameAttribute(), principal, ldapSettings.isActiveDirectory(), ldapSettings.getGroupSearchBase(), ldapSettings.getGroupIdAttribute(), ldapSettings.getGroupSearchPattern());
        if (userEntry == null) {
            LOG.debug("User {} not found in LDAP", principal);
            return null;
        }
        // needs to use the DN of the entry, not the parameter for the lookup filter we used to find the entry!
        final boolean authenticated = ldapConnector.authenticate(connection, userEntry.getDn(), password);
        if (!authenticated) {
            LOG.info("Invalid credentials for user {} (DN {})", principal, userEntry.getDn());
            return null;
        }
        // user found and authenticated, sync the user entry with mongodb
        final User user = syncFromLdapEntry(userEntry, ldapSettings, principal);
        if (user == null) {
            // in case there was an error reading, creating or modifying the user in mongodb, we do not authenticate the user.
            LOG.error("Unable to sync LDAP user {} (DN {})", userEntry.getBindPrincipal(), userEntry.getDn());
            return null;
        }
        return new SimpleAccount(principal, null, "ldap realm");
    } catch (LdapException e) {
        LOG.error("LDAP error", e);
    } catch (CursorException e) {
        LOG.error("Unable to read LDAP entry", e);
    } catch (Exception e) {
        LOG.error("Error during LDAP user account sync. Cannot log in user {}", principal, e);
    }
    // Return null by default to ensure a login failure if anything goes wrong.
    return null;
}
Also used : SimpleAccount(org.apache.shiro.authc.SimpleAccount) User(org.graylog2.plugin.database.users.User) LdapConnectionConfig(org.apache.directory.ldap.client.api.LdapConnectionConfig) LdapEntry(org.graylog2.shared.security.ldap.LdapEntry) LdapNetworkConnection(org.apache.directory.ldap.client.api.LdapNetworkConnection) TrustAllX509TrustManager(org.graylog2.security.TrustAllX509TrustManager) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) NotFoundException(org.graylog2.database.NotFoundException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) ValidationException(org.graylog2.plugin.database.ValidationException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapSettings(org.graylog2.shared.security.ldap.LdapSettings)

Example 18 with AuthenticationException

use of org.apache.shiro.authc.AuthenticationException in project bamboobsc by billchen198318.

the class GreenStepBaseAuthorizingRealm method doGetAuthenticationInfo.

/**
	 * 認證
	 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    GreenStepBaseUsernamePasswordToken token = (GreenStepBaseUsernamePasswordToken) authenticationToken;
    String account = token.getUsername();
    AccountVO accountObj = new AccountVO();
    accountObj.setAccount(account);
    try {
        DefaultResult<AccountVO> result = accountService.findByUK(accountObj);
        if (result.getValue() == null) {
            return null;
        }
        accountObj = result.getValue();
        return new SimpleAuthenticationInfo(accountObj.getAccount(), accountObj.getPassword(), this.getName());
    } catch (ServiceException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) AccountVO(com.netsteadfast.greenstep.vo.AccountVO) AuthenticationException(org.apache.shiro.authc.AuthenticationException) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException)

Example 19 with AuthenticationException

use of org.apache.shiro.authc.AuthenticationException in project ddf by codice.

the class AbstractStsRealm method renewSecurityToken.

/**
     * Renew a security token (SAML assertion) from the STS.
     *
     * @param securityToken The token being renewed.
     * @return security token (SAML assertion)
     */
protected SecurityToken renewSecurityToken(SecurityToken securityToken) {
    SecurityToken token = null;
    String stsAddress = getAddress();
    try {
        LOGGER.debug("Renewing security token from STS at: {}.", stsAddress);
        if (securityToken != null) {
            LOGGER.debug("Telling the STS to renew a security token on behalf of the auth token");
            STSClient stsClient = configureStsClient();
            stsClient.setWsdlLocation(stsAddress);
            stsClient.setTokenType(getAssertionType());
            stsClient.setKeyType(getKeyType());
            stsClient.setKeySize(Integer.parseInt(getKeySize()));
            stsClient.setAllowRenewing(true);
            token = stsClient.renewSecurityToken(securityToken);
            LOGGER.debug("Finished renewing security token.");
        }
    } catch (Exception e) {
        String msg = "Error renewing the security token from STS at: " + stsAddress + ".";
        LOGGER.debug(msg, e);
        throw new AuthenticationException(msg, e);
    }
    return token;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) STSClient(org.apache.cxf.ws.security.trust.STSClient) AuthenticationException(org.apache.shiro.authc.AuthenticationException) XMLStreamException(javax.xml.stream.XMLStreamException) AuthenticationException(org.apache.shiro.authc.AuthenticationException)

Example 20 with AuthenticationException

use of org.apache.shiro.authc.AuthenticationException in project ddf by codice.

the class AbstractStsRealm method doGetAuthenticationInfo.

/**
     * Perform authentication based on the supplied token.
     */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    String method = "doGetAuthenticationInfo(    AuthenticationToken token )";
    Object credential;
    if (token instanceof SAMLAuthenticationToken) {
        credential = token.getCredentials();
    } else if (token instanceof BaseAuthenticationToken) {
        credential = ((BaseAuthenticationToken) token).getCredentialsAsXMLString();
    } else {
        credential = token.getCredentials().toString();
    }
    if (credential == null) {
        String msg = "Unable to authenticate credential.  A NULL credential was provided in the supplied authentication token. This may be due to an error with the SSO server that created the token.";
        LOGGER.info(msg);
        throw new AuthenticationException(msg);
    } else {
        //removed the credentials from the log message for now, I don't think we should be dumping user/pass into log
        LOGGER.debug("Received credentials.");
    }
    SecurityToken securityToken;
    if (token instanceof SAMLAuthenticationToken && credential instanceof SecurityToken) {
        securityToken = renewSecurityToken((SecurityToken) credential);
    } else {
        securityToken = requestSecurityToken(credential);
    }
    LOGGER.debug("Creating token authentication information with SAML.");
    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
    SimplePrincipalCollection principals = new SimplePrincipalCollection();
    SecurityAssertion assertion = new SecurityAssertionImpl(securityToken);
    principals.add(assertion.getPrincipal(), NAME);
    principals.add(assertion, NAME);
    simpleAuthenticationInfo.setPrincipals(principals);
    simpleAuthenticationInfo.setCredentials(credential);
    return simpleAuthenticationInfo;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) SecurityAssertionImpl(ddf.security.assertion.impl.SecurityAssertionImpl)

Aggregations

AuthenticationException (org.apache.shiro.authc.AuthenticationException)21 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)9 Subject (org.apache.shiro.subject.Subject)6 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)4 LockedAccountException (org.apache.shiro.authc.LockedAccountException)4 AccountVO (com.netsteadfast.greenstep.vo.AccountVO)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)3 IncorrectCredentialsException (org.apache.shiro.authc.IncorrectCredentialsException)3 SimpleAuthenticationInfo (org.apache.shiro.authc.SimpleAuthenticationInfo)3 UnknownAccountException (org.apache.shiro.authc.UnknownAccountException)3 Session (org.apache.shiro.session.Session)3 Serializable (java.io.Serializable)2 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)2 SecurityContext (javax.ws.rs.core.SecurityContext)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 STSClient (org.apache.cxf.ws.security.trust.STSClient)2 ExcessiveAttemptsException (org.apache.shiro.authc.ExcessiveAttemptsException)2 DelegatingSubject (org.apache.shiro.subject.support.DelegatingSubject)2 Test (org.junit.Test)2