io.lsn.spring.auth.transport.header.OutAuthCookieWriter Maven / Gradle / Ivy
package io.lsn.spring.auth.transport.header;
import io.lsn.spring.auth.entity.User;
import io.lsn.spring.auth.transport.InOutSignature;
import io.lsn.spring.auth.transport.cookie.CookieAuthHelper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@ControllerAdvice
@ConditionalOnProperty(name = "io.lsn.spring.security.transportMethod", havingValue = "COOKIE", matchIfMissing = false)
public class OutAuthCookieWriter implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof UsernamePasswordAuthenticationToken
&& !(authentication.getPrincipal() instanceof String)
&& request instanceof ServletServerHttpRequest
&& response instanceof ServletServerHttpResponse) {
User user = (User) authentication.getPrincipal();
ServletServerHttpResponse servletResponse = (ServletServerHttpResponse) (response);
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
// set cookie only if not available in request or different value
Cookie[] cookies = servletRequest.getCookies() != null ? servletRequest.getCookies() : new Cookie[0];
Cookie authCookie = Arrays.asList(cookies).stream()
.filter(cookie -> InOutSignature.AUTH_TOKEN_NAME.equalsIgnoreCase(cookie.getName()))
.findFirst().orElse(null);
if (authCookie == null || !user.getApiToken().getToken().equals(authCookie.getValue())) {
servletResponse.getServletResponse().addCookie(CookieAuthHelper.buildCookie(servletRequest, user, false));
}
}
return body;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy