java - java - Spring Boot安全性oauth自定义异常消息

目前我只能得到消息"Bad credentials",我没有找到如何根据某些用户属性或特殊情况自定义消息的解决方案。

我目前有这样的自定义身份验证提供程序:


@Component


public class CustomAuthenticationProvider implements AuthenticationProvider {



 @Autowired


 private CustomUserDetailsService userDetailsService;



 @Autowired


 PasswordEncoder passwordEncoder;



 @Override


 public Authentication authenticate(Authentication authentication)


 throws org.springframework.security.core.AuthenticationException {



 String name = authentication.getName();


 String password = authentication.getCredentials().toString();



 UserDetails userDetails = userDetailsService.loadUserByUsername(name);



 if(passwordEncoder.matches(password, userDetails.getPassword())) {


 return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),


 userDetails.getAuthorities());


 }



 return null;


 }



 @Override


 public boolean supports(Class<?> authentication) {


 return authentication.equals(UsernamePasswordAuthenticationToken.class);


 }



}



我也有这样的自定义用户详细信息服务:


@Service


public class CustomUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService{



 @Autowired


 UserService userService; //my custom user service



 @Override


 public UserDetails loadUserByUsername(String username) {


 try {


 User user = userService.getUserByUsername(username);



 if(user == null) {


 throw new UsernameNotFoundException("Username doesn't exist");


 } else if(user.isDeactivated()) {


 throw new UsernameNotFoundException("User deactivated");


 }



 List<Authority> listOfAuthorities = userService.getAllAuthoritiesFromUser(user.getUserId());


 List<GrantedAuthority> grantedAuthorities = new ArrayList<>();



 for(Authority authority : listOfAuthorities) {


 grantedAuthorities.add(new SimpleGrantedAuthority(authority.getName()));


 }



 org.springframework.security.core.userdetails.User userNew =


 new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);


 return userNew;



 }


 catch(Exception ex) {


 throw new UsernameNotFoundException("Username or password not correct");


 }



 }


}



从哪里可以处理消息throw new UsernameNotFoundException

时间:

这是你处理每个单独异常的逻辑。





@ControllerAdvice


public class ExceptionTranslator {



 @ExceptionHandler(UsernameNotFoundException.class)


 public ResponseEntity<String> handleUsernameNotFoundException(UsernameNotFoundException ex) {


 return ResponseEntity


 .status(HttpStatus.UNAUTHORIZED)


 .body("your message goes here"); // could be a DTO


 }


}



...