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

io.lsn.spring.auth.transport.header.OutAuthHeaderWriter 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 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.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;

@ControllerAdvice
@ConditionalOnProperty(name = "io.lsn.spring.security.transportMethod", havingValue = "HEADER", matchIfMissing = true)
public class OutAuthHeaderWriter 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)
                && response instanceof ServletServerHttpResponse) {
            User user = (User) authentication.getPrincipal();
            ServletServerHttpResponse servletResponse = (ServletServerHttpResponse) (response);
            servletResponse.getServletResponse().setHeader(InOutSignature.AUTH_TOKEN_NAME, user.getAuthToken());
        }
        return body;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy