1
我正在使用Spring-MVC和Spring-Security開發Web應用程序。處理Spring Security的身份驗證提供程序中引發的BadCredentialsException
我使用了AuthenticationProvider的自定義登錄,而AuthenticationProvider又使用UserDetailsService將登錄表單中的數據與數據庫中的數據進行匹配。
我想在AuthenticationProvider中拋出2個異常,第一次當用戶名不存在於數據庫中時,另一次當密碼不同時。
我想要做的是在我的網頁上顯示拋出的異常(錯誤的用戶名或密碼錯誤)的錯誤消息,但我不知道在哪裏使用catch塊,因爲登錄流是通過彈簧安全
的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>
正如我所見,他不會在他的CustomAuthenticationProvider中的userDetailsService中拋出異常,而是所有的邏輯都在CustomAuthenticationProvider中執行,他希望在提供者中拋出不同的錯誤消息,所以在他的情況下如何看到thymeleaf中的錯誤文本? – makson