Hi các bạn, mình đang nghiên cứu về spring security và có thắc mắc về việc hiển thị lỗi trong quá trình đặng nhập, hy vọng được mọi người giúp đỡ
WebSecurityConfig
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/", "/login", "/logout").permitAll();
http.authorizeRequests()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/")
.failureUrl("/login?error=true");
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/logout-successful");
}
UserDetailsServiceImpl
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> opt = repository.findByUsername(username);
if (!opt.isPresent()) {
// (1) Tài khoản không tồn tại
throw new UsernameNotFoundException("User was not found!");
}
User user = opt.get();
if (user.getStatus == 0) {
// (2) Tài khoản chưa kích hoạt
}
// (3) mật khẩu không đúng
List<String> listRoles = repository.getListRolesByUserId(user.getUserId());
List<GrantedAuthority> listGrants = new ArrayList<>();
if (listRoles != null) {
for (String role : listRoles) {
listGrants.add(new SimpleGrantedAuthority(role));
}
}
return (UserDetails) new org.springframework.security.core
.userdetails.User(user.getUsername(), user.getPassword(), listGrants);
}
Vậy làm thế nào để hiển thị các lỗi (1), (2), (3) nếu trên login view cho người dùng biết. Mình tìm thử nhưng chỉ thấy hướng dẫn bằng cách kiểm tra như sau
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<font color="red">
Your login attempt was not successful: <br/><br/>
<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>.
</font>
</c:if>
nhưng đoạn code này chỉ in 1 lỗi chung chung là Bad credentials
.