All Downloads are FREE. Search and download functionalities are using the official Maven repository.

no.nav.brukerdialog.security.jaspic.TokenLocator Maven / Gradle / Ivy

There is a newer version: 1.2020.02.21_14.01-cdaccec525a6
Show newest version
package no.nav.brukerdialog.security.jaspic;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

import static no.nav.brukerdialog.security.Constants.ID_TOKEN_COOKIE_NAME;
import static no.nav.brukerdialog.security.Constants.REFRESH_TOKEN_COOKIE_NAME;


public class TokenLocator {

    private final String idTokenCookieName;
    private final String refreshTokenCookieName;

    public TokenLocator(String idTokenCookieName, String refreshTokenCookieName) {
        this.idTokenCookieName = idTokenCookieName;
        this.refreshTokenCookieName = refreshTokenCookieName;
    }

    public Optional getToken(HttpServletRequest request) {
        Optional tokenFromCookie = getCookie(request, idTokenCookieName);
        if (tokenFromCookie.isPresent()) {
            return tokenFromCookie;
        }
        return getTokenFromHeader(request);
    }

    public Optional getRefreshToken(HttpServletRequest request) {
        return getCookie(request, refreshTokenCookieName);
    }

    private Optional getCookie(HttpServletRequest request, String cookieName) {
        if (request.getCookies() == null) {
            return Optional.empty();
        }
        for (javax.servlet.http.Cookie c : request.getCookies()) {
            if (c.getName().equals(cookieName) && c.getValue() != null) {
                return Optional.of(c.getValue());
            }
        }
        return Optional.empty();
    }

    public static Optional getTokenFromHeader(HttpServletRequest request) {
        String headerValue = request.getHeader("Authorization");
        return headerValue != null && !headerValue.isEmpty() && headerValue.startsWith("Bearer ")
                ? Optional.of(headerValue.substring("Bearer ".length()))
                : Optional.empty();
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy