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


 }


}



...