在过滤器中设置用户主体

时间:2017-12-10 00:28:13

标签: jax-rs servlet-filters

我有一个实现过滤器的身份验证过滤器。

通过将ServletRequest编程到HTTPServletRequest,我可以获得userPrincipal。

public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain)
        throws IOException, ServletException {



    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

 // code to resolve user name from apikey

    Principal principal = httpServletRequest.getUserPrincipal();

我的问题是如何设置校长?这样我就可以传入经过身份验证的用户名;

或者我应该使用HttpServletRequestWrapper将名称作为附加参数传递?

2 个答案:

答案 0 :(得分:0)

实际上我没有意识到HttpServletRequestWrapper有getUserPrincipal()方法我可以覆盖

答案 1 :(得分:0)

假设您在禁用spring安全性时需要委托人在场。请参考以下链接以禁用安全性https://stackoverflow.com/a/61120549/6459098

我们需要以下拦截器和UserDetailsS​​ervice才能为每个请求提供自定义主体。

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if(request.getUserPrincipal()==null)//initially no principal found
            request.login("uname", "pwd");//add principal to request
        return true;
    }

然后

@Component
class UserDetailsServiceTools implements UserDetailsService {
    @Override
        public UserDetails loadUserByUsername(String username){
            // TODO Auto-generated method stub
                return User.withUsername(username).password("{noop}pwd").roles("User").build();
        }
}