Search in sources :

Example 6 with AuthenticationException

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

the class TestKillBillJdbcRealm method testAuthentication.

@Test(groups = "slow")
public void testAuthentication() throws SecurityApiException {
    final String username = "toto";
    final String password = "supperCompli43cated";
    securityApi.addRoleDefinition("root", ImmutableList.of("*"), callContext);
    securityApi.addUserRoles(username, password, ImmutableList.of("root"), callContext);
    final DelegatingSubject subject = new DelegatingSubject(securityManager);
    final AuthenticationToken goodToken = new UsernamePasswordToken(username, password);
    securityManager.login(subject, goodToken);
    Assert.assertTrue(true);
    try {
        final AuthenticationToken badToken = new UsernamePasswordToken(username, "somethingelse");
        securityManager.login(subject, badToken);
        Assert.assertTrue(true);
        securityManager.logout(subject);
        securityManager.login(subject, badToken);
        Assert.fail("Should not succeed to login with an incorrect password");
    } catch (final AuthenticationException e) {
    }
    // Update password and try again
    final String newPassword = "suppersimple";
    securityApi.updateUserPassword(username, newPassword, callContext);
    try {
        final AuthenticationToken notGoodTokenAnyLonger = goodToken;
        securityManager.login(subject, notGoodTokenAnyLonger);
        Assert.fail("Should not succeed to login with an incorrect password");
    } catch (final AuthenticationException e) {
    }
    final AuthenticationToken newGoodToken = new UsernamePasswordToken(username, newPassword);
    securityManager.login(subject, newGoodToken);
    Assert.assertTrue(true);
    securityManager.logout(subject);
    securityApi.invalidateUser(username, callContext);
    try {
        final AuthenticationToken notGoodTokenAnyLonger = goodToken;
        securityManager.login(subject, notGoodTokenAnyLonger);
        Assert.fail("Should not succeed to login with an incorrect password");
    } catch (final AuthenticationException e) {
    }
}
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 7 with AuthenticationException

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

the class KillBillJndiLdapRealm method findLDAPGroupsForUser.

private Set<String> findLDAPGroupsForUser(final PrincipalCollection principals, final LdapContextFactory ldapContextFactory) throws NamingException {
    final String username = (String) getAvailablePrincipal(principals);
    LdapContext systemLdapCtx = null;
    try {
        systemLdapCtx = ldapContextFactory.getSystemLdapContext();
        return findLDAPGroupsForUser(username, systemLdapCtx);
    } catch (AuthenticationException ex) {
        log.info("LDAP authentication exception='{}'", ex.getLocalizedMessage());
        return ImmutableSet.<String>of();
    } finally {
        LdapUtils.closeContext(systemLdapCtx);
    }
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) LdapContext(javax.naming.ldap.LdapContext)

Example 8 with AuthenticationException

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

the class ShiroAuthenticationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (securityContext instanceof ShiroSecurityContext) {
        final ShiroSecurityContext context = (ShiroSecurityContext) securityContext;
        final Subject subject = context.getSubject();
        LOG.trace("Authenticating... {}", subject);
        if (!subject.isAuthenticated()) {
            try {
                LOG.trace("Logging in {}", subject);
                context.loginSubject();
            } catch (LockedAccountException e) {
                LOG.debug("Unable to authenticate user, account is locked.", e);
                throw new NotAuthorizedException(e, "Basic realm=\"Graylog Server\"");
            } catch (AuthenticationException e) {
                LOG.debug("Unable to authenticate user.", e);
                throw new NotAuthorizedException(e, "Basic realm=\"Graylog Server\"");
            }
        }
    } else {
        throw new NotAuthorizedException("Basic realm=\"Graylog Server\"");
    }
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) SecurityContext(javax.ws.rs.core.SecurityContext) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Subject(org.apache.shiro.subject.Subject) LockedAccountException(org.apache.shiro.authc.LockedAccountException)

Example 9 with AuthenticationException

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

the class SessionsResource method newSession.

@POST
@ApiOperation(value = "Create a new session", notes = "This request creates a new session for a user or reactivates an existing session: the equivalent of logging in.")
@NoAuditEvent("dispatches audit events in the method body")
public SessionResponse newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Username and credentials", required = true) @Valid @NotNull SessionCreateRequest createRequest) {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (!(securityContext instanceof ShiroSecurityContext)) {
        throw new InternalServerErrorException("Unsupported SecurityContext class, this is a bug!");
    }
    final ShiroSecurityContext shiroSecurityContext = (ShiroSecurityContext) securityContext;
    // we treat the BASIC auth username as the sessionid
    final String sessionId = shiroSecurityContext.getUsername();
    // pretend that we had session id before
    Serializable id = null;
    if (sessionId != null && !sessionId.isEmpty()) {
        id = sessionId;
    }
    final String remoteAddrFromRequest = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
    final Subject subject = new Subject.Builder().sessionId(id).host(remoteAddrFromRequest).buildSubject();
    ThreadContext.bind(subject);
    final Session s = subject.getSession();
    try {
        subject.login(new UsernamePasswordToken(createRequest.username(), createRequest.password()));
        final User user = userService.load(createRequest.username());
        if (user != null) {
            long timeoutInMillis = user.getSessionTimeoutMs();
            s.setTimeout(timeoutInMillis);
        } else {
            // set a sane default. really we should be able to load the user from above.
            s.setTimeout(TimeUnit.HOURS.toMillis(8));
        }
        s.touch();
        // save subject in session, otherwise we can't get the username back in subsequent requests.
        ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
    } catch (AuthenticationException e) {
        LOG.info("Invalid username or password for user \"{}\"", createRequest.username());
    } catch (UnknownSessionException e) {
        subject.logout();
    }
    if (subject.isAuthenticated()) {
        id = s.getId();
        final Map<String, Object> auditEventContext = ImmutableMap.of("session_id", id, "remote_address", remoteAddrFromRequest);
        auditEventSender.success(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        // TODO is the validUntil attribute even used by anyone yet?
        return SessionResponse.create(new DateTime(s.getLastAccessTime(), DateTimeZone.UTC).plus(s.getTimeout()).toDate(), id.toString());
    } else {
        final Map<String, Object> auditEventContext = ImmutableMap.of("remote_address", remoteAddrFromRequest);
        auditEventSender.failure(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        throw new NotAuthorizedException("Invalid username or password", "Basic realm=\"Graylog Server session\"");
    }
}
Also used : Serializable(java.io.Serializable) User(org.graylog2.plugin.database.users.User) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownSessionException(org.apache.shiro.session.UnknownSessionException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Subject(org.apache.shiro.subject.Subject) DateTime(org.joda.time.DateTime) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) SecurityContext(javax.ws.rs.core.SecurityContext) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Session(org.apache.shiro.session.Session) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 10 with AuthenticationException

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

the class GreenStepBaseFormAuthenticationFilter method executeLogin.

protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
    GreenStepBaseUsernamePasswordToken token = (GreenStepBaseUsernamePasswordToken) this.createToken(request, response);
    try {
        this.doCaptchaValidate((HttpServletRequest) request, token);
        AccountVO account = this.queryUser(token.getUsername());
        this.userValidate(account);
        Subject subject = this.getSubject(request, response);
        subject.login(token);
        // set session
        this.setUserSession((HttpServletRequest) request, (HttpServletResponse) response, account);
        return this.onLoginSuccess(token, subject, request, response);
    } catch (AuthenticationException e) {
        // clear session	
        UserAccountHttpSessionSupport.remove((HttpServletRequest) request);
        this.getSubject(request, response).logout();
        return this.onLoginFailure(token, e, request, response);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.apache.shiro.authc.AuthenticationException) AccountVO(com.netsteadfast.greenstep.vo.AccountVO) Subject(org.apache.shiro.subject.Subject)

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