網頁

2018/4/23

Spring Security 自訂無存取權限時返回的錯誤內容 403 Access is denied

Spring Security在使用者存取無使用權限的資源時,預設會返回HTTP Status 403 - Access is denied頁面,如果想要自訂返回的內容,則設定如下。

建立一個實作AccessDeniedHandler的類別如下,本範例在無權限存取時改成返回json字串。

package idv.matt.security

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response,
    AccessDeniedException accessDeniedException) throws IOException, ServletException {
    
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode objNode1 = mapper.createObjectNode();
    objNode1.put("error", "403");
    
    
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write(objNode1.toString());
    response.getWriter().flush();
    response.getWriter().close();
  
  }

}

在Spring Security的配置檔applicationContext.xml<http>的屬性access-denied-handler設為剛剛自訂的CustomAccessDeniedHandler

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/security 
                           http://www.springframework.org/schema/security/spring-security.xsd">  
                           
  <bean id="customAccessDeniedHandler" class="idv.matt.security.CustomAccessDeniedHandler"/>  
  
  <security:http>
    <!-- some other configs ... -->
    <security:access-denied-handler ref="customAccessDeniedHandler"/>
  </security:http>
  
<beans>

透過以上設定,在使用者無存取權限的情況下,會返回json字串如下。

{"error":"403"}

參考:

沒有留言:

張貼留言