@Override
    public Optional<UserIdentity> getApiUserIdentity(final HttpServletRequest request) {
        Optional<UserIdentity> optUserIdentity = Optional.empty();

        if (IdpType.NO_IDP.equals(idpType)) {
            throw new IllegalStateException(
                    "Attempting to get user identity from tokens in request when " +
                    "identityProviderType set to NONE.");
        } else {
            // See if we can log in with a token if one is supplied. It is valid for it to not be present.
            // e.g. the front end calling API methods, as the user is held in session.
            try {
                final Optional<JwtContext> optJwtContext = jwtContextFactory.getJwtContext(request);

                optUserIdentity = optJwtContext.flatMap(jwtContext ->
                                mapApiIdentity(jwtContext, request))
                        .or(() -> {
                            LOGGER.trace(() ->
                                    "No JWS found in headers in request to " + request.getRequestURI());
                            return Optional.empty();
                        });
            } catch (final RuntimeException e) {
                throw new AuthenticationException("Error authenticating request to "
                                                  + request.getRequestURI() + " - " + e.getMessage(), e);
            }

            if (optUserIdentity.isEmpty()) {
                LOGGER.trace(() -> "Cannot get a valid JWS for API request to " + request.getRequestURI());
            } else {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Got API user identity "
                                 + optUserIdentity.map(Objects::toString).orElse("EMPTY"));
                }
            }
        }
        return optUserIdentity;
    }
Map the IDP identity provided by the {@link JwtContext} and the
{@link TokenResponse}to a local user. This is for use in a UI based
authentication flow.

@param jwtContext    The identity on the IDP to map to a local user.
@param request       The HTTP request
@param tokenResponse The token received from the IDP.
@return A local {@link UserIdentity} if the identity can be mapped.
stroom-security/stroom-security-common-impl/src/main/java/stroom/security/common/impl/AbstractUserIdentityFactory.java