春季安全认证错误不显示

时间:2019-07-16 19:30:39

标签: spring-boot spring-security

我使用Spring Security和Spring Boot。

如果用户无法连接到系统,我想得到spring安全错误。

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationEventPublisher authenticationEventPublisher;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Autowired
    private CustomLogoutHandler customLogoutHandler;

    @Configuration
    public class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationEventPublisher(authenticationEventPublisher).userDetailsService(userDetailsService)
                    .passwordEncoder(passwordEncoder);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/i18n/**", "/css/**", "/webjars/**", "/js/**", "/img/**", "/").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().loginPage("/login").permitAll()
                    .successHandler(customAuthenticationSuccessHandler)
                    .failureHandler(customAuthenticationFailureHandler)
                    .and()
                    .logout().logoutUrl("/logout").logoutSuccessHandler(customLogoutHandler)
                    .logoutSuccessUrl("/login")
                    .and().csrf().disable();
        }


        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/i18n/**", "/css/**", "/webjars/**", "/js/**", "/img/**");
        }
    }
}


Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private MessageSource messages;

    @Autowired
    private LocaleResolver localeResolver;

    @Override
    public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException {

        setDefaultFailureUrl("/login?error=true");

        super.onAuthenticationFailure(request, response, exception);

        final Locale locale = localeResolver.resolveLocale(request);

        String errorMessage = messages.getMessage("message.badCredentials", null, locale);

        if (exception.getMessage().equalsIgnoreCase("User is disabled")) {
            errorMessage = messages.getMessage("auth.message.disabled", null, locale);
        } else if (exception.getMessage().equalsIgnoreCase("User account has expired")) {
            errorMessage = messages.getMessage("auth.message.expired", null, locale);
        } else if (exception.getMessage().equalsIgnoreCase("blocked")) {
            errorMessage = messages.getMessage("auth.message.blocked", null, locale);
        }

        request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, errorMessage);
    }
}



@Controller
public class LoginController {

    @GetMapping(value = {"/", "login"})
    public String login() throws Exception {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!"anonymousUser".equals(auth.getPrincipal())) {
            Users user = ((CustomUserDetails) auth.getPrincipal()).getUsers();
            if (user != null) {
                return "redirect:/main";
            }
        }

        return "login/login";
    }

}

如果用户转到/ login,请输入错误信息,请参见浏览器中的调试

show picture

<div th:if="${param.error}">
    <div class="alert alert-danger"
        th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message} + ': Error !'">Error!</div>
</div>

不显示任何内容,尝试直接错误,结果相同。

0 个答案:

没有答案