<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之旅 廣告
                # Dropwizard – BasicAuth 安全示例 > 原文: [https://howtodoinjava.com/dropwizard/dropwizard-basic-auth-security-example/](https://howtodoinjava.com/dropwizard/dropwizard-basic-auth-security-example/) 使用 dropwizard,我們了解了[創建 REST API](//howtodoinjava.com/dropwizard/tutorial-and-hello-world-example/) ,[編寫客戶端代碼](//howtodoinjava.com/dropwizard/client-configuration-and-examples/)和[添加運行狀況檢查過濾器](//howtodoinjava.com/dropwizard/health-check-configuration-example/)的知識。 在本教程中,我們將學習使用**基本認證**將**基于用戶名/密碼的認證**和基于**基于角色的授權**功能添加到 REST API 中。 ```java Table of Contents Include Dropwizard Auth Module Maven Dependency Add Custom Principal Object Add Custom Authenticator Add Custom Authorizer Configure BasicCredentialAuthFilter Secure REST APIs with @Auth Annotation Test Dropwizard Basic Auth Code ``` ## 包含 Dropwizard Auth 模塊的 Maven 依賴項 認證功能在 dropwizard 應用中作為單獨的模塊添加。 ```java <properties> <dropwizard.version>1.0.0</dropwizard.version> </properties> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-auth</artifactId> <version>${dropwizard.version}</version> </dependency> ``` ## 添加自定義主體對象 在安全性方面,主體對象表示已為其提供憑據的用戶。 它實現了`java.security.Principal`接口。 ```java package com.howtodoinjava.rest.auth; import java.security.Principal; import java.util.Set; public class User implements Principal { private final String name; private final Set<String> roles; public User(String name) { this.name = name; this.roles = null; } public User(String name, Set<String> roles) { this.name = name; this.roles = roles; } public String getName() { return name; } public int getId() { return (int) (Math.random() * 100); } public Set<String> getRoles() { return roles; } } ``` ## 添加自定義認證器 `Authenticator`類負責驗證基本認證標頭中包含的用戶名/密碼憑證。 在企業應用中,您可以從數據庫中獲取用戶密碼,如果密碼匹配,則將用戶角色設置為主體對象。 在 dropwizard 中,您將需要實現`io.dropwizard.auth.Authenticator`接口以放置您的應用邏輯。 ```java package com.howtodoinjava.rest.auth; import io.dropwizard.auth.AuthenticationException; import io.dropwizard.auth.Authenticator; import io.dropwizard.auth.basic.BasicCredentials; import java.util.Map; import java.util.Optional; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; public class AppBasicAuthenticator implements Authenticator<BasicCredentials, User> { private static final Map<String, Set<String>> VALID_USERS = ImmutableMap.of( "guest", ImmutableSet.of(), "user", ImmutableSet.of("USER"), "admin", ImmutableSet.of("ADMIN", "USER") ); @Override public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException { if (VALID_USERS.containsKey(credentials.getUsername()) && "password".equals(credentials.getPassword())) { return Optional.of(new User(credentials.getUsername(), VALID_USERS.get(credentials.getUsername()))); } return Optional.empty(); } } ``` ## 添加自定義授權器 `Authorizer`類負責匹配角色,并確定是否允許用戶執行某些操作。 ```java package com.howtodoinjava.rest.auth; import io.dropwizard.auth.Authorizer; public class AppAuthorizer implements Authorizer<User> { @Override public boolean authorize(User user, String role) { return user.getRoles() != null && user.getRoles().contains(role); } } ``` ## 配置`BasicCredentialAuthFilter` 現在,讓我們將自定義類注冊到 dropwizard 安全框架中。 ```java package com.howtodoinjava.rest; import io.dropwizard.Application; import io.dropwizard.Configuration; import io.dropwizard.auth.AuthDynamicFeature; import io.dropwizard.auth.AuthValueFactoryProvider; import io.dropwizard.auth.basic.BasicCredentialAuthFilter; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import javax.ws.rs.client.Client; import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; import com.howtodoinjava.rest.auth.AppAuthorizer; import com.howtodoinjava.rest.auth.AppBasicAuthenticator; import com.howtodoinjava.rest.auth.User; import com.howtodoinjava.rest.controller.EmployeeRESTController; import com.howtodoinjava.rest.controller.RESTClientController; import com.howtodoinjava.rest.healthcheck.AppHealthCheck; import com.howtodoinjava.rest.healthcheck.HealthCheckController; public class App extends Application<Configuration> { @Override public void initialize(Bootstrap<Configuration> b) { } @Override public void run(Configuration c, Environment e) throws Exception { e.jersey().register(new EmployeeRESTController(e.getValidator())); final Client client = new JerseyClientBuilder(e).build("DemoRESTClient"); e.jersey().register(new RESTClientController(client)); // Application health check e.healthChecks().register("APIHealthCheck", new AppHealthCheck(client)); // Run multiple health checks e.jersey().register(new HealthCheckController(e.healthChecks())); //****** Dropwizard security - custom classes ***********/ e.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new AppBasicAuthenticator()) .setAuthorizer(new AppAuthorizer()) .setRealm("BASIC-AUTH-REALM") .buildAuthFilter())); e.jersey().register(RolesAllowedDynamicFeature.class); e.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); } public static void main(String[] args) throws Exception { new App().run(args); } } ``` ## 具有`@Auth`注解的安全 REST API 添加`@Auth`注解將在將其作為參數的任何 API 上觸發認證過濾器。 #### 1)用戶必須經過驗證。 允許所有用戶使用 API??。 ```java @PermitAll @GET public Response getEmployees(@Auth User user) { return Response.ok(EmployeeDB.getEmployees()).build(); } ``` #### 2)用戶必須經過驗證。 僅角色為`ADMIN`的所有用戶都可以使用 API??。 ```java @RolesAllowed({ "ADMIN" }) @GET @Path("/{id}") public Response getEmployeeById(@PathParam("id") Integer id, @Auth User user) { Employee employee = EmployeeDB.getEmployee(id); if (employee != null) return Response.ok(employee).build(); else return Response.status(Status.NOT_FOUND).build(); } ``` 這樣,您可以根據需要在所有 API 中添加各種認證方案。 ## 測試 Dropwizard 基本驗證代碼 讓我們測試一下我們的安全 API。 #### 調用任何安全的 API ![Basic Authentication Screen](https://img.kancloud.cn/2b/a5/2ba5decab6f2aba4a2fc02cf55623ebb_363x245.png) 基本認證屏幕 #### `http://localhost:8080/employees` ![Authenticated and allowed to all roles](https://img.kancloud.cn/db/b4/dbb436676971ea09ed73ae783fdbfcd5_948x471.png) 經過認證并允許所有角色 #### `http://localhost:8080/employees/1` ![Authenticated and allowed to ADMIN role only](https://img.kancloud.cn/38/aa/38aab298e65ef50811c751bfe378d980_946x406.png) 經過認證并僅允許`ADMIN`角色 將我的問題放在評論部分。 學習愉快! [源碼下載](//howtodoinjava.com/wp-content/downloads/DropWizardExample.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>

                              哎呀哎呀视频在线观看