简体   繁体   English

Spring-处理访问被拒绝的异常

[英]Spring - handling access denied exception

In my app I want to handle AccessDeniedException and return Json content in response for that. 在我的应用中,我想处理AccessDeniedException并为此返回Json内容。 Can someone explain how to do this? 有人可以解释如何做吗? I can't find answer. 我找不到答案。 I tried to catch Exception using @ExceptionHandler but I always get redirect to log in page. 我试图使用@ExceptionHandler捕获Exception,但是我总是重定向到登录页面。 I'm writing just api so I don't need whole mvc. 我只是在写api,所以我不需要整个mvc。

Any ideas? 有任何想法吗?

You can introduce a HandlerExceptionResolver which is capable of converting a AccessDeniedException into a JSON response: 您可以引入HandlerExceptionResolver ,它能够将AccessDeniedException转换为JSON响应:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component("handlerExceptionResolver")
public class RestExceptionResolver implements HandlerExceptionResolver {
    private final ObjectMapper objectMapper;

    @Autowired
    public RestExceptionResolver(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
        if (exception instanceof AccessDeniedException) {
            try {
                //you can use a pojo instead of a map too
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("status", HttpServletResponse.SC_FORBIDDEN);
                data.put("message", "my custom message");

                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);

                objectMapper.writeValue(response.getOutputStream(), data);

                //exception handled
                return new ModelAndView();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        //default processing
        return null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM