用户已通过过滤器认证,但未被控制器接收

时间:2020-01-10 09:08:35

标签: spring spring-boot kotlin spring-security

我目前有一个自定义的登录过滤器,除了创建虚拟的Authentication对象外,它什么都不做。当我向/ test提交请求时,我得到一个没有输出的空白页面。预期的输出应该是hello user!

这是控制器

@RestController
class TestController {
    @GetMapping("/test")
    fun getTest(): String {
        return "hello user!";
    }
}

TokenAuthenticationFilter

open class TokenAuthenticationFilter : AbstractAuthenticationProcessingFilter {
    private val log: Logger = LogManager.getLogger(TokenAuthenticationFilter::class.java)

    constructor(authenticationManager: AuthenticationManager) : super("/**") {
        setAuthenticationManager(authenticationManager);
    }

    override fun requiresAuthentication(request: HttpServletRequest?, response: HttpServletResponse?): Boolean {
        return true
    }

    @Throws(AuthenticationException::class)
    override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse?): Authentication? {
        val header = request.getHeader("Authorization")
        if (header == null || !header.startsWith("Bearer ")) {
            throw BadCredentialsException("No token found in request headers")
        }

        val authentication = UsernamePasswordAuthenticationToken("jon", "password");
        return authenticationManager.authenticate(authentication);
    }

    @Throws(IOException::class, ServletException::class)
    override fun successfulAuthentication(req: HttpServletRequest?,
                                          res: HttpServletResponse,
                                          chain: FilterChain?,
                                          auth: Authentication) {

        log.info("successfulAuthentication: success!!!")

        //Is this part supposed to be blank?
    }
}

提交请求时,我在控制台中看到successfulAuthentication: success!!!

AuthorizationConfig

@Configuration
@EnableWebSecurity(debug = true)
class AuthorizationConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    @Throws(Exception::class)
    fun configureGlobal(authenticationManager: AuthenticationManagerBuilder) {
        authenticationManager.inMemoryAuthentication()
                .withUser("jon").password("{noop}password").authorities("ROLE_USER")
                .and()
                .withUser("admin").password("{noop}PASSWORD").authorities("ROLE_USER", "ROLE_ADMIN");
    }

    override fun configure(http: HttpSecurity) {
        http.exceptionHandling()
                .authenticationEntryPoint(RestAuthenticationEntryPoint())
                .and()
                .addFilterAfter(TokenAuthenticationFilter(authenticationManager()), LogoutFilter::class.java)
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated();
    }
}

所以..我想我已经正确连接了,但是响应完全空白。 感谢指导!

更新

好的,我设法使其正常运行,但我不知道为什么。 我使用新的成功处理程序(NoRedirectStrategy)更新了AuthorizationConfig的configure方法。

    override fun configure(http: HttpSecurity) {
        val successHandler = SimpleUrlAuthenticationSuccessHandler()
        successHandler.setRedirectStrategy(NoRedirectStrategy())

        var tokenAuthFilter = TokenAuthenticationFilter();
        tokenAuthFilter.setAuthenticationManager(authenticationManager());
        tokenAuthFilter.setAuthenticationSuccessHandler(successHandler);

        http.exceptionHandling()
                .authenticationEntryPoint(RestAuthenticationEntryPoint())
                .and()
                .sessionManagement()
                .sessionCreationPolicy(STATELESS)
                .and()
                .addFilterAfter(tokenAuthFilter, AnonymousAuthenticationFilter::class.java)
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable()
                .authorizeRequests()
                .anyRequest().authenticated();
    }

并且我更新了过滤器,使其包含super.successfulAuthentication()chain.doFilter

    @Throws(IOException::class, ServletException::class)
    override fun successfulAuthentication(request: HttpServletRequest?,
                                          response: HttpServletResponse,
                                          chain: FilterChain?,
                                          auth: Authentication) {
        log.info("successfulAuthentication: success!!!")
        super.successfulAuthentication(request, response, chain, auth);
        chain!!.doFilter(request, response);
    }

为什么这样做?

0 个答案:

没有答案