处理在Spring Security的身份验证提供程序中抛出的BadCredentialsException

时间:2017-02-21 12:35:49

标签: java authentication spring-security exception-handling

我正在使用Spring-MVC和Spring-Security来开发Web应用程序。

我正在使用AuthenticationProvider进行自定义登录,而AuthenticationProvider又使用UserDetailsS​​ervice将登录表单中的数据与数据库中的数据进行匹配。

我想在AuthenticationProvider中抛出2个异常,第一个是db中没有用户名,另一个是密码不同时。

我想要做的是在我的网页上显示抛出异常的错误消息(错误的用户名或错误的密码),但我不知道在哪里使用catch块,因为登录流程是受管理的通过Spring-Security

的AuthenticationProvider

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    CustomUserDetailsService userDetails;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        Customer customer = userDetails.loadUserByUsername(username);

        if(customer == null) {
            throw new BadCredentialsException("Wrong username");
        }

        if(!password.equals(customer.getPassword())) {
            throw new BadCredentialsException("Wrong password");
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(customer.getRole()));

        return new UsernamePasswordAuthenticationToken(customer, password, authorities);
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.equals(UsernamePasswordAuthenticationToken.class);
    }
}

登录页面

[...]
<div class="form">
    <h2>Login</h2>
    <form th:action="@{/login}" method="POST" th:object="${customer}">
        <input type="text" placeholder="Username" name="username" th:field="*{username}"/> 
        <input type="password" placeholder="Password" name="password" th:field="*{password}"/>
        <button type="submit">Login</button>
    </form>
</div>
[...]

弹簧security.xml文件

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http pattern="/resources/**" security="none" />

    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/user/**" access="hasRole('USER')" />
        <form-login authentication-failure-url="/login" login-page="/login"
            login-processing-url="/login" default-target-url="/user" />
        <logout invalidate-session="true" success-handler-ref="logoutSuccessHandler" />
    </http>

    <authentication-manager>
        <authentication-provider ref="customAuthenticationProvider" />
    </authentication-manager>
</beans:beans>

1 个答案:

答案 0 :(得分:0)

使用Thymeleaf时,您可以“捕获”这样的身份验证异常:

<p th:if="${param.error != null and session['SPRING_SECURITY_LAST_EXCEPTION'] != null}"
   th:text="${session['SPRING_SECURITY_LAST_EXCEPTION'].message}">
  Wrong username or password
</p>

您可以使用标准DaoAuthenticationProvider而不是自定义类:

@Bean
public DaoAuthenticationProvider customAuthenticationProvider()
{
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setUserDetailsService(userDetailsService);
    provider.setHideUserNotFoundExceptions(false);
    return provider;
}

请注意,通常不建议在身份验证失败时判断系统中是否存在用户名。