问题
The Java Servlet 3.0 and 3.1 specifications allow developers to perform many of the common configuration based tasks in Java code rather than via the traditional mechanism of providing a web.xml file.
I have all of this working for my application, but upon looking to tackle application security, I could not find any reference to how or if it is possible to also configuration application security constraints via code.
Basically, I am looking for a programmatic way to do the following:
<security-constraint>
<web-resource-collection>
<web-resource-name>my-secure-webapp</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>SSORole</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>CLIENT-CERT</auth-method>
</login-config>
<security-role>
<role-name>SSORole</role-name>
</security-role>
Is anyone aware of a means to do this?
thanks
回答1:
You will find details in the section provided by Mark, but for short hand, you could put in your servlet something like:
@ServletSecurity((httpMethodConstraints = {
@HttpMethodConstraint(value = "GET", rolesAllowed = "SSORole"),
@HttpMethodConstraint(value = "POST", rolesAllowed = "SSORole",
transportGuarantee = TransportGuarantee.CONFIDENTIAL)
})
However there are still some drawbacks of using annotation in web module security:
- your
url-pattern
will be direct match to your servlet mappings - cannot define/*
for whole application like viaweb.xml
- unfortunately still there is no annotation for
login-config
So I'd suggest to stick with web.xml
for security definitions for a bit longer.
回答2:
You need to read section 13.4 of the Servlet 3 specification.
来源:https://stackoverflow.com/questions/25552491/servlet-3-1-security-constraints-without-web-xml