public class RoleBasedSecurityFilter implements ContainerRequestFilter {
protected String[] rolesAllowed;
protected boolean denyAll;
protected boolean permitAll;
public RoleBasedSecurityFilter(String[] rolesAllowed, boolean denyAll, boolean permitAll) {
this.rolesAllowed = rolesAllowed;
this.denyAll = denyAll;
this.permitAll = permitAll;
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (denyAll) {
requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
return;
}
if (permitAll) return;
if (rolesAllowed != null) {
SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class);
if (context != null) {
for (String role : rolesAllowed) {
if (context.isUserInRole(role)) return;
}
requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
return;
}
}
return;
}
}
public class RoleBasedSecurityFilter implements ContainerRequestFilter {
protected String[] rolesAllowed;
protected boolean denyAll;
protected boolean permitAll;
public RoleBasedSecurityFilter(String[] rolesAllowed, boolean denyAll, boolean permitAll) {
this.rolesAllowed = rolesAllowed;
this.denyAll = denyAll;
this.permitAll = permitAll;
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (denyAll) {
requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
return;
}
if (permitAll) return;
if (rolesAllowed != null) {
SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class);
if (context != null) {
for (String role : rolesAllowed) {
if (context.isUserInRole(role)) return;
}
requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
return;
}
}
return;
}
}
Copy to ClipboardCopied!Toggle word wrapToggle overflow
示例:Response Filter
public class CacheControlFilter implements ContainerResponseFilter {
private int maxAge;
public CacheControlFilter(int maxAge) {
this.maxAge = maxAge;
}
public void filter(ContainerRequestContext req, ContainerResponseContext res)
throws IOException {
if (req.getMethod().equals("GET")) {
CacheControl cc = new CacheControl();
cc.setMaxAge(this.maxAge);
res.getHeaders().add("Cache-Control", cc);
}
}
}
public class CacheControlFilter implements ContainerResponseFilter {
private int maxAge;
public CacheControlFilter(int maxAge) {
this.maxAge = maxAge;
}
public void filter(ContainerRequestContext req, ContainerResponseContext res)
throws IOException {
if (req.getMethod().equals("GET")) {
CacheControl cc = new CacheControl();
cc.setMaxAge(this.maxAge);
res.getHeaders().add("Cache-Control", cc);
}
}
}
Copy to ClipboardCopied!Toggle word wrapToggle overflow