use of org.mycore.restapi.v1.MCRRestAPIAuthentication in project mycore by MyCoRe-Org.
the class MCRSessionFilter method addJWTToResponse.
/**
* If request was authenticated via JSON Web Token add a new token if <code>aud</code> was
* {@link MCRRestAPIAuthentication#AUDIENCE}.
*
* If the response has a status code that represents a client error (4xx), the JSON Web Token is ommited.
* If the response already has a JSON Web Token no changes are made.
*/
private static void addJWTToResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
boolean renewJWT = Optional.ofNullable(requestContext.getProperty(PROP_RENEW_JWT)).map(Boolean.class::cast).orElse(Boolean.FALSE);
Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).filter(s -> s.startsWith("Bearer ")).filter(s -> !responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.CLIENT_ERROR)).filter(s -> responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null).map(h -> renewJWT ? ("Bearer " + MCRRestAPIAuthentication.getToken(currentSession, currentSession.getCurrentIP()).orElseThrow(() -> new InternalServerErrorException("Could not get JSON Web Token"))) : h).ifPresent(h -> {
responseContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, h);
// Authorization header may never be cached in public caches
Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.CACHE_CONTROL)).map(RuntimeDelegate.getInstance().createHeaderDelegate(CacheControl.class)::fromString).filter(cc -> !cc.isPrivate()).ifPresent(cc -> {
cc.setPrivate(true);
responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
});
});
}
Aggregations