Search in sources :

Example 1 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project zeppelin by apache.

the class ZeppelinHubRealm method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authToken;
    if (StringUtils.isBlank(token.getUsername())) {
        throw new AccountException("Empty usernames are not allowed by this realm.");
    }
    String loginPayload = createLoginPayload(token.getUsername(), token.getPassword());
    User user = authenticateUser(loginPayload);
    LOG.debug("{} successfully login via ZeppelinHub", user.login);
    return new SimpleAuthenticationInfo(user.login, token.getPassword(), name);
}
Also used : AccountException(org.apache.shiro.authc.AccountException) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 2 with UsernamePasswordToken

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

the class PasswordAlgorithmCredentialsMatcher method doCredentialsMatch.

@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    if (token instanceof UsernamePasswordToken && info instanceof UserAccount) {
        final UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        final UserAccount userAccount = (UserAccount) info;
        final User user = userAccount.getUser();
        return user.isUserPassword(String.valueOf(usernamePasswordToken.getPassword()));
    } else {
        return false;
    }
}
Also used : User(org.graylog2.plugin.database.users.User) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 3 with UsernamePasswordToken

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

the class PasswordAuthenticator method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authToken;
    LOG.debug("Retrieving authc info for user {}", token.getUsername());
    final User user = userService.load(token.getUsername());
    if (user == null || user.isLocalAdmin()) {
        // skip the local admin user here, it's ugly, but for auth that user is treated specially.
        return null;
    }
    if (user.isExternalUser()) {
        // we don't store passwords for LDAP users, so we can't handle them here.
        LOG.trace("Skipping mongodb-based password check for LDAP user {}", token.getUsername());
        return null;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Found user {} to be authenticated with password.", user.getName());
    }
    return new UserAccount(token.getPrincipal(), user.getHashedPassword(), credentialsSalt, "graylog2MongoDbRealm", user);
}
Also used : User(org.graylog2.plugin.database.users.User) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 4 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken 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 5 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken 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

UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)114 Subject (org.apache.shiro.subject.Subject)50 Test (org.junit.Test)30 AuthenticationException (org.apache.shiro.authc.AuthenticationException)28 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)27 SimpleAuthenticationInfo (org.apache.shiro.authc.SimpleAuthenticationInfo)17 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)11 Test (org.testng.annotations.Test)11 LockedAccountException (org.apache.shiro.authc.LockedAccountException)10 IncorrectCredentialsException (org.apache.shiro.authc.IncorrectCredentialsException)9 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 UnknownAccountException (org.apache.shiro.authc.UnknownAccountException)7 DelegatingSubject (org.apache.shiro.subject.support.DelegatingSubject)7 Session (org.apache.shiro.session.Session)6 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)6 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 AuthorizationInfo (org.apache.shiro.authz.AuthorizationInfo)4 AbstractQi4jTest (org.qi4j.test.AbstractQi4jTest)4