Search in sources :

Example 1 with AuthenticationException

use of org.apache.shiro.authc.AuthenticationException in project qi4j-sdk by Qi4j.

the class StandaloneShiroTest method test.

@Test
public void test() {
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();
    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = currentUser.getSession();
    session.setAttribute("someKey", "aValue");
    String value = (String) session.getAttribute("someKey");
    assertEquals("aValue", value);
    LOG.info("Retrieved the correct value! [" + value + "]");
    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            fail("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            fail("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            fail("The account for username " + token.getPrincipal() + " is locked.  " + "Please contact your administrator to unlock it.");
        }// ... catch more exceptions here (maybe custom ones specific to your application?
         catch (AuthenticationException ae) {
            //unexpected condition?  error?
            throw ae;
        }
    }
    //say who they are:
    //print their identifying principal (in this case, a username):
    assertNotNull(currentUser.getPrincipal());
    LOG.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    //test a role:
    if (currentUser.hasRole("schwartz")) {
        LOG.info("May the Schwartz be with you!");
    } else {
        fail("Hello, mere mortal.");
    }
    //test a typed permission (not instance-level)
    if (currentUser.isPermitted("lightsaber:weild")) {
        LOG.info("You may use a lightsaber ring.  Use it wisely.");
    } else {
        fail("Sorry, lightsaber rings are for schwartz masters only.");
    }
    //a (very powerful) Instance Level permission:
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        LOG.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " + "Here are the keys - have fun!");
    } else {
        fail("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }
    //all done - log out!
    currentUser.logout();
}
Also used : IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) Subject(org.apache.shiro.subject.Subject) LockedAccountException(org.apache.shiro.authc.LockedAccountException) Session(org.apache.shiro.session.Session) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) AbstractQi4jTest(org.qi4j.test.AbstractQi4jTest) Test(org.junit.Test)

Example 2 with AuthenticationException

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

the class TestKillbillJdbcTenantRealm method testAuthentication.

@Test(groups = "slow")
public void testAuthentication() throws Exception {
    final DelegatingSubject subject = new DelegatingSubject(securityManager);
    // Good combo
    final AuthenticationToken goodToken = new UsernamePasswordToken(tenant.getApiKey(), tenant.getApiSecret());
    try {
        securityManager.login(subject, goodToken);
        Assert.assertTrue(true);
    } catch (final AuthenticationException e) {
        Assert.fail();
    }
    // Bad login
    final AuthenticationToken badPasswordToken = new UsernamePasswordToken(tenant.getApiKey(), tenant.getApiSecret() + "T");
    try {
        securityManager.login(subject, badPasswordToken);
        Assert.fail();
    } catch (final AuthenticationException e) {
        Assert.assertTrue(true);
    }
    // Bad password
    final AuthenticationToken badLoginToken = new UsernamePasswordToken(tenant.getApiKey() + "U", tenant.getApiSecret());
    try {
        securityManager.login(subject, badLoginToken);
        Assert.fail();
    } catch (final AuthenticationException e) {
        Assert.assertTrue(true);
    }
}
Also used : DelegatingSubject(org.apache.shiro.subject.support.DelegatingSubject) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Test(org.testng.annotations.Test)

Example 3 with AuthenticationException

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

the class MultiRealmAuthManager method login.

@Override
public EnterpriseSecurityContext login(Map<String, Object> authToken) throws InvalidAuthTokenException {
    EnterpriseSecurityContext securityContext;
    ShiroAuthToken token = new ShiroAuthToken(authToken);
    assertValidScheme(token);
    try {
        securityContext = new StandardEnterpriseSecurityContext(this, (ShiroSubject) securityManager.login(null, token));
        if (logSuccessfulLogin) {
            securityLog.info(securityContext, "logged in");
        }
    } catch (UnsupportedTokenException e) {
        securityLog.error("Unknown user failed to log in: %s", e.getMessage());
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof InvalidAuthTokenException) {
            throw new InvalidAuthTokenException(cause.getMessage() + ": " + token);
        }
        throw invalidToken(": " + token);
    } catch (ExcessiveAttemptsException e) {
        // NOTE: We only get this with single (internal) realm authentication
        securityContext = new StandardEnterpriseSecurityContext(this, new ShiroSubject(securityManager, AuthenticationResult.TOO_MANY_ATTEMPTS));
        securityLog.error("[%s]: failed to log in: too many failed attempts", escape(token.getPrincipal().toString()));
    } catch (AuthenticationException e) {
        if (e.getCause() != null && e.getCause() instanceof AuthProviderTimeoutException) {
            securityLog.error("[%s]: failed to log in: auth server timeout", escape(token.getPrincipal().toString()));
            throw new AuthProviderTimeoutException(e.getCause().getMessage(), e.getCause());
        }
        securityContext = new StandardEnterpriseSecurityContext(this, new ShiroSubject(securityManager, AuthenticationResult.FAILURE));
        securityLog.error("[%s]: failed to log in: invalid principal or credentials", escape(token.getPrincipal().toString()));
    }
    return securityContext;
}
Also used : EnterpriseSecurityContext(org.neo4j.kernel.enterprise.api.security.EnterpriseSecurityContext) AuthenticationException(org.apache.shiro.authc.AuthenticationException) ExcessiveAttemptsException(org.apache.shiro.authc.ExcessiveAttemptsException) AuthProviderTimeoutException(org.neo4j.graphdb.security.AuthProviderTimeoutException) UnsupportedTokenException(org.apache.shiro.authc.pam.UnsupportedTokenException) InvalidAuthTokenException(org.neo4j.kernel.api.security.exception.InvalidAuthTokenException)

