Note that our projection was based on the linked inward the reference below, nosotros only made or thus modifications thus that it volition run on a newer version of jboss.
Tech Stack
- JavaEE6 / 7
- JBoss EAP 6.2
Things to remember
- Download resteasy-jaxrs-3.0.6.Final-all.zip
- Extract the zipped file as well as within it discovery the folder: resteasy-jboss-modules-3.0.6.Final
- Copy all the folders within it as well as glue into JBOSS_HOME/modules.
- In web.xml, nosotros don't add together whatever resteasy related parameters, instead it should hold off similar this.
- Create a spider web service activator.
- And finally the remainder asking interceptor:
- To examination if the filter volition actually live triggered when in that location is a remainder spider web service request, I've provided an activeness edible bean as well as a jersey customer that sends a asking alongside username as well as password
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>JAX-RS 2.0 Security Demo</display-name> </web-app>
package com.kalidadbiz; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * @author Edward P. Legaspi **/ @ApplicationPath("/api/rest") populace cast JaxRsActivator extends Application { }
package com.kalidadbiz; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.resteasy.core.Headers; import org.jboss.resteasy.core.ResourceMethodInvoker; import org.jboss.resteasy.core.ServerResponse; import org.jboss.resteasy.util.Base64; /** * @author Edward P. Legaspi * * http://java.dzone.com/articles/java-ee-7-and-jax-rs-20 **/ @Provider populace cast RESTSecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter, ExceptionMapper<Exception> { somebody Log log = LogFactory.getLog(RESTSecurityInterceptor.class); somebody static concluding String AUTHORIZATION_PROPERTY = "Authorization"; somebody static concluding String AUTHENTICATION_SCHEME = "Basic"; somebody static concluding ServerResponse ACCESS_DENIED = novel ServerResponse( "Access denied for this resource", 401, novel Headers<Object>());; somebody static concluding ServerResponse ACCESS_FORBIDDEN = novel ServerResponse( "Nobody tin flame access this resource", 403, novel Headers<Object>());; somebody static concluding ServerResponse SERVER_ERROR = novel ServerResponse( "INTERNAL SERVER ERROR", 500, novel Headers<Object>()); @Override populace void filter(ContainerRequestContext requestContext) { log.info("filter"); ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker"); Method method = methodInvoker.getMethod(); // Access allowed for all if (!method.isAnnotationPresent(PermitAll.class)) { // Access denied for all if (method.isAnnotationPresent(DenyAll.class)) { requestContext.abortWith(ACCESS_FORBIDDEN); return; } // Get asking headers concluding MultivaluedMap<String, String> headers = requestContext .getHeaders(); // Fetch potency header concluding List<String> potency = headers .get(AUTHORIZATION_PROPERTY); // If no potency information present; block access if (authorization == nix || authorization.isEmpty()) { requestContext.abortWith(ACCESS_DENIED); return; } // Get encoded username as well as password concluding String encodedUserPassword = authorization.get(0) .replaceFirst(AUTHENTICATION_SCHEME + " ", ""); // Decode username as well as password String usernameAndPassword = null; endeavour { usernameAndPassword = novel String( Base64.decode(encodedUserPassword)); } select handgrip of (IOException e) { requestContext.abortWith(SERVER_ERROR); return; } // Split username as well as password tokens concluding StringTokenizer tokenizer = novel StringTokenizer( usernameAndPassword, ":"); concluding String username = tokenizer.nextToken(); concluding String password = tokenizer.nextToken(); // Verifying Username as well as password log.info(username); log.info(password); // Verify user access if (method.isAnnotationPresent(RolesAllowed.class)) { RolesAllowed rolesAnnotation = method .getAnnotation(RolesAllowed.class); Set<String> rolesSet = novel HashSet<String>( Arrays.asList(rolesAnnotation.value())); // Is user valid? if (!isUserAllowed(username, password, rolesSet)) { requestContext.abortWith(ACCESS_DENIED); return; } } } } somebody boolean isUserAllowed(final String username, concluding String password, concluding Set<String> rolesSet) { boolean isAllowed = false; // Step 1. Fetch password from database as well as stand upwardly for alongside password inward // declaration // If both stand upwardly for as well as thus larn the defined role for user from database as well as // continue; else render isAllowed [false] // Access the database as well as produce this role yourself // String userRole = userMgr.getUserRole(username); String userRole = "ADMIN"; // Step 2. Verify user role if (rolesSet.contains(userRole)) { isAllowed = true; } render isAllowed; } @Override populace Response toResponse(Exception exception) { // TODO Auto-generated method stub render null; } }
package com.kalidadbiz; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; /** * @author Edward P. Legaspi **/ populace cast RestClient { somebody Log log = LogFactory.getLog(RestClient.class); somebody String host; somebody String api; somebody Properties properties = novel Properties(); populace RestClient() { } populace RestClient(String host, String api) { this.host = host; this.api = api; } populace void addParam(String key, String value) { properties.put(key, value); } populace String execute() { endeavour { Client customer = Client.create(); client.addFilter(new HTTPBasicAuthFilter("edward", "edward")); String params = ""; if (properties != null) { for (String cardinal : properties.stringPropertyNames()) { String value = properties.getProperty(key); if (params != null) { params += "&"; } params += cardinal + "=" + value; } } String apiUrl = host + "/" + api; if (params != nix && params.length() > 0) { apiUrl = apiUrl + "?" + params; } WebResource webResource = client.resource(apiUrl); ClientResponse answer = webResource.accept("application/json") .get(ClientResponse.class); if (response.getStatus() != 200) { throw novel RuntimeException("Failed : HTTP mistake code : " + response.getStatus()); } render response.getEntity(String.class); } select handgrip of (Exception e) { log.error(e.getMessage()); render ""; } } populace String getHost() { render host; } populace void setHost(String host) { this.host = host; } populace String getApi() { render api; } populace void setApi(String api) { this.api = api; } }
And lastly, don't forget to encrypt your password :-).
0 komentar:
Please comment if there are any that need to be asked.