我有以下问题:我自定义Spring引导提供的AuthenticationProvider类来调用休息服务,以便在远程服务器上进行登录。
如果凭据正确,没问题。
当凭据不正确并且服务器响应http状态为403时,会出现问题。 实际上,我无法得到响应,因为它会自动引发API休息的例外:
ResponseEntity <UserResponse> resp = restTemplate.exchange (url, HttpMethod.POST, requestEntity, UserResponse.class);
我尝试创建自定义类,以捕获异常 @ControllerAdvice注释,但无法调用它,因为异常不会出现在控制器中,而是出现在AuthenticationProvider类中。
有没有办法拦截其他API异常的响应?
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static final Logger log = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
@Value("${search.login}")
private String searchLogin;
@Autowired
private HttpServletRequest request;
private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
User user=new User();
ObjectWriter ow = new ObjectMapper().writer();
String json="log-> ";
UserResponse response=new UserResponse();
try {
RestTemplate restTemplate = new RestTemplate();
URI url;
url = new URI(searchLogin);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username",URLEncoder.encode(authentication.getName(), "utf-8"));
map.add("password",URLEncoder.encode(authentication.getCredentials().toString(), "utf-8"));
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
List<MediaType> acceptableMediaTypes=new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
requestHeaders.setAccept(acceptableMediaTypes);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(map,requestHeaders);
ResponseEntity<UserResponse> resp = restTemplate.exchange(url, HttpMethod.POST, requestEntity, UserResponse.class);
response = resp.getBody();
提前致谢。
答案 0 :(得分:0)
我担心你必须从Spring Security处理它,因为@ControllerAdvice只拦截直接从你的控制器抛出的异常。我认为this link会为您提供您正在寻找的解决方案。
答案 1 :(得分:-1)
你可以尝试在你的Rest中添加@ExceptionHandler。就像例如
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
//balabala
}