Example 4 with AuthenticationException

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

the class PluginRealm method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (token instanceof ShiroAuthToken) {
        try {
            AuthToken pluginAuthToken = PluginApiAuthToken.createFromMap(((ShiroAuthToken) token).getAuthTokenMap());
            if (authPlugin != null) {
                AuthInfo authInfo = authPlugin.authenticateAndAuthorize(pluginAuthToken);
                if (authInfo != null) {
                    PluginAuthInfo pluginAuthInfo = PluginAuthInfo.createCacheable(authInfo, getName(), secureHasher);
                    cacheAuthorizationInfo(pluginAuthInfo);
                    return pluginAuthInfo;
                }
            } else if (authenticationPlugin != null) {
                org.neo4j.server.security.enterprise.auth.plugin.spi.AuthenticationInfo authenticationInfo = authenticationPlugin.authenticate(pluginAuthToken);
                if (authenticationInfo != null) {
                    return PluginAuthenticationInfo.createCacheable(authenticationInfo, getName(), secureHasher);
                }
            }
        } catch (org.neo4j.server.security.enterprise.auth.plugin.api.AuthenticationException | InvalidAuthTokenException e) {
            throw new AuthenticationException(e.getMessage(), e.getCause());
        }
    }
    return null;
}
Also used : AuthInfo(org.neo4j.server.security.enterprise.auth.plugin.spi.AuthInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) ShiroAuthToken(org.neo4j.server.security.enterprise.auth.ShiroAuthToken) ShiroAuthToken(org.neo4j.server.security.enterprise.auth.ShiroAuthToken) AuthToken(org.neo4j.server.security.enterprise.auth.plugin.api.AuthToken) CustomCacheableAuthenticationInfo(org.neo4j.server.security.enterprise.auth.plugin.spi.CustomCacheableAuthenticationInfo) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) InvalidAuthTokenException(org.neo4j.kernel.api.security.exception.InvalidAuthTokenException)

Example 5 with AuthenticationException

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

the class ShiroSecurityProcessor method authenticateUser.

private void authenticateUser(Subject currentUser, ShiroSecurityToken securityToken) {
    boolean authenticated = currentUser.isAuthenticated();
    boolean sameUser = securityToken.getUsername().equals(currentUser.getPrincipal());
    LOG.trace("Authenticated: {}, same Username: {}", authenticated, sameUser);
    if (!authenticated || !sameUser) {
        UsernamePasswordToken token = new UsernamePasswordToken(securityToken.getUsername(), securityToken.getPassword());
        if (policy.isAlwaysReauthenticate()) {
            token.setRememberMe(false);
        } else {
            token.setRememberMe(true);
        }
        try {
            currentUser.login(token);
            LOG.debug("Current user {} successfully authenticated", currentUser.getPrincipal());
        } catch (UnknownAccountException uae) {
            throw new UnknownAccountException("Authentication Failed. There is no user with username of " + token.getPrincipal(), uae.getCause());
        } catch (IncorrectCredentialsException ice) {
            throw new IncorrectCredentialsException("Authentication Failed. Password for account " + token.getPrincipal() + " was incorrect!", ice.getCause());
        } catch (LockedAccountException lae) {
            throw new LockedAccountException("Authentication Failed. The account for username " + token.getPrincipal() + " is locked." + "Please contact your administrator to unlock it.", lae.getCause());
        } catch (AuthenticationException ae) {
            throw new AuthenticationException("Authentication Failed.", ae.getCause());
        }
    }
}
Also used : IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) LockedAccountException(org.apache.shiro.authc.LockedAccountException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

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