我正在尝试使用“Cognito Oauth2”在资源服务器中实现Spring Security,但是我似乎找不到太多信息。关于它(或者甚至有可能这样做)。
我最近的方法是使用“Nimbus + JOSE”检查带有“JWKS”的“访问 token ”的有效性,并授予访问该资源的权限。
(类似于他们通过“API网关资源保护实现”给出的示例,可以在这里找到:https://aws.amazon.com/es/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/)
最佳答案
在这里可以找到使用最新的Sprint Boot 2.x/Sprint Security 5.x的Oauth2的绝佳起点:https://spring.io/blog/2018/03/06/using-spring-security-5-to-integrate-with-oauth-2-secured-services-such-as-facebook-and-github
它以Facebook/Github为例,但您也可以将其应用于AWS Cognito。
到目前为止,这是使用Spring Security/Cognito OAuth2设置安全REST后端的最简单方法。您的后端将通过Spring Security进行保护,AWS Cognito将用作身份提供者。
您可以使用本文中概述的spring安全启动器使用以下依赖项来设置vanilla spring boot应用程序:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
并提供您的认知配置(客户端注册+提供者定义),如下所示:
spring:
security:
oauth2:
client:
registration:
cognito-client-1:
client-id: 391uhnjlr8v8kicm3cru6g1s8g
client-secret: xxxxxxxxxxxxxxxxxxxxxxxxxx
client-name: Cognito Code Grant
provider: cognito
scope: openid
redirect-uri-template: http://localhost:8080/login/oauth2/code/cognito
authorization-grant-type: authorization_code
provider:
cognito:
authorization-uri: https://custom-domain.auth.eu-central-1.amazoncognito.com/oauth2/authorize
token-uri: https://custom-domain.auth.eu-central-1.amazoncognito.com/oauth2/token
user-info-uri: https://custom-domain.auth.eu-central-1.amazoncognito.com/oauth2/userInfo
jwk-set-uri: https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_xxxxxxxxx/.well-known/jwks.json
user-name-attribute: cognito:username
就Cognito而言,您需要在一个拥有两个用户的用户池/身份池和一个有效的app客户端(spring config中的
client-id
)中使用client-secret
)redirect-uri-template
)jwk-set-uri
)一切就绪后,Spring Boot应用程序将自动生成一个登录URL
将您重定向到Cognito登录页面,您可以在其中输入您的Cognito凭据
通过成功的身份验证后,您将可以进行安全的REST调用
使用这样的REST Controller :
@RestController
public class ExampleController {
@RequestMapping("/")
public String email(Principal principal) {
return "Hello " + principal.getName();
}
}