1. Introduction
1.绪论
In this tutorial, we’ll show how to externalize Spring Security’s authorization decisions to OPA – the Open Policy Agent.
在本教程中,我们将展示如何将 Spring Security 的授权决策外化为 OPA – 开放策略代理。
2. Preamble: the Case for Externalized Authorization
2.序言:外部化授权的案例
A common requirement across applications is to have the ability to make certain decisions based on a policy. When this policy is simple enough and unlikely to change, we can implement this policy directly in code, which is the most common scenario.
整个应用程序的一个共同要求是拥有根据策略做出某些决定的能力。当这个策略足够简单且不太可能改变时,我们可以直接在代码中实现这个策略,这是最常见的情况。
However, there are other cases where we need more flexibility. Access control decisions are typical: as the application grows in complexity, granting access to a given functionality might depend not only on who you are but also on other contextual aspects of the request. Those aspects might include the IP address, time of day, and login authentication method (ex: “remember me”, OTP), among others.
然而,在其他情况下,我们需要更多的灵活性。访问控制决策是典型的:随着应用程序的复杂性增加,授予对特定功能的访问可能不仅取决于你是谁,还取决于请求的其他背景方面。这些方面可能包括IP地址,一天中的时间,以及登录认证方法(例如:”记住我”,OTP),等等。
Moreover, the rules compounding that contextual information with the user’s identity should be easy to change, preferably with no application downtime. This requirement naturally leads to an architecture where a dedicated service handles policy evaluation requests.
此外,与用户身份复合的上下文信息的规则应该很容易改变,最好是在没有应用程序停机的情况下。这一要求自然导致了一种架构,即由专门的服务处理政策评估请求。
Here, the tradeoff for this flexibility is the added complexity and the performance penalty incurred for making the call to the external service. On the other hand, we can evolve or even replace the authorization service entirely without affecting the application. Furthermore, we can share this service with multiple applications, thus allowing a consistent authorization model across them.
在这里,这种灵活性的代价是增加的复杂性和调用外部服务所带来的性能损失。另一方面,我们可以在不影响应用程序的情况下发展甚至完全替换授权服务。此外,我们还可以与多个应用程序共享这个服务,从而使它们的授权模式保持一致。
3. What’s OPA?
3.什么是OPA?
The Open Policy Agent, or OPA for short, is an open-source policy evaluation engine implemented in Go. It was initially developed by Styra and is now a CNCF-graduated project. Here’s a list of some typical uses of this tool:
开放政策代理,简称OPA,是一个用Go实现的开源政策评估引擎。它最初由Styra开发,现在是CNCF的一个毕业项目。这里列出了这个工具的一些典型用途。
- Envoy authorization filter
- Kubernetes admission controller
- Terraform plan evaluation
Installing OPA is quite simple: Just download the binary for our platform, put it in a folder in the operating system’s PATH, and we’re good to go. We can verify it’s correctly installed with a simple command:
安装OPA是非常简单的。只要下载适合我们平台的二进制文件,把它放在操作系统PATH中的一个文件夹里,我们就可以开始了。我们可以用一个简单的命令来验证它是否正确安装。
$ opa version
Version: 0.39.0
Build Commit: cc965f6
Build Timestamp: 2022-03-31T12:34:56Z
Build Hostname: 5aba1d393f31
Go Version: go1.18
Platform: windows/amd64
WebAssembly: available
OPA evaluates policies written in REGO, a declarative language optimized to run queries on complex object structures. The result of those queries is then used by client applications according to the specific use case. In our case, the object structure is an authorization request, and we’ll use the policy to query the result to grant access to a given functionality.
OPA评估用REGO编写的策略,这是一种经过优化的声明性语言,可以对复杂的对象结构运行查询。这些查询的结果然后由客户应用程序根据具体的使用情况来使用。在我们的案例中,对象结构是一个授权请求,我们将使用策略来查询结果,以授予对特定功能的访问。
It is important to notice that OPA’s policies are generic and not tied to in any way to express authorization decisions. In fact, we can use it in other scenarios that traditionally are dominated by rule engines like Drools and others.
需要注意的是,OPA的策略是通用的,不以任何方式与表达授权决策挂钩。事实上,我们可以将其用于其他传统上由Drools等规则引擎主导的场景。
4. Writing Policies
4.写作政策
This is what a simple authorization policy written in REGO looks like:
这就是用REGO编写的简单授权策略的样子。
package baeldung.auth.account
# Not authorized by default
default authorized = false
authorized = true {
count(deny) == 0
count(allow) > 0
}
# Allow access to /public
allow["public"] {
regex.match("^/public/.*",input.uri)
}
# Account API requires authenticated user
deny["account_api_authenticated"] {
regex.match("^/account/.*",input.uri)
regex.match("ANONYMOUS",input.principal)
}
# Authorize access to account
allow["account_api_authorized"] {
regex.match("^/account/.+",input.uri)
parts := split(input.uri,"/")
account := parts[2]
role := concat(":",[ "ROLE_account", "read", account] )
role == input.authorities[i]
}
The first thing to notice is the package statement. OPA policies use packages to organize rules, and they also play a key role when evaluating incoming requests, as we’ll show later. We can organize policy files across multiple directories.
首先要注意的是包的声明。OPA策略使用包来组织规则,它们在评估传入请求时也发挥了关键作用,我们将在后面展示。我们可以在多个目录下组织策略文件。
Next, we define the actual policy rules:
接下来,我们定义实际的政策规则。
- A default rule to ensure that we’ll always end up with a value for the authorized variable
- The main aggregator rule that we can read as “authorized is true when there are no rules denying access and at least one rule allowing access”
- Allow and deny rules, each one expressing a condition that, if matched, will add an entry to the allow or deny arrays, respectively
A complete description of OPA’s policy language is beyond the scope of this article, but the rules themselves are not hard to read. There are a few things to keep in mind when looking at them:
对OPA政策语言的完整描述超出了本文的范围,但规则本身并不难读。在看这些规则时,有几件事需要记住。
- Statements of the form a := b or a=b are simple assignments (they’re not the same, though)
- Statements of the form a = b { … conditions } or a { …conditions } mean “assign b to a if conditions are true
- Order appearance in the policy document is irrelevant
Other than that, OPA comes with a rich built-in function library optimized for querying deeply nested data structures, along with more familiar features such as string manipulation, collections, and so forth.
除此之外,OPA还有一个丰富的内置函数库,为查询深度嵌套的数据结构进行了优化,同时还有更多熟悉的功能,如字符串操作、集合等等。
5. Evaluating Policies
5.评估政策
Let’s use the policy defined in the previous section to evaluate an authorization request. In our case, we’ll build this authorization request using a JSON structure containing some pieces from the incoming request:
让我们使用上一节中定义的策略来评估一个授权请求。在我们的例子中,我们将使用一个包含传入请求的一些片段的JSON结构来建立这个授权请求。
{
"input": {
"principal": "user1",
"authorities": ["ROLE_account:read:0001"],
"uri": "/account/0001",
"headers": {
"WebTestClient-Request-Id": "1",
"Accept": "application/json"
}
}
}
Notice that we’ve wrapped the request attributes in a single input object. This object becomes the input variable during the policy evaluation, and we can access its properties using a JavaScript-like syntax.
请注意,我们已经将请求属性包装在一个input对象中。这个对象在策略评估期间成为input变量,我们可以使用类似JavaScript的语法来访问它的属性。
To test if our policy works as expected, let’s run OPA locally in server mode and manually submit some test requests:
为了测试我们的策略是否像预期的那样工作,让我们在本地以服务器模式运行OPA,并手动提交一些测试请求。
$ opa run -w -s src/test/rego
The option -s enables running in server mode, while -w enables automatic rule file reloading. The src/test/rego is the folder containing policy files from our sample code. Once running, OPA will listen for API requests on local port 8181. If needed, we can change the default port using the -a option.
选项-s可以在服务器模式下运行,而-w可以自动重新加载规则文件。src/test/rego是包含我们样本代码的策略文件的文件夹。一旦运行,OPA将监听本地8181端口的API请求。如果需要,我们可以使用-a选项改变默认端口。
Now, we can use curl or some other tool to send the request:
现在,我们可以使用curl或其他一些工具来发送请求。
$ curl --location --request POST 'http://localhost:8181/v1/data/baeldung/auth/account' \
--header 'Content-Type: application/json' \
--data-raw '{
"input": {
"principal": "user1",
"authorities": [],
"uri": "/account/0001",
"headers": {
"WebTestClient-Request-Id": "1",
"Accept": "application/json"
}
}
}'
Notice the path part after the /v1/data prefix: It corresponds to the policy’s package name, with dots replaced by forward slashes.
注意/v1/data前缀之后的路径部分。它与策略的包名相对应,点被正斜线取代。
The response will be a JSON object containing all results produced by evaluating the policy against input data:
响应将是一个JSON对象,包含根据输入数据评估政策产生的所有结果。
{
"result": {
"allow": [],
"authorized": false,
"deny": []
}
}
The result property is an object containing the results produced by the policy engine. We can see that, in this case, the authorized property is false. We can also see that allow and deny are empty arrays. This means that no specific rule matched the input. As a result, the main authorized rule didn’t match either.
result 属性是一个包含由策略引擎产生的结果的对象。我们可以看到,在这种情况下,authorized属性是false。我们还可以看到,allow和deny是空数组。这意味着没有特定的规则与输入相匹配。因此,主要的授权规则也没有匹配。
6. Spring Authorization Manager Integration
6.Spring授权管理器集成
Now that we’ve seen the way OPA works, we can move forward and integrate it into the Spring Authorization framework. Here, we’ll focus on its reactive web variant, but the general idea applies to regular MVC-based applications too.
现在我们已经看到了OPA的工作方式,我们可以继续前进并将其集成到Spring授权框架中。在这里,我们将专注于它的反应式Web变体,但一般的想法也适用于基于MVC的常规应用。
First, we need to implement ReactiveAuthorizationManager bean that uses OPA as its backend:
首先,我们需要实现ReactiveAuthorizationManager bean,它使用OPA作为其后台。
@Bean
public ReactiveAuthorizationManager<AuthorizationContext> opaAuthManager(WebClient opaWebClient) {
return (auth, context) -> {
return opaWebClient.post()
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.body(toAuthorizationPayload(auth,context), Map.class)
.exchangeToMono(this::toDecision);
};
}
Here, the injected WebClient comes from another bean, where we pre-initialize its properties from a @ConfigurationPropreties class.
这里,注入的WebClient来自另一个Bean,我们从@ConfigurationPropreties类中预先初始化其属性。
The processing pipeline delegates to the toAuthorizationRequest method the duty of gathering information from the current Authentication and AuthorizationContext and then building an authorization request payload. Similarly, toAuthorizationDecision takes the authorization response and maps it to an AuthorizationDecision.
处理管道将从当前的Authentication和AuthorizationContext中收集信息的职责委托给toAuthorizationRequest方法,然后构建一个授权请求有效载荷。同样地,toAuthorizationDecision接收授权响应并将其映射到AuthorizationDecision。
Now, we use this bean to build a SecurityWebFilterChain:
现在,我们使用这个bean来建立一个SecurityWebFilterChain:。
@Bean
public SecurityWebFilterChain accountAuthorization(ServerHttpSecurity http, @Qualifier("opaWebClient") WebClient opaWebClient) {
return http
.httpBasic()
.and()
.authorizeExchange(exchanges -> {
exchanges
.pathMatchers("/account/*")
.access(opaAuthManager(opaWebClient));
})
.build();
}
We’re applying our custom AuthorizationManager to the /account API only. The reason behind this approach is that we could easily extend this logic to support multiple policy documents, thus making them easier to maintain. For instance, we could have a configuration that uses the request URI to select an appropriate rule package and use this information to build the authorization request.
我们将我们的自定义AuthorizationManager仅应用于/account API。这种方法背后的原因是,我们可以很容易地扩展这种逻辑,以支持多个策略文件,从而使它们更容易维护。例如,我们可以有一个配置,使用请求URI来选择一个合适的规则包,并使用这些信息来建立授权请求。
In our case, the /account API itself is just a simple controller/service pair that returns an Account object populated with a fake balance.
在我们的案例中,/account API本身只是一个简单的控制器/服务对,它返回一个Account对象,并填充一个假的余额。
7. Testing
7.测试
Last but not least, let’s build an integration test to put everything together. First, let’s ensure the “happy path” works. This means that given an authenticated user, they should be able to access their own account:
最后但并非最不重要的是,让我们建立一个集成测试,把所有东西放在一起。首先,让我们确保 “快乐路径 “的工作。这意味着,给定一个认证的用户,他们应该能够访问自己的账户。
@Test
@WithMockUser(username = "user1", roles = { "account:read:0001"} )
void testGivenValidUser_thenSuccess() {
rest.get()
.uri("/account/0001")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.is2xxSuccessful();
}
Secondly, we must also verify that an authenticated user should only be able to access their own account:
其次,我们还必须验证,经过认证的用户应该只能访问他们自己的账户。
@Test
@WithMockUser(username = "user1", roles = { "account:read:0002"} )
void testGivenValidUser_thenUnauthorized() {
rest.get()
.uri("/account/0001")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isForbidden();
}
Finally, let’ also test the case where the authenticated user has no authority:
最后,让我们也测试一下认证用户没有权限的情况。
@Test
@WithMockUser(username = "user1", roles = {} )
void testGivenNoAuthorities_thenForbidden() {
rest.get()
.uri("/account/0001")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isForbidden();
}
We can run those tests from the IDE or the command line. Please notice that, in either case, we must first start the OPA server pointing to the folder containing our authorization policy file.
我们可以从IDE或命令行中运行这些测试。请注意,无论哪种情况,我们都必须首先启动OPA服务器,指向包含我们的授权策略文件的文件夹。
8. Conclusion
8.结语
In this article, we’ve shown how to use OPA to externalize authorization decisions of a Spring Security-based application. As usual, complete code is available over on GitHub.
在这篇文章中,我们展示了如何使用OPA来外部化基于Spring Security的应用程序的授权决策。像往常一样,完整的代码可以在GitHub上找到。