optimize 1192: Set a friendly prompt respectively when the login user does not exist and the password is wrong (#1194)

* optimize: set a friendly prompt respectively when the login user does not exist and the password is wrong.

* test: add test for JWTAuthenticationFilter.getMessage

* style: Add a blank line for JWTAuthenticationFilterTest.class

---------

Co-authored-by: lucca <luccasuen.dev@gmail.com>
pull/1202/head
lucca suen 2 years ago committed by GitHub
parent cdeae3010f
commit e3cb45f5ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -26,6 +26,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@ -86,11 +87,6 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
return source;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
@ -111,6 +107,20 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
web.ignoring().antMatchers(ignores);
}
/**
* Injection DaoAuthenticationProvider
* Modify hideUserNotFoundExceptions initial value to false
* Solve the problem of UserNotFoundException don't throw
*/
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(bCryptPasswordEncoder());
return provider;
}
private void disableAuthenticationIfNeeded(HttpSecurity http) throws Exception {
if (Boolean.FALSE.equals(enableAuthentication)) {
http.authorizeRequests().antMatchers("/hippo4j/v1/cs/**").permitAll();

@ -31,6 +31,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
@ -72,8 +73,12 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
rememberMe.set(loginUser.getRememberMe());
authenticate = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList()));
} catch (UsernameNotFoundException e) {
log.warn("User {} not found", e.getMessage());
throw e;
} catch (BadCredentialsException e) {
log.warn("Bad credentials exception: {}", e.getMessage());
throw e;
} catch (Exception e) {
log.error("Attempt authentication error", e);
}
@ -108,6 +113,19 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSONUtil.toJSONString(new ReturnT(ReturnT.JWT_FAIL_CODE, "Server Error")));
response.getWriter().write(JSONUtil.toJSONString(new ReturnT(ReturnT.JWT_FAIL_CODE, getMessage(failed))));
}
/**
* Return different echo information to the front end according to different exception types
*/
private String getMessage(AuthenticationException failed) {
String message = "Server Error";
if (failed instanceof UsernameNotFoundException) {
message = "用户不存在";
} else if (failed instanceof BadCredentialsException) {
message = "密码错误";
}
return message;
}
}

@ -59,7 +59,6 @@ public class UserDetailsServiceImpl implements UserDetailsService {
}
UserInfo userInfo = userMapper.selectOne(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserName, userName));
if (Objects.isNull(userInfo)) {
log.warn("User {} not found", userName);
throw new UsernameNotFoundException(userName);
}
JwtUser jwtUser = new JwtUser();

@ -43,13 +43,13 @@ public class ReturnT<T> implements Serializable {
private int code;
private String msg;
private String message;
private T content;
public ReturnT(int code, String msg) {
public ReturnT(int code, String message) {
this.code = code;
this.msg = msg;
this.message = message;
}
public ReturnT(T content) {

@ -0,0 +1,19 @@
package cn.hippo4j.auth.filter;
import cn.hippo4j.common.toolkit.ReflectUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
class JWTAuthenticationFilterTest {
@Test
void getMessageTest() {
JWTAuthenticationFilter filter = new JWTAuthenticationFilter(null);
Assertions.assertEquals("用户不存在", ReflectUtil.invoke(filter,
"getMessage", new UsernameNotFoundException("")));
Assertions.assertEquals("密码错误", ReflectUtil.invoke(filter,
"getMessage", new BadCredentialsException("")));
}
}

@ -39,7 +39,7 @@ public final class ReturnTTest {
@Test
public void assertGetMessage() {
Assert.isNull(returnT.getMsg());
Assert.isNull(returnT.getMessage());
}
@Test

Loading…
Cancel
Save