在AbstractPreAuthenticatedProcessingFilter中设置SecurityContext

时间:2019-05-01 15:35:26

标签: java spring spring-security

我正在尝试使用PreAuthenticatedAuthenticationToken中的AbstractPreAuthenticatedProcessingFilter对用户进行身份验证。在MyPreAuthenticationFilter中,我这样做的是:

    @Override
    public Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        String session = getSession(request); // not JSESSIONID, custom session
        UserInfo user = getUser(session); // custom user object

        Authentication auth = new PreAuthenticatedAuthenticationToken(
            user,
            session,
            Arrays.asList(
                new SimpleGrantedAuthority("ROLE_USER")
            )
       );
       SecurityContextHolder.getContext().setAuthentication(auth);
       return userInfo;
    }

这是我的SecurityConfig

    @Autowired
    AuthenticationManager authenticationManager;

    @Bean
    public MyPreAuthenticationFilter preAuthenticationFilter() {
        return new MyPreAuthenticationFilter(authenticationManager);
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
            .addFilterBefore(preAuthenticationFilter(), BasicAuthenticationFilter.class)
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .antMatcher("/login/oauth/authorize")
            .authorizeRequests().anyRequest().authenticated()
        .and()
            .httpBasic()
            .authenticationEntryPoint(new OAuth2EntryPoint("/login?path=/login/oauth/authorize"))
        .and()
            .csrf().disable();
    }

我正尝试通过托管在/login/oauth/authorize上的自定义登录页面来保护/login,该页面重定向到path参数。但是,在访问此URL时,我在Spring Security过滤器链的末尾找到了该日志

org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS

为什么MyPreAuthenticationFilter不对Spring SecurityContext进行身份验证?

0 个答案:

没有答案