<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Jersey REST API 安全示例 > 原文: [https://howtodoinjava.com/jersey/jersey-rest-security/](https://howtodoinjava.com/jersey/jersey-rest-security/) 在此 **Jersey rest 安全**示例中,我們將學習**通過基本認證**保護 Jersey REST API 的安全。 這將強制每個用戶提供用戶名/密碼以認證到門戶。 另外,用戶還必須具有一定級別的角色。 我從為 [RESTEasy API 安全性](https://howtodoinjava.com/resteasy/jax-rs-2-0-resteasy-3-0-2-final-security-tutorial/)創建的另一個示例擴展了此示例,并使用[`ContainerRequestFilter`](https://jax-rs-spec.java.net/nonav/2.0-SNAPSHOT/apidocs/javax/ws/rs/container/ContainerRequestFilter.html)實現在用戶登陸實際的 REST API 之前驗證其訪問權限。 ```java Table of Contents 1\. Create request authentication filter 2\. Register AuthenticationFilter with ResourceConfig 3\. Secure REST APIs 4\. Test Jersey AuthenticationFilter ``` ## 1\. 創建請求認證過濾器 我們知道 *JAX-RS 2.0* 具有用于處理請求前和請求的過濾器,因此我們將使用`ContainerRequestFilter`接口。 在此過濾器中,我們將獲取請求嘗試訪問的方法的詳細信息。 我們將找出該方法上所有與安全性相關的配置,并在此過濾器中驗證所有內容,例如,注解,例如`@PermitAll`,`@DenyAll`或`@RolesAllowed`。 根據方法上的注解,我們將決定是通過還是阻止請求。 ```java package com.howtodoinjava.jersey.provider; 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.container.ResourceInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.internal.util.Base64; /** * This filter verify the access permissions for a user * based on username and passowrd provided in request * */ @Provider public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter { @Context private ResourceInfo resourceInfo; private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String AUTHENTICATION_SCHEME = "Basic"; @Override public void filter(ContainerRequestContext requestContext) { Method method = resourceInfo.getResourceMethod(); //Access allowed for all if( ! method.isAnnotationPresent(PermitAll.class)) { //Access denied for all if(method.isAnnotationPresent(DenyAll.class)) { requestContext.abortWith(Response.status(Response.Status.FORBIDDEN) .entity("Access blocked for all users !!").build();); 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(Response.status(Response.Status.UNAUTHORIZED) .entity("You cannot access this resource").build()); return; } //Get encoded username and password final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", ""); //Decode username and password String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes()));; //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(Response.status(Response.Status.UNAUTHORIZED) .entity("You cannot access this resource").build();); 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); if(username.equals("howtodoinjava") && password.equals("password")) { String userRole = "ADMIN"; //Step 2\. Verify user role if(rolesSet.contains(userRole)) { isAllowed = true; } } return isAllowed; } } ``` ## 2\. 向`ResourceConfig`注冊`AuthenticationFilter` 現在,您需要在`ResourceConfig`實例上方注冊過濾器。 因此,創建一個如下所示的實例: ```java package com.howtodoinjava.jersey; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.server.ResourceConfig; import com.howtodoinjava.jersey.provider.AuthenticationFilter; import com.howtodoinjava.jersey.provider.GsonMessageBodyHandler; public class CustomApplication extends ResourceConfig { public CustomApplication() { packages("com.howtodoinjava.jersey"); register(LoggingFilter.class); register(GsonMessageBodyHandler.class); //Register Auth Filter here register(AuthenticationFilter.class); } } ``` 并將此資源配置添加到`web.xml`文件中。 ```java <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.howtodoinjava.jersey.CustomApplication</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app> ``` ## 3\. 安全的 REST API 現在是時候保護 REST API 了。 如下使用標準的 JAX-RS 注解。 ```java @Path("/employees") public class JerseyService { @RolesAllowed("ADMIN") @GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Employees getAllEmployees() { Employees list = new Employees(); list.setEmployeeList(new ArrayList<Employee>()); list.getEmployeeList().add(new Employee(1, "Lokesh Gupta")); list.getEmployeeList().add(new Employee(2, "Alex Kolenchiskey")); list.getEmployeeList().add(new Employee(3, "David Kameron")); return list; } } ``` ## 4\. 測試 Jersey `AuthenticationFilter` 讓我們測試認證設置是否有效。 #### 點擊 URL:`http://localhost:8080/JerseyDemos/rest/employees` ![Jersey authentication failure request](https://img.kancloud.cn/2f/72/2f724e6da584951395352da9cf644d4e_954x447.png) Jersey 認證失敗的請求 #### 在基本認證參數中傳遞用戶名和密碼:`howtodoinjava/password` ![Jersey authenticated success request](https://img.kancloud.cn/20/cf/20cf83ee7d8eb055ddf8b620bac30634_700x357.png) Jersey 認證成功的請求 單擊下面的鏈接下載 **jersey rest api 認證示例**應用的源代碼。 [JerseyDemos](//howtodoinjava.com/wp-content/uploads/2015/08/JerseyDemos1.zip) 學習愉快!
                  <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>

                              哎呀哎呀视频在线观看