標註存取控制


除了在 web.xml 中設定 <security-constraint> 外,亦可直接在程式碼中使用 @ServletSecurity 設定對應的資訊。例如,如果 web.xml 中設定基本驗證:

<login-config>
    <auth-method>BASIC</auth-method>
</login-config>

/admin 僅允許 admin 角色存取的話,可以如下在 Servlet 中定義:

package cc.openhome;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/admin")
@ServletSecurity(
    @HttpConstraint(rolesAllowed = {"admin"})
)
public class Admin extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                         throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("只有 admin 才看得到");
    }
}

進一步地,如果 /manager 只允許 adminmanager 使用 GETPOST,而其他方法只允許 admin 角色,可以如下:

package cc.openhome;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/manager")
@ServletSecurity(
    value=@HttpConstraint(rolesAllowed = {"admin"}), 
    httpMethodConstraints = {
        @HttpMethodConstraint(
            value = "GET", rolesAllowed = {"admin", "manager"}
        ),
        @HttpMethodConstraint(
            value = "POST", rolesAllowed = {"admin", "manager"}
        )
    }
)
public class Manager extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                       throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("只有 admin 與 manager 才看得到");
    }
}

如果要設定 <transport-guarantee> 的對應資訊,則可以如下:

...
@WebServlet(urlPatterns={"/security"})
@ServletSecurity(
    httpMethodConstraints = {
        @HttpMethodConstraint(
            value = "GET", rolesAllowed = {"admin", "manager"},
            transportGuarantee = TransportGuarantee.CONFIDENTIAL
        ),
        @HttpMethodConstraint(
            value = "POST", rolesAllowed = {"admin", "manager"},
            transportGuarantee = TransportGuarantee.CONFIDENTIAL
        )
    }
)
public class SecurityServlet extends HttpServlet {
...