下面列出了怎么用javax.servlet.annotation.ServletSecurity的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create from an annotation.
* @param annotation Annotation to use as the basis for the new instance
* @throws IllegalArgumentException if a method name is specified more than
*/
public ServletSecurityElement(ServletSecurity annotation) {
this(new HttpConstraintElement(annotation.value().value(),
annotation.value().transportGuarantee(),
annotation.value().rolesAllowed()));
List<HttpMethodConstraintElement> l = new ArrayList<>();
HttpMethodConstraint[] constraints = annotation.httpMethodConstraints();
if (constraints != null) {
for (int i = 0; i < constraints.length; i++) {
HttpMethodConstraintElement e =
new HttpMethodConstraintElement(constraints[i].value(),
new HttpConstraintElement(
constraints[i].emptyRoleSemantic(),
constraints[i].transportGuarantee(),
constraints[i].rolesAllowed()));
l.add(e);
}
}
addHttpMethodConstraints(l);
}
public List<SecurityConstraint> getConstraintsFromSecurityAnnotations(ServletContext servletContext, AuthorizationService authorizationService) throws ServletException {
List<Entry<List<String>, ServletSecurity>> elements = getOptionalAttribute(servletContext, SECURITY_ANNOTATIONS);
if (elements == null) {
return null;
}
List<SecurityConstraint> constraints = new ArrayList<>();
for (Entry<List<String>, ServletSecurity> elementEntry : elements) {
constraints.addAll(ElementsToConstraintsTransformer.createConstraints(
new HashSet<>(elementEntry.getKey()),
elementEntry.getValue()));
}
return constraints;
}
private void processServletSecurityAnnotation(Class<?> clazz) {
// Calling this twice isn't harmful so no syncs
servletSecurityAnnotationScanRequired = false;
Context ctxt = (Context) getParent();
if (ctxt.getIgnoreAnnotations()) {
return;
}
ServletSecurity secAnnotation =
clazz.getAnnotation(ServletSecurity.class);
if (secAnnotation != null) {
ctxt.addServletSecurity(
new ApplicationServletRegistration(this, ctxt),
new ServletSecurityElement(secAnnotation));
}
}
/**
* Create from an annotation.
* @param annotation
* @throws IllegalArgumentException if a method name is specified more than
*/
public ServletSecurityElement(ServletSecurity annotation) {
this(new HttpConstraintElement(annotation.value().value(),
annotation.value().transportGuarantee(),
annotation.value().rolesAllowed()));
List<HttpMethodConstraintElement> l =
new ArrayList<HttpMethodConstraintElement>();
HttpMethodConstraint[] constraints = annotation.httpMethodConstraints();
if (constraints != null) {
for (int i = 0; i < constraints.length; i++) {
HttpMethodConstraintElement e =
new HttpMethodConstraintElement(constraints[i].value(),
new HttpConstraintElement(
constraints[i].emptyRoleSemantic(),
constraints[i].transportGuarantee(),
constraints[i].rolesAllowed()));
l.add(e);
}
}
addHttpMethodConstraints(l);
}
/**
* Constructs an instance from a {@link ServletSecurity} annotation value.
*
* @param annotation the annotation value
*
* @throws IllegalArgumentException if duplicate method names are
* detected
*/
public ServletSecurityElement(ServletSecurity annotation) {
super(annotation.value().value(),
annotation.value().transportGuarantee(),
annotation.value().rolesAllowed());
this.methodConstraints = new HashSet<HttpMethodConstraintElement>();
for (HttpMethodConstraint constraint :
annotation.httpMethodConstraints()) {
this.methodConstraints.add(
new HttpMethodConstraintElement(
constraint.value(),
new HttpConstraintElement(constraint.emptyRoleSemantic(),
constraint.transportGuarantee(),
constraint.rolesAllowed())));
}
methodNames = checkMethodNames(this.methodConstraints);
}
private void processServletSecurityAnnotation(Class<?> clazz) {
// Calling this twice isn't harmful so no syncs
servletSecurityAnnotationScanRequired = false;
Context ctxt = (Context) getParent();
if (ctxt.getIgnoreAnnotations()) {
return;
}
ServletSecurity secAnnotation =
clazz.getAnnotation(ServletSecurity.class);
if (secAnnotation != null) {
ctxt.addServletSecurity(
new ApplicationServletRegistration(this, ctxt),
new ServletSecurityElement(secAnnotation));
}
}
/**
* Create from an annotation.
* @param annotation
* @throws IllegalArgumentException if a method name is specified more than
*/
public ServletSecurityElement(ServletSecurity annotation) {
this(new HttpConstraintElement(annotation.value().value(),
annotation.value().transportGuarantee(),
annotation.value().rolesAllowed()));
List<HttpMethodConstraintElement> l =
new ArrayList<HttpMethodConstraintElement>();
HttpMethodConstraint[] constraints = annotation.httpMethodConstraints();
if (constraints != null) {
for (int i = 0; i < constraints.length; i++) {
HttpMethodConstraintElement e =
new HttpMethodConstraintElement(constraints[i].value(),
new HttpConstraintElement(
constraints[i].emptyRoleSemantic(),
constraints[i].transportGuarantee(),
constraints[i].rolesAllowed()));
l.add(e);
}
}
addHttpMethodConstraints(l);
}
/**
* Process the annotations for the servlets.
*
* @param context The context which will have its annotations processed
*/
protected static void loadApplicationServletAnnotations(Context context) {
Container[] children = context.findChildren();
for (Container child : children) {
if (child instanceof Wrapper) {
Wrapper wrapper = (Wrapper) child;
if (wrapper.getServletClass() == null) {
continue;
}
Class<?> clazz = Introspection.loadClass(context, wrapper.getServletClass());
if (clazz == null) {
continue;
}
loadClassAnnotation(context, clazz);
loadFieldsAnnotation(context, clazz);
loadMethodsAnnotation(context, clazz);
/* Process RunAs annotation which can be only on servlets.
* Ref JSR 250, equivalent to the run-as element in
* the deployment descriptor
*/
RunAs runAs = clazz.getAnnotation(RunAs.class);
if (runAs != null) {
wrapper.setRunAs(runAs.value());
}
// Process ServletSecurity annotation
ServletSecurity servletSecurity = clazz.getAnnotation(ServletSecurity.class);
if (servletSecurity != null) {
context.addServletSecurity(
new ApplicationServletRegistration(wrapper, context),
new ServletSecurityElement(servletSecurity));
}
}
}
}
private static SecurityConstraint createConstraint(
HttpConstraintElement element, String urlPattern, boolean alwaysCreate) {
SecurityConstraint constraint = new SecurityConstraint();
SecurityCollection collection = new SecurityCollection();
boolean create = alwaysCreate;
if (element.getTransportGuarantee() !=
ServletSecurity.TransportGuarantee.NONE) {
constraint.setUserConstraint(element.getTransportGuarantee().name());
create = true;
}
if (element.getRolesAllowed().length > 0) {
String[] roles = element.getRolesAllowed();
for (String role : roles) {
constraint.addAuthRole(role);
}
create = true;
}
if (element.getEmptyRoleSemantic() != EmptyRoleSemantic.PERMIT) {
constraint.setAuthConstraint(true);
create = true;
}
if (create) {
collection.addPattern(urlPattern);
constraint.addCollection(collection);
return constraint;
}
return null;
}
@Override
public Void run() {
final ServletSecurity security = servletInfo.getServletClass().getAnnotation(ServletSecurity.class);
if (security != null) {
ServletSecurityInfo servletSecurityInfo = new ServletSecurityInfo()
.setEmptyRoleSemantic(security.value().value() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
.setTransportGuaranteeType(security.value().transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
.addRolesAllowed(security.value().rolesAllowed());
for (HttpMethodConstraint constraint : security.httpMethodConstraints()) {
servletSecurityInfo.addHttpMethodSecurityInfo(new HttpMethodSecurityInfo()
.setMethod(constraint.value()))
.setEmptyRoleSemantic(constraint.emptyRoleSemantic() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
.setTransportGuaranteeType(constraint.transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
.addRolesAllowed(constraint.rolesAllowed());
}
servletInfo.setServletSecurityInfo(servletSecurityInfo);
}
final MultipartConfig multipartConfig = servletInfo.getServletClass().getAnnotation(MultipartConfig.class);
if (multipartConfig != null) {
servletInfo.setMultipartConfig(new MultipartConfigElement(multipartConfig.location(), multipartConfig.maxFileSize(), multipartConfig.maxRequestSize(), multipartConfig.fileSizeThreshold()));
}
final RunAs runAs = servletInfo.getServletClass().getAnnotation(RunAs.class);
if (runAs != null) {
servletInfo.setRunAs(runAs.value());
}
final DeclareRoles declareRoles = servletInfo.getServletClass().getAnnotation(DeclareRoles.class);
if (declareRoles != null) {
deploymentInfo.addSecurityRoles(declareRoles.value());
}
return null;
}
/**
* Is this a web annotation.
*
* @param annotation the annotation.
* @return true if it is, false otherwise.
*/
private boolean isWebAnnotation(Annotation annotation) {
return annotation instanceof WebServlet
|| annotation instanceof WebListener
|| annotation instanceof WebInitParam
|| annotation instanceof WebFilter
|| annotation instanceof ServletSecurity
|| annotation instanceof MultipartConfig;
}
/**
* Constructor.
*
* @param annotation the annotation.
*/
public ServletSecurityElement(ServletSecurity annotation) {
super(annotation.value().value(), annotation.value().transportGuarantee(), annotation.value().rolesAllowed());
this.methodConstraints = new HashSet<>();
for (HttpMethodConstraint constraint : annotation.httpMethodConstraints()) {
this.methodConstraints.add(new HttpMethodConstraintElement(constraint.value(),
new HttpConstraintElement(constraint.emptyRoleSemantic(),
constraint.transportGuarantee(),
constraint.rolesAllowed())));
}
methodNames = collectMethodNames(methodConstraints);
}
/**
* Test constructor.
*/
@Test
public void testConstructor() {
HttpConstraintElement element = new HttpConstraintElement(
ServletSecurity.TransportGuarantee.NONE, "developer");
assertEquals(element.getEmptyRoleSemantic(), ServletSecurity.EmptyRoleSemantic.PERMIT);
assertEquals(element.getTransportGuarantee(), ServletSecurity.TransportGuarantee.NONE);
assertEquals(element.getRolesAllowed()[0], "developer");
}
/**
* Test constructor.
*/
@Test
public void testConstructor() {
HttpConstraintElement httpConstraintElement = new HttpConstraintElement(ServletSecurity.EmptyRoleSemantic.PERMIT);
ServletSecurityElement element = new ServletSecurityElement(httpConstraintElement);
assertEquals(element.getEmptyRoleSemantic(), ServletSecurity.EmptyRoleSemantic.PERMIT);
assertNotNull(element.getHttpMethodConstraints());
}
/**
* Test constructor.
*/
@Test
public void testConstructor2() {
HttpConstraintElement httpConstraintElement = new HttpConstraintElement(ServletSecurity.EmptyRoleSemantic.PERMIT);
ArrayList<HttpMethodConstraintElement> methodConstraints = new ArrayList<>();
methodConstraints.add(new HttpMethodConstraintElement("HEAD"));
ServletSecurityElement element = new ServletSecurityElement(httpConstraintElement, methodConstraints);
assertEquals(element.getEmptyRoleSemantic(), ServletSecurity.EmptyRoleSemantic.PERMIT);
assertNotNull(element.getHttpMethodConstraints());
assertEquals(element.getHttpMethodConstraints().iterator().next().getMethodName(), "HEAD");
}
/**
* Test constructor.
*/
@Test
public void testConstructor3() {
HttpConstraintElement httpConstraintElement = new HttpConstraintElement(ServletSecurity.EmptyRoleSemantic.PERMIT);
ArrayList<HttpMethodConstraintElement> methodConstraints = new ArrayList<>();
methodConstraints.add(new HttpMethodConstraintElement("HEAD"));
methodConstraints.add(new HttpMethodConstraintElement("HEAD"));
assertThrows(IllegalArgumentException.class, () -> new ServletSecurityElement(httpConstraintElement, methodConstraints));
}
private static SecurityConstraint createConstraint(
HttpConstraintElement element, String urlPattern, boolean alwaysCreate) {
SecurityConstraint constraint = new SecurityConstraint();
SecurityCollection collection = new SecurityCollection();
boolean create = alwaysCreate;
if (element.getTransportGuarantee() !=
ServletSecurity.TransportGuarantee.NONE) {
constraint.setUserConstraint(element.getTransportGuarantee().name());
create = true;
}
if (element.getRolesAllowed().length > 0) {
String[] roles = element.getRolesAllowed();
for (String role : roles) {
constraint.addAuthRole(role);
}
create = true;
}
if (element.getEmptyRoleSemantic() != EmptyRoleSemantic.PERMIT) {
constraint.setAuthConstraint(true);
create = true;
}
if (create) {
collection.addPattern(urlPattern);
constraint.addCollection(collection);
return constraint;
}
return null;
}
@Override
public Void run() {
final ServletSecurity security = servletInfo.getServletClass().getAnnotation(ServletSecurity.class);
if (security != null) {
ServletSecurityInfo servletSecurityInfo = new ServletSecurityInfo()
.setEmptyRoleSemantic(security.value().value() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
.setTransportGuaranteeType(security.value().transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
.addRolesAllowed(security.value().rolesAllowed());
for (HttpMethodConstraint constraint : security.httpMethodConstraints()) {
servletSecurityInfo.addHttpMethodSecurityInfo(new HttpMethodSecurityInfo()
.setMethod(constraint.value()))
.setEmptyRoleSemantic(constraint.emptyRoleSemantic() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
.setTransportGuaranteeType(constraint.transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
.addRolesAllowed(constraint.rolesAllowed());
}
servletInfo.setServletSecurityInfo(servletSecurityInfo);
}
final MultipartConfig multipartConfig = servletInfo.getServletClass().getAnnotation(MultipartConfig.class);
if (multipartConfig != null) {
servletInfo.setMultipartConfig(new MultipartConfigElement(multipartConfig.location(), multipartConfig.maxFileSize(), multipartConfig.maxRequestSize(), multipartConfig.fileSizeThreshold()));
}
final RunAs runAs = servletInfo.getServletClass().getAnnotation(RunAs.class);
if (runAs != null) {
servletInfo.setRunAs(runAs.value());
}
final DeclareRoles declareRoles = servletInfo.getServletClass().getAnnotation(DeclareRoles.class);
if (declareRoles != null) {
deploymentInfo.addSecurityRoles(declareRoles.value());
}
return null;
}
private static SecurityConstraint createConstraint(
HttpConstraintElement element, String urlPattern, boolean alwaysCreate) {
SecurityConstraint constraint = new SecurityConstraint();
SecurityCollection collection = new SecurityCollection();
boolean create = alwaysCreate;
if (element.getTransportGuarantee() !=
ServletSecurity.TransportGuarantee.NONE) {
constraint.setUserConstraint(element.getTransportGuarantee().name());
create = true;
}
if (element.getRolesAllowed().length > 0) {
String[] roles = element.getRolesAllowed();
for (String role : roles) {
constraint.addAuthRole(role);
}
create = true;
}
if (element.getEmptyRoleSemantic() != EmptyRoleSemantic.PERMIT) {
constraint.setAuthConstraint(true);
create = true;
}
if (create) {
collection.addPattern(urlPattern);
constraint.addCollection(collection);
return constraint;
}
return null;
}
public static ServletSecurity.TransportGuarantee getTransportGuarantee(String propertyName) {
AppConstants appConstants = AppConstants.getInstance();
String constraintType = appConstants.getString(propertyName, null);
if (StringUtils.isNotEmpty(constraintType))
return ServletSecurity.TransportGuarantee.valueOf(constraintType);
String stage = appConstants.getString("dtap.stage", null);
if (StringUtils.isNotEmpty(stage) && stage.equalsIgnoreCase("LOC")) {
return ServletSecurity.TransportGuarantee.NONE;
}
return ServletSecurity.TransportGuarantee.CONFIDENTIAL;
}
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass,
Servlet servlet, Map<String,String> initParams) throws IllegalStateException {
if (servletName == null || servletName.equals("")) {
throw new IllegalArgumentException(sm.getString(
"applicationContext.invalidServletName", servletName));
}
if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
//TODO Spec breaking enhancement to ignore this restriction
throw new IllegalStateException(
sm.getString("applicationContext.addServlet.ise",
getContextPath()));
}
Wrapper wrapper = (Wrapper) context.findChild(servletName);
// Assume a 'complete' ServletRegistration is one that has a class and
// a name
if (wrapper == null) {
wrapper = context.createWrapper();
wrapper.setName(servletName);
context.addChild(wrapper);
} else {
if (wrapper.getName() != null &&
wrapper.getServletClass() != null) {
if (wrapper.isOverridable()) {
wrapper.setOverridable(false);
} else {
return null;
}
}
}
ServletSecurity annotation = null;
if (servlet == null) {
wrapper.setServletClass(servletClass);
Class<?> clazz = Introspection.loadClass(context, servletClass);
if (clazz != null) {
annotation = clazz.getAnnotation(ServletSecurity.class);
}
} else {
wrapper.setServletClass(servlet.getClass().getName());
wrapper.setServlet(servlet);
if (context.wasCreatedDynamicServlet(servlet)) {
annotation = servlet.getClass().getAnnotation(ServletSecurity.class);
}
}
if (initParams != null) {
for (Map.Entry<String, String> initParam: initParams.entrySet()) {
wrapper.addInitParameter(initParam.getKey(), initParam.getValue());
}
}
ServletRegistration.Dynamic registration =
new ApplicationServletRegistration(wrapper, context);
if (annotation != null) {
registration.setServletSecurity(new ServletSecurityElement(annotation));
}
return registration;
}
@SuppressWarnings("unchecked")
private Class<? extends HttpServlet> getTargetServlet(AnnotationInfo<ServletSecurity> annotationInfo) {
return (Class<? extends HttpServlet>) annotationInfo.getTargetType();
}
/**
* Test constructor.
*/
@Test
public void testConstructor4() {
ServletSecurity servletSecurity = new ServletSecurity() {
@Override
public HttpMethodConstraint[] httpMethodConstraints() {
return new HttpMethodConstraint[]{
new HttpMethodConstraint() {
@Override
public ServletSecurity.EmptyRoleSemantic emptyRoleSemantic() {
return ServletSecurity.EmptyRoleSemantic.PERMIT;
}
@Override
public String[] rolesAllowed() {
return new String[]{};
}
@Override
public ServletSecurity.TransportGuarantee transportGuarantee() {
return ServletSecurity.TransportGuarantee.NONE;
}
@Override
public String value() {
return "HEAD";
}
@Override
public Class<? extends Annotation> annotationType() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
};
}
@Override
public HttpConstraint value() {
return new HttpConstraint() {
@Override
public String[] rolesAllowed() {
return new String[]{};
}
@Override
public ServletSecurity.TransportGuarantee transportGuarantee() {
return ServletSecurity.TransportGuarantee.NONE;
}
@Override
public ServletSecurity.EmptyRoleSemantic value() {
return ServletSecurity.EmptyRoleSemantic.PERMIT;
}
@Override
public Class<? extends Annotation> annotationType() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
@Override
public Class<? extends Annotation> annotationType() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
ServletSecurityElement servletSecurityElement = new ServletSecurityElement(servletSecurity);
assertNotNull(servletSecurityElement);
}
public void registerServlet(String servletName, Servlet servletClass, String urlMapping, String[] roles, int loadOnStartup, Map<String, String> initParameters) {
log.info("instantiating IbisInitializer servlet name ["+servletName+"] servletClass ["+servletClass+"] loadOnStartup ["+loadOnStartup+"]");
getServletContext().log("instantiating IbisInitializer servlet ["+servletName+"]");
AppConstants appConstants = AppConstants.getInstance();
String propertyPrefix = "servlet."+servletName+".";
if(!appConstants.getBoolean(propertyPrefix+"enabled", true))
return;
ServletRegistration.Dynamic serv = getServletContext().addServlet(servletName, servletClass);
ServletSecurity.TransportGuarantee transportGuarantee = getTransportGuarantee(propertyPrefix+"transportGuarantee");
String stage = appConstants.getString("dtap.stage", null);
String[] rolesCopy = new String[0];
if(roles != null && !stage.equalsIgnoreCase("LOC"))
rolesCopy = roles;
String roleNames = appConstants.getString(propertyPrefix+"securityroles", null);
if(StringUtils.isNotEmpty(roleNames))
rolesCopy = roleNames.split(",");
declareRoles(rolesCopy);
HttpConstraintElement httpConstraintElement = new HttpConstraintElement(transportGuarantee, rolesCopy);
ServletSecurityElement constraint = new ServletSecurityElement(httpConstraintElement);
String urlMappingCopy = appConstants.getString(propertyPrefix+"urlMapping", urlMapping);
if(!urlMappingCopy.startsWith("/") && !urlMappingCopy.startsWith("*")) {
urlMappingCopy = "/"+urlMappingCopy;
}
serv.addMapping(urlMappingCopy);
int loadOnStartupCopy = appConstants.getInt(propertyPrefix+"loadOnStartup", loadOnStartup);
serv.setLoadOnStartup(loadOnStartupCopy);
serv.setServletSecurity(constraint);
if(initParameters != null && !initParameters.isEmpty()) {
//Manually loop through the map as serv.setInitParameters will fail all parameters even if only 1 fails...
for (String key : initParameters.keySet()) {
String value = initParameters.get(key);
if(!serv.setInitParameter(key, value)) {
log("unable to set init-parameter ["+key+"] with value ["+value+"] for servlet ["+servletName+"]", Level.ERROR);
}
}
}
if(log.isDebugEnabled()) log.debug("registered servlet ["+servletName+"] class ["+servletClass+"] url ["+urlMapping+"] loadOnStartup ["+loadOnStartup+"]");
}