61.md 7.4 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4
# Dropwizard – BasicAuth 安全示例

> 原文: [https://howtodoinjava.com/dropwizard/dropwizard-basic-auth-security-example/](https://howtodoinjava.com/dropwizard/dropwizard-basic-auth-security-example/)

W
wizardforcel 已提交
5
使用 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 中。
W
wizardforcel 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18

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

W
wizardforcel 已提交
19
## 包含 Dropwizard Auth 模块的 Maven 依赖项
W
wizardforcel 已提交
20

W
wizardforcel 已提交
21
认证功能在 dropwizard 应用中作为单独的模块添加。
W
wizardforcel 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

```java
<properties>
	<dropwizard.version>1.0.0</dropwizard.version>
</properties>
<dependency>
	<groupId>io.dropwizard</groupId>
	<artifactId>dropwizard-auth</artifactId>
	<version>${dropwizard.version}</version>
</dependency>

```

## 添加自定义主体对象

W
wizardforcel 已提交
37
在安全性方面,主体对象表示已为其提供凭据的用户。 它实现了`java.security.Principal`接口。
W
wizardforcel 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

```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;
    }
}

```

W
wizardforcel 已提交
75
## 添加自定义认证器
W
wizardforcel 已提交
76

W
wizardforcel 已提交
77
`Authenticator`类负责验证基本认证标头中包含的用户名/密码凭证。 在企业应用中,您可以从数据库中获取用户密码,如果密码匹配,则将用户角色设置为主体对象。 在 dropwizard 中,您将需要实现`io.dropwizard.auth.Authenticator`接口以放置您的应用逻辑。
W
wizardforcel 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

```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();
    }
}

```

W
wizardforcel 已提交
114
## 添加自定义授权器
W
wizardforcel 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

`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);
    }
}

```

W
wizardforcel 已提交
133
## 配置`BasicCredentialAuthFilter`
W
wizardforcel 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

现在,让我们将自定义类注册到 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);
	}
}

```

W
wizardforcel 已提交
197
## 具有`@Auth`注解的安全 REST API
W
wizardforcel 已提交
198

W
wizardforcel 已提交
199
添加`@Auth`注解将在将其作为参数的任何 API 上触发认证过滤器。
W
wizardforcel 已提交
200 201 202 203 204 205 206 207 208 209 210 211

#### 1)用户必须经过验证。 允许所有用户使用 API​​。

```java
@PermitAll
@GET
public Response getEmployees(@Auth User user) {
	return Response.ok(EmployeeDB.getEmployees()).build();
}

```

W
wizardforcel 已提交
212
#### 2)用户必须经过验证。 仅角色为`ADMIN`的所有用户都可以使用 API​​。
W
wizardforcel 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

```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();
}

```

W
wizardforcel 已提交
228
这样,您可以根据需要在所有 API 中添加各种认证方案。
W
wizardforcel 已提交
229

W
wizardforcel 已提交
230
## 测试 Dropwizard 基本验证代码
W
wizardforcel 已提交
231 232 233 234 235

让我们测试一下我们的安全 API。

#### 调用任何安全的 API

W
wizardforcel 已提交
236 237
![Basic Authentication Screen](img/56f39a3b025386d461d8fcc301894442.png)

W
wizardforcel 已提交
238
基本认证屏幕
W
wizardforcel 已提交
239 240 241



W
wizardforcel 已提交
242
#### `http://localhost:8080/employees`
W
wizardforcel 已提交
243

W
wizardforcel 已提交
244 245
![Authenticated and allowed to all roles](img/5318634f4deb3de26864415723abcd4f.png)

W
wizardforcel 已提交
246
经过认证并允许所有角色
W
wizardforcel 已提交
247 248 249



W
wizardforcel 已提交
250
#### `http://localhost:8080/employees/1`
W
wizardforcel 已提交
251

W
wizardforcel 已提交
252 253
![Authenticated and allowed to ADMIN role only](img/fbb8cceba654c954c3a8e89a6611b195.png)

W
wizardforcel 已提交
254
经过认证并仅允许`ADMIN`角色
W
wizardforcel 已提交
255 256 257 258 259 260 261



将我的问题放在评论部分。

学习愉快!

W
wizardforcel 已提交
262
[源码下载](//howtodoinjava.com/wp-content/downloads/DropWizardExample.zip)