AuthenticationEntryPoint никогда не вызывается в Spring Boot

Хэш-решение приятное, но не очень понятное для человека, когда вы хотите узнать, какая версия файла находится в вашей локальной веб-папке. Решение заключается в date/time отпечатать вашу версию, чтобы вы могли легко сравнить ее с файлом сервера.

Например, если ваш файл .js or .css датирован 2011-02-08 15:55:30 (последняя модификация), то версия должна быть равна .js?v=20110208155530

. Должно быть легко читать свойства любого файла на любом языке. В ASP.Net это очень просто ...

".js?v=" + File.GetLastWriteTime(HttpContext.Current.Request.PhysicalApplicationPath + filename).ToString("yyMMddHHHmmss");

Из coz получить его красиво реорганизован в свойства / функции в первую очередь и вы идете. Больше никаких оправданий.

Удачи, Art.

1
задан Carlos Alberto Murillo 16 January 2019 в 17:12
поделиться

1 ответ

Я решил эту проблему с помощью AuthenticationFailureHandler, который вызывается методом unsuccessfulAuthentication, реализованным в AbstractAuthenticationProcessingFilter ... Это код конфигурации:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
            .sessionManagement()
            .sessionCreationPolicy(STATELESS)
            .and()
            .exceptionHandling()
            // this entry point handles when you request a protected page and you are not yet
            // authenticated
            .defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
            .and()
            .authenticationProvider(provider)
            .addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
            .authorizeRequests()
            .requestMatchers(PROTECTED_URLS)
            .authenticated()
            .and()
            .csrf().disable()
            .formLogin().disable()
            .httpBasic().disable()
            .logout().disable()
    ;
}


@Bean
TokenAuthenticationFilter restAuthenticationFilter() throws Exception {
    final TokenAuthenticationFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
    filter.setAuthenticationManager(authenticationManager());
    filter.setAuthenticationSuccessHandler(successHandler());
    filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
    return filter;
}

Это AuthenticationFailureHandler:

[111 ]

В потоке аутентификации, когда я генерирую исключение CredentialsExpiredException, BadCredentialsException или любое исключение аутентификации, вызовет метод unsuccessfulAuthentication из AbstractAuthenticationProcessingFilter и будет выполнять данный AuthenticationFailureHandler:

public final class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private static final String BEARER = "Bearer";

public TokenAuthenticationFilter(final RequestMatcher requiresAuth) {
    super(requiresAuth);
}

@Override
public Authentication attemptAuthentication(
        final HttpServletRequest request,
        final HttpServletResponse response) {
    final String param = ofNullable(request.getHeader(AUTHORIZATION))
            .orElse(request.getParameter("t"));

    final String token = ofNullable(param)
            .map(value -> removeStart(value, BEARER))
            .map(String::trim)
            .orElseThrow(() -> new BadCredentialsException("Missing Authentication Token"));

    final Authentication auth = new UsernamePasswordAuthenticationToken(null, token);
    return getAuthenticationManager().authenticate(auth);
}

@Override
protected void successfulAuthentication(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final FilterChain chain,
        final Authentication authResult) throws IOException, ServletException {
    super.successfulAuthentication(request, response, chain, authResult);
    chain.doFilter(request, response);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
                                          HttpServletResponse response,
                                          AuthenticationException failed)
        throws IOException, ServletException {
    getFailureHandler().onAuthenticationFailure(request, response, failed);
    }
}
0
ответ дан Carlos Alberto Murillo 16 January 2019 в 17:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: