1. 簡介
本教程將介紹如何使用 Spring Security 的 OAuth 2.0 支持與 Amazon Cognito 進行身份驗證。
在學習過程中,我們將簡要了解 Amazon Cognito 是什麼以及它支持的 OAuth 2.0 流式。
最終,我們將擁有一個簡單的單頁應用程序。 沒有任何花哨的功能。
2. 什麼是亞馬遜認知服務?
亞馬遜認知服務 是一種用户身份和數據同步服務,它使我們能夠輕鬆地管理應用程序的用户數據,跨多個設備。
通過亞馬遜認知服務,我們可以:
- 創建、認證和授權應用程序中的用户
- 為使用其他公共 身份提供商(如 Google、Facebook 或 Twitter)的用户創建身份
- 將應用程序的用户數據保存為鍵值對
3. 設置
This section describes the steps required to set up the system.
3.1 Installing the Software
- Download the latest version of the software from our website: https://example.com/download
- Extract the downloaded archive to a directory of your choice.
- Run the installer executable (
setup.exeon Windows,setup.shon Linux/macOS). - Follow the on-screen instructions to complete the installation.
3.2 Configuring the System
- Launch the application from the Start Menu (Windows) or the Applications folder (macOS).
- The first time you run the application, you will be prompted to create an administrator account.
- Set the system time and date.
- Configure the network settings.
3.3 Initial Configuration
- Run the configuration wizard.
- Select your desired language.
- Enter your company name and address.
- Click "Finish" to complete the initial configuration.
# This code block demonstrates a simple example.
# It's designed to illustrate the basic functionality of the system.
# You can modify this code to suit your specific needs.
def main():
print("Hello, world!")
3.1. Amazon Cognito 設置
作為身份提供者,Cognito 支持 授權碼、隱式和客户端憑據 類型的授權。 針對我們的目的,我們設置使用 授權碼 類型的授權。
首先,我們需要進行一些 Cognito 設置:
在應用程序客户端的配置中,請確保 回調URL 與 Spring 配置文件的 redirect-uri 匹配。 在我們的情況下,這將是:
http://localhost:8080/login/oauth2/code/cognito允許的 OAuth 流應為授權碼流程。隨後,在同一頁面上,我們需要將允許的 OAuth 範圍設置為openid。
為了將用户重定向到 Cognito 的自定義登錄頁面,我們還需要添加用户泳池域名。
3.2. Spring 配置
為了使用 OAuth 2.0 登錄,我們需要將 <a href="https://mvnrepository.com/artifact/org.springframework.security/spring-security-oauth2-client">spring-security-oauth2-client</a> 和 <a href="https://mvnrepository.com/artifact/org.springframework.security/spring-security-oauth2-jose">spring-security-oauth2-jose</a> 依賴項添加到我們的應用程序中:
<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:
clientId: clientId
clientSecret: clientSecret
scope: openid
redirect-uri: http://localhost:8080/login/oauth2/code/cognito
clientName: clientName
provider:
cognito:
issuerUri: https://cognito-idp.{region}.amazonaws.com/{poolId}
user-name-attribute: cognito:username在上述配置中,clientId、clientSecret、clientName和issuerUri應根據我們在AWS上創建的用户泳池和應用客户端進行填充。
並且有了這些,我們應該已經完成了Spring和Amazon Cognito的設置! 教程的其餘部分定義了應用程序的安全配置,並解決了一些遺留問題。
3.3. Spring Security 配置
現在我們將添加一個安全配置類:
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(Customizer.withDefaults())
.authorizeHttpRequests(authz -> authz.requestMatchers("/")
.permitAll()
.anyRequest()
.authenticated())
.oauth2Login(Customizer.withDefaults())
.logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutSuccessUrl("/"));
return http.build();
}
}首先,我們指定了需要防範 CSRF 攻擊,然後允許所有人訪問我們的登陸頁面。之後,我們添加了對 oauth2Login 的調用,以集成 Cognito 客户端註冊。
4. 添加登陸頁面
接下來,我們添加一個簡單的 Thymeleaf 登陸頁面,以便在登錄時進行確認:
<div>
<h1 class="title">OAuth 2.0 Spring Security Cognito Demo</h1>
<div sec:authorize="isAuthenticated()">
<div class="box">
Hello, <strong th:text="${#authentication.name}"></strong>!
</div>
</div>
<div sec:authorize="isAnonymous()">
<div class="box">
<a class="button login is-primary" th:href="@{/oauth2/authorization/cognito}">
Log in with Amazon Cognito</a>
</div>
</div>
</div>簡單來説,當用户已登錄時,它將顯示用户名;當未登錄時,它將顯示登錄鏈接。請務必注意鏈接的外觀,因為它會從我們的配置文件中獲取 cognito 部分。
然後,我們確保將應用程序根目錄與歡迎頁面關聯:
@Configuration
public class CognitoWebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}5. 運行應用程序
這是負責啓動所有身份驗證相關操作的類。
@SpringBootApplication
public class SpringCognitoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCognitoApplication.class, args);
}
}現在我們可以開始運行我們的應用程序,請前往 http://localhost:8080,然後點擊登錄鏈接。 輸入我們先前在 AWS 上創建的用户憑據後,我們應該能夠看到 Hello, username 消息。
6. 結論
在本教程中,我們探討了如何將 Spring Security 與 Amazon Cognito 集成,只需進行一些簡單的配置。然後,我們通過幾段代碼將所有內容整合在一起。