【问题标题】:Spring boot - find username from session cookie valueSpring Boot - 从会话 cookie 值中查找用户名
【发布时间】:2021-10-18 07:55:19
【问题描述】:

我目前正在开发一个 Spring Boot 应用程序,并且我有一个将 HttpServletRequest 作为参数的处理程序。 我想知道,是否有可能调用一个 bean——提供会话 cookie——可以返回谁发出请求的信息? (例如用户名)

【问题讨论】:

  • 你使用 Spring Security 并且用户必须登录吗?
  • @SimonMartinelli 是的,但我解决了,我正在发布解决方案

标签: java spring-boot session-cookies


【解决方案1】:

最后我找到了使代码以期望的方式工作的方法。

package org.my.package;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;


@Slf4j
@Configuration
public class CsrfDeniedHandlerConfig {

    @AllArgsConstructor
    static class CsrfDeniedHandler implements AccessDeniedHandler {

        private final AccessDeniedHandler accessDeniedHandler;

        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
            if (accessDeniedException.getClass().equals(InvalidCsrfTokenException.class)) {
                SecurityContextImpl securityContext = (SecurityContextImpl) request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY);
                User user = (User) securityContext.getAuthentication().getPrincipal();
                log.error("Invalid CSRF token request from {}: {}", user.getUsername().toUpperCase(), accessDeniedException.getMessage());
            }
            accessDeniedHandler.handle(request, response, accessDeniedException);
        }
    }

    @Bean
    public AccessDeniedHandler csrfDeniedHandler() {
        return new CsrfDeniedHandler(new AccessDeniedHandlerImpl());
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 2017-06-12
    • 2020-06-02
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 2020-03-14
    相关资源
    最近更新 更多