Spring Security 403 自定义返回消息

刺骨的言语ヽ痛彻心扉 2022-04-10 04:22 296阅读 0赞

Spring Security 403 自定义返回消息

  • 自定义处理类 CustomAccessDeniedHandler

    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.security.access.AccessDeniedException;
    import org.springframework.security.web.access.AccessDeniedHandler;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;

    public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    1. @Override
    2. public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
    3. response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    4. response.setStatus(HttpStatus.FORBIDDEN.value());
    5. response.getWriter().write(new ObjectMapper().writeValueAsString(new CustomResponse("Session Invalid", null)));
    6. }
    7. static class CustomResponse {
    8. private String message;
    9. private Object data;
    10. CustomResponse(String message, Object data) {
    11. this.message = message;
    12. this.data = data;
    13. }
    14. public String getMessage() {
    15. return message;
    16. }
    17. public void setMessage(String message) {
    18. this.message = message;
    19. }
    20. public Object getData() {
    21. return data;
    22. }
    23. public void setData(Object data) {
    24. this.data = data;
    25. }
    26. }

    }

  • 在Spring Security 配置中添加配置

    import org.springframework.context.annotation.Bean;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.web.access.AccessDeniedHandler;

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

    1. @Override
    2. protected void configure(HttpSecurity http) throws Exception {
    3. http.authorizeRequests()
    4. .antMatchers("/",
    5. "/index.html",
    6. "/**/favicon.ico",
    7. "/login",
    8. "/logout",
    9. "/index",
    10. "/error")
    11. .permitAll();
    12. http.authorizeRequests()
    13. .anyRequest()
    14. .authenticated()
    15. .and()
    16. .exceptionHandling().accessDeniedHandler(accessDeniedHandler());
    17. }
    18. @Bean
    19. public AccessDeniedHandler accessDeniedHandler() {
    20. return new CustomAccessDeniedHandler();
    21. }

    }

  • 返回值

    {“message”:”Session Invalid”,”data”:null}

发表评论

表情:
评论列表 (有 0 条评论,296人围观)

还没有评论,来说两句吧...

相关阅读