有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何让自定义过滤器继续执行Spring会话?

我有这个代码,它似乎工作正常

滤器

public class JsonAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final ObjectMapper objectMapper;
    private final Validator validator;

    protected JsonAuthenticationFilter(
        final RequestMatcher matcher,
        final ObjectMapper objectMapper,
        final Validator validator
    ) {
        super( matcher );
        this.objectMapper = objectMapper;
        this.validator = validator;
    }

    @Override
    public Authentication attemptAuthentication( final HttpServletRequest request, final HttpServletResponse response )
        throws AuthenticationException, IOException, ServletException {

        PasswordCredentials credentials;
        try {
            credentials = objectMapper.readValue( request.getReader(), PasswordCredentials.class );
            DataBinder dataBinder = new DataBinder( credentials );
            dataBinder.setValidator( validator );
            dataBinder.validate();
        } catch ( final Exception e ) {
            throw new BadRequestException( "Bad Request", e );
        }

        AbstractAuthenticationToken authRequest = credentials.toAuthenticationToken();

        setDetails( request, authRequest );

        return this.getAuthenticationManager().authenticate( authRequest );
    }

    protected void setDetails( HttpServletRequest request, AbstractAuthenticationToken authRequest ) {
        authRequest.setDetails( authenticationDetailsSource.buildDetails( request ) );
    }

    @Override
    @Autowired
    public void setAuthenticationManager( final AuthenticationManager authenticationManager ) {
        super.setAuthenticationManager( authenticationManager );
    }
}

过滤器配置

@Configuration
class FilterConfig {

    @Bean
    AuthenticationSuccessHandler successHandler() {
        return new MySavedRequestAwareAuthenticationSuccessHandler();
    }

    @Bean
    AuthenticationFailureHandler failureHandler() {
        return new SimpleUrlAuthenticationFailureHandler();
    }

    @Bean
    JsonAuthenticationFilter authenticationFilter( final ObjectMapper mapper, final Validator validator ) {
        RequestMatcher matcher = new AndRequestMatcher( Arrays.asList(
            new AntPathRequestMatcher( "/authentication/password", "POST" ),
            new MediaTypeRequestMatcher( new ContentTypeContentNegotiationStrategy(),
                MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8 )
        ) );

        JsonAuthenticationFilter filter = new JsonAuthenticationFilter( matcher, mapper, validator );
        filter.setAuthenticationSuccessHandler( successHandler() );
        filter.setAuthenticationFailureHandler( failureHandler() );
        return filter;
    }
}

安全配置

@Configuration
@Order( SecurityConstants.WEB_SECURITY_CONFIG + 2 )
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final JsonAuthenticationFilter authenticationFilter;

    WebSecurityConfig( final JsonAuthenticationFilter authenticationFilter ) {
        this.authenticationFilter = authenticationFilter;
    }

    @Bean
    SessionRepository<ExpiringSession> sessionRepository() {
        return new MapSessionRepository();
    }

    @Override
    protected void configure( final HttpSecurity http ) throws Exception {
        http
            .exceptionHandling()
            .authenticationEntryPoint( ( request, response, authException ) -> {
                response.sendError( HttpServletResponse.SC_UNAUTHORIZED );
            } )
            .and()
            .addFilterAt( authenticationFilter, UsernamePasswordAuthenticationFilter.class )
            .formLogin()
            .and()
            .csrf().disable();
    }

我使用这个测试来验证登录是否完成了所有适当的操作,它在缺少的Set-Cookie头上失败

@SpringBootTest
@AutoConfigureMockMvc
@RunWith( SpringRunner.class )
public class AuthenticationTest extends AbstractSecurityTest {
    @Autowired
    private MockMvc mvc;
    @Autowired
    private Gson gson;

    @Test
    public void validLogin() throws Exception {
        log.debug( "posting password" );
        String json = gson.toJson( new PasswordCredentials( name, pass ) );
        this.mvc.perform(
            post( "/authentication/password" )
                .contentType( MediaType.APPLICATION_JSON )
                .content( json ) )
            .andExpect( header().string( "Set-Cookie", startsWith( "SESSION" ) ) )
            .andExpect( status().is2xxSuccessful() );
    }

它不会继续创建会话,或者假设,如果我只是简单地进行表单登录,我会得到许多其他东西。我在这里展示的内容之外尝试了很多东西,这只是我当前的迭代。注意:在Spring平台RC1中使用版本为的Spring引导

我需要添加/删除什么才能让它继续执行与使用formLogin时相同的操作


共 (0) 个答案