Created
July 2, 2012 06:45
-
-
Save inancsevinc/3031495 to your computer and use it in GitHub Desktop.
JAX-RS resource filter class used to authorize requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.ws.rs.WebApplicationException; | |
import javax.ws.rs.core.Response; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Component; | |
import com.sun.jersey.spi.container.ContainerRequest; | |
import com.sun.jersey.spi.container.ContainerRequestFilter; | |
import com.sun.jersey.spi.container.ContainerResponse; | |
import com.sun.jersey.spi.container.ContainerResponseFilter; | |
import com.sun.jersey.spi.container.ResourceFilter; | |
/** | |
* JAX-RS resource filter class used to authorize requests. | |
* Checks the name of UserPrincipal against adminUsers list, | |
* returns 403 if not found. | |
* | |
*/ | |
@Component | |
public class AdminResourceFilter implements ResourceFilter{ | |
@Autowired | |
private PortalSettingsService settings; | |
@Override | |
public ContainerRequestFilter getRequestFilter() { | |
return new ContainerRequestFilter() { | |
@Override | |
public ContainerRequest filter(ContainerRequest request) { | |
String name = request.getUserPrincipal().getName(); | |
String[] admins = settings.getAdminUsers(); | |
for (String adminName : admins) { | |
if( adminName.equals(name) ) | |
return request; | |
} | |
// return HTTP 403 if name is not found in admin users | |
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN) | |
.entity("You are not authorized! This service can only used by admin users.").build()); | |
} | |
}; | |
} | |
@Override | |
public ContainerResponseFilter getResponseFilter() { | |
return new ContainerResponseFilter() { | |
@Override | |
public ContainerResponse filter(ContainerRequest request, | |
ContainerResponse response) { | |
return response; | |
} | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Path("/portal/admin") | |
@ResourceFilters(AdminResourceFilter.class) | |
@Component | |
public class PortalAdminResource { | |
//.... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanx isso me ajudou muito, com @namebinding no jerdey 1.19 não funciona