public Optional<Session> login(@Nullable String currentSessionId, String host,
                                   ActorAwareAuthenticationToken authToken) throws AuthenticationServiceUnavailableException {

        final String previousSessionId = StringUtils.defaultIfBlank(currentSessionId, null);
        final Subject subject = new Subject.Builder().sessionId(previousSessionId).host(host).buildSubject();

        ThreadContext.bind(subject);

        try {
            final Session session = subject.getSession();

            subject.login(authToken);

            return createSession(subject, session, host);
        } catch (AuthenticationServiceUnavailableException e) {
            log.info("Session creation failed due to authentication service being unavailable. Actor: \"{}\"",
                    authToken.getActor().urn());
            final Map<String, Object> auditEventContext = ImmutableMap.of(
                    "remote_address", host,
                    "message", "Authentication service unavailable: " + e.getMessage()
            );
            auditEventSender.failure(authToken.getActor(), SESSION_CREATE, auditEventContext);
            throw e;
        } catch (AuthenticationException e) {
            log.info("Invalid credentials in session create request. Actor: \"{}\"", authToken.getActor().urn());
            final Map<String, Object> auditEventContext = ImmutableMap.of(
                    "remote_address", host
            );
            auditEventSender.failure(authToken.getActor(), SESSION_CREATE, auditEventContext);
            return Optional.empty();
        }
    }
@Test
    public void throwingRealmDoesNotInhibitAuthentication() {
        setUpUserMock();

        assertFalse(SecurityUtils.getSubject().isAuthenticated());

        // Put a throwing realm in the first position. Authentication should still be successful, because the second
        // realm will find an account for the user
        final List<Realm> realms = new ArrayList<>(securityManager.getRealms());
        realms.add(0, throwingRealm());
        securityManager.setRealms(realms);

        assertThat(sessionCreator.login(null, "host", validToken)).isPresent();
        assertThat(SecurityUtils.getSubject().isAuthenticated()).isTrue();
        verify(auditEventSender).success(eq(AuditActor.user("username")), anyString(), anyMap());
    }