<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # RESTEasy `ContainerRequestFilter` - RESTEasy 安全過濾器示例 > 原文: [https://howtodoinjava.com/resteasy/resteasy-containerrequestfilter-example/](https://howtodoinjava.com/resteasy/resteasy-containerrequestfilter-example/) 了解如何使用 RESTEasy `ContainerRequestFilter`創建安全篩選器,該篩選器能夠對基于 RESTEasy 的 Web 應用執行認證和授權。 ## 1\. RESTEasy `ContainerRequestFilter`和`ContainerReponseFilter` 最近發布了新的 [**RESTEasy 版本 3.0.2.Final**](http://docs.jboss.org/resteasy/docs/3.0.2.Final/userguide/html_single/index.html "resteasy docs"),并使其與 **JAX-RS 2.0** 兼容。 如果您還記得以前的 JAX-RS 版本沒有關于實現過濾器和攔截器的規范。 這就是所有 JAX-RS 實現都有自己獨特風格的原因。 RESTEasy 的`PreProcessorInterceptor`和`PostProcessorInterceptor`現在已棄用。 現在,JAX-RS 在過濾器和攔截器方面有了自己的規范。 您可以閱讀 Bill Burke 的[**帖子中的詳細討論**](http://java.dzone.com/articles/whats-new-jax-rs-20 "new in jax-rs 2.0")。 在 resteasy 中,過濾器在調用`resource`方法之前和之后運行。 這些過濾器實質上是`ContainerRequestFilter`和`ContainerReponseFilter`。 `ContainerRequestFilter`在調用 JAX-RS 資源方法之前運行。 `ContainerResponseFilter`在調用 JAX-RS 資源方法之后運行。 需要注意的是,`ContainerRequestFilter`有兩種風格:匹配前和匹配后。 預先匹配的`ContainerRequestFilter`用`@PreMatching`注解指定,??并且將在 JAX-RS 資源方法與傳入的 HTTP 請求匹配之前執行。 在匹配 Java 資源方法之后,執行匹配后的`ContainerRequestFilters`。 過濾器修改請求或響應頭時,攔截器處理消息正文。 它們可用于實現特定的內容編碼。 它們可用于生成數字簽名,或在編組 Java 對象模型之前或之后發布或預處理 Java 對象模型。 ## 2\. RESTEasy `ContainerRequestFilter`示例 在本文中,我將修改 [**resteasy 認證和授權教程**](//howtodoinjava.com/resteasy/jax-rs-resteasy-basic-authentication-and-authorization-tutorial/ "JAX-RS RESTEasy basic authentication and authorization tutorial"),該教程最初是使用`PreProcessorInterceptor`在 RESTEasy 2.3.1.GA 中編寫的。 我已將其更新為基于 JAX-RS 2.0 規范的 RESTEasy 版本 3.0.2.Final。 #### 2.1 更新 Maven 依賴項 在使用 Maven 時,我已經更新了`pom.xml`文件,如下所示。 如果您使用的是 ant 或 jar 文件,請相應地更新所需的 jar。 ```java <dependencies> <!-- core library --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>3.0.2.Final</version> </dependency> <!-- JAXB support --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxb-provider</artifactId> <version>3.0.2.Final</version> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>jaxrs-api</artifactId> <version>3.0.2.Final</version> </dependency> <dependency> <groupId>net.sf.scannotation</groupId> <artifactId>scannotation</artifactId> <version>1.0.3</version> </dependency> </dependencies> ``` #### 2.2 RESTEasy 安全攔截器 由于 JAX-RS 2.0 具有用于處理前后請求的過濾器,因此我們將使用`ContainerRequestFilter`接口。 記住`PreProcessorInterceptor`現在已棄用。 ```java @Provider public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) { //More code... } } ``` 現在,首先我們必須訪問資源方法以檢查安全性約束及其定義的屬性。 ```java ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker"); Method method = methodInvoker.getMethod(); ``` 現在我們可以訪問資源方法了。 現在,一切將與我們之前所做的相同。 即 * 檢查`PermitAll`注解(如果存在),則無需進一步檢查任何內容 * 檢查`DenyAll`注解(如果存在),然后返回拒絕訪問 * 檢查``RolesAllowed``注解,然后從注解中獲取所需的角色。 從請求中獲取授權信息,并根據應用邏輯進行匹配。 如果授權成功,則授予訪問權限,否則返回拒絕訪問權限。 #### 2.3 RESTEasy `SecurityInterceptor`源代碼 `SecurityInterceptor`的完整代碼如下。 ```java package com.howtodoinjava.demo.rest.security; 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.ext.Provider; import org.jboss.resteasy.core.Headers; import org.jboss.resteasy.core.ResourceMethodInvoker; import org.jboss.resteasy.core.ServerResponse; import org.jboss.resteasy.util.Base64; /** * This interceptor verify the access permissions for a user * based on username and passowrd provided in request * */ @Provider public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter { private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String AUTHENTICATION_SCHEME = "Basic"; private static final ServerResponse ACCESS_DENIED = new ServerResponse("Access denied for this resource", 401, new Headers<Object>());; private static final ServerResponse ACCESS_FORBIDDEN = new ServerResponse("Nobody can access this resource", 403, new Headers<Object>());; private static final ServerResponse SERVER_ERROR = new ServerResponse("INTERNAL SERVER ERROR", 500, new Headers<Object>());; @Override public void filter(ContainerRequestContext requestContext) { 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 request headers final MultivaluedMap<String, String> headers = requestContext.getHeaders(); //Fetch authorization header final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY); //If no authorization information present; block access if(authorization == null || authorization.isEmpty()) { requestContext.abortWith(ACCESS_DENIED); return; } //Get encoded username and password final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", ""); //Decode username and password String usernameAndPassword = null; try { usernameAndPassword = new String(Base64.decode(encodedUserPassword)); } catch (IOException e) { requestContext.abortWith(SERVER_ERROR); return; } //Split username and password tokens final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); //Verifying Username and password System.out.println(username); System.out.println(password); //Verify user access if(method.isAnnotationPresent(RolesAllowed.class)) { RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class); Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value())); //Is user valid? if( ! isUserAllowed(username, password, rolesSet)) { requestContext.abortWith(ACCESS_DENIED); return; } } } } private boolean isUserAllowed(final String username, final String password, final Set<String> rolesSet) { boolean isAllowed = false; //Step 1\. Fetch password from database and match with password in argument //If both match then get the defined role for user from database and continue; else return isAllowed [false] //Access the database and do this part yourself //String userRole = userMgr.getUserRole(username); String userRole = "ADMIN"; //Step 2\. Verify user role if(rolesSet.contains(userRole)) { isAllowed = true; } return isAllowed; } } ``` ## 2.4 RESTEasy 安全過濾器演示 要測試安全代碼,請將 Web 應用部署在任何應用服務器(例如 Tomcat)中。 現在,發送以下請求: * 不帶用戶名和密碼的 HTTP GET `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1` 用戶能夠成功訪問 API。 ![resteasy authorization test get api](https://img.kancloud.cn/29/94/29945236d0cc1b93e13bf59cd34c98d4_945x382.png) * 不帶用戶名和密碼的 HTTP PUT `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1` 用戶無法訪問 API。 ![resteasy authorization test get api](https://img.kancloud.cn/ec/28/ec28901443f17ceb03557f5d69d37e6a_949x376.png) * 添加基本授權憑據 ![Add basic authorization credentials](https://img.kancloud.cn/aa/f1/aaf1e0084104d852f7f07556a783f425_591x297.png) * 帶有用戶名和密碼的 HTTP PUT `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1` 用戶能夠訪問受保護的 API ![resteasy authorization test put api 2](https://img.kancloud.cn/9f/7a/9f7af3333fb0d52d55a0c60f43816007_952x458.png) 以上就是 **resteasy 安全攔截器示例**。 如果您有任何疑問或建議,請給我評論。 [**下載面向 Jboss 的源碼**](https://docs.google.com/file/d/0B7yo2HclmjI4Q09OVld2dnBaOEU/edit?usp=sharing "JAX-RS 2.0 RESTEasy 3.0.2.Final Security Tutorial") 更新:以下是在 tomcat 7 中運行此項目的步驟。 今天,我再次致力于在 tomcat 7 上運行的該項目。要成功運行,我執行了以下步驟: + 在 eclipse 中導入項目 + 在項目根文件夾中運行提示符 `> mvn eclipse:eclipse -Dwtpversion=2.0`([**參考**](//howtodoinjava.com/maven/ "Maven Tutorials")) + **更新**方法上的`@Produces`和`@Consumes`注解 + 啟動 tomcat 服務器并測試應用。 您將獲得理想的結果。 [**下載面向 Tomcat 7 的源碼**](https://drive.google.com/file/d/0B7yo2HclmjI4LTNiX0d6MUNTb2M/edit?usp=sharing "JAX-RS 2.0 RESTEasy 3.0.2.Final security tutorial on tomcat 7") 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看