gpt4 book ai didi

Spring 安全 : Access the current authenticated User inside a servlet Filter

转载 作者:IT老高 更新时间:2023-10-28 13:58:13 30 4
gpt4 key购买 nike

我最近开始学习 Spring Security,今天我遇到了一个基本的(我相信的)问题:为什么我不能访问 Servlet 过滤器中的当前 Principal,如下面的类(class)所示:

package com.acme.test;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class TestFilter implements Filter {

/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub

}

/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication auth = securityContext.getAuthentication();

// auth is null here

chain.doFilter(request, response);
}

/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
// TODO Auto-generated method stub

}

}

使用 Authentication auth = securityContext.getAuthentication(); 检索到的 Authentication 对象为空。在 MVC @Controller 中使用上面的代码片段可以正常工作(如预期的那样)。

为什么会这样?

最佳答案

doFilter里面:

HttpServletRequest request = (HttpServletRequest) request;
HttpSession session = request.getSession(false);

SecurityContextImpl sci = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");

if (sci != null) {
UserDetails cud = (UserDetails) sci.getAuthentication().getPrincipal();
// do whatever you need here with the UserDetails
}

希望对你有帮助

关于 Spring 安全 : Access the current authenticated User inside a servlet Filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26126586/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com