首頁 Java java教程 如何使用Java開發一個基於Spring Security OAuth2的單一登入系統

如何使用Java開發一個基於Spring Security OAuth2的單一登入系統

Sep 20, 2023 pm 01:06 PM
java oauth spring security

如何使用Java开发一个基于Spring Security OAuth2的单点登录系统

如何使用Java開發一個基於Spring Security OAuth2的單一登入系統

引言:
隨著網路的高速發展,越來越多的網站和應用程式需要用戶進行登錄,而用戶不希望為每個網站或應用程式記住一個帳號和密碼。單一登入系統(Single Sign-On,簡稱SSO)能夠解決這個問題,允許使用者在一次登入後,無需重複認證即可存取多個網站和應用程式。本文將介紹如何使用Java開發一個基於Spring Security OAuth2的單一登入系統,並提供具體的程式碼範例。

一、準備工作:
在開始開發之前,我們需要準備一些基本的工具和環境:

  1. JDK 1.8以上版本;
  2. Maven 3.0以上版本;
  3. 開發IDE,如Eclipse、IntelliJ IDEA等;
  4. 一個可用的MySQL資料庫。

二、建立Spring Boot項目:
首先,我們需要建立一個Spring Boot項目,並且加入所需的依賴項。打開Eclipse或IntelliJ IDEA,點擊"New",選擇"Spring Starter Project",並填寫必要的資訊(如專案名稱、套件名稱等)。然後,新增以下相依性到專案的pom.xml檔案中:

<dependencies>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.security.oauth</groupId>
       <artifactId>spring-security-oauth2</artifactId>
       <version>2.3.4.RELEASE</version>
   </dependency>
   <!-- 添加其他需要的依赖 -->
</dependencies>
登入後複製

三、設定Spring Security OAuth2:
接下來,我們需要設定Spring Security OAuth2模組。在src/main/resources目錄下建立一個名為application.yml的文件,並新增以下設定資訊:

spring:
   security:
       oauth2:
           client:
               registration:
                   custom:
                       client-id: {your-client-id}
                       client-secret: {your-client-secret}
                       provider: custom
                       auth-uri: {authorization-uri}
                       token-uri: {token-uri}
                       user-info-uri: {user-info-uri}
                       redirect-uri: {redirect-uri}
                       scope: {scope-list}
               provider:
                   custom:
                       authorization-uri: {authorization-uri}
                       token-uri: {token-uri}
                       user-info-uri: {user-info-uri}
           resource:
               user-info-uri: {user-info-uri}
登入後複製

上述設定中,{your-client-id}、{your-client-secret} 、{authorization-uri}、{token-uri}、{user-info-uri}、{redirect-uri}和{scope-list}分別需要替換為實際的值。

四、建立登入頁面:
接下來,我們需要建立一個登入頁面來進行使用者登入。在src/main/resources/templates目錄下建立一個名為login.html的文件,並新增以下程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form method="post" action="/login">
        <div>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" />
        </div>
        <div>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" />
        </div>
        <button type="submit">Login</button>
    </form>
</body>
</html>
登入後複製

五、建立認證和授權伺服器:
接下來,我們需要建立一個認證伺服器(Authorization Server)和一個授權伺服器(Resource Server)來處理使用者的認證和授權。建立一個名為SecurityConfig的Java類,並加入以下程式碼:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated()
           .and().formLogin().loginPage("/login").permitAll()
           .and().logout().logoutSuccessUrl("/login?logout").permitAll();

      http.csrf().disable();
   }
   
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.inMemoryAuthentication()
           .withUser("admin").password("{noop}admin").roles("ADMIN");
   }
}
登入後複製

六、建立資源伺服器:
接下來,我們需要建立一個資源伺服器來保護我們的API。建立一個名為ResourceServerConfig的Java類,並新增以下程式碼:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
   
   @Override
   public void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests().antMatchers("/api/**").authenticated();
   }

}
登入後複製

七、測試單一登入:
到此,我們已經完成了單一登入系統的開發。我們可以運行應用程序,並透過瀏覽器訪問登入頁面(http://localhost:8080/login)進行登入。登入成功後,我們可以在其他受保護的資源上透過要求頭部新增Access Token來存取。

結論:
本文介紹如何使用Java開發一個基於Spring Security OAuth2的單一登入系統,並提供了具體的程式碼範例。透過使用單一登入系統,使用者可以輕鬆存取多個網站和應用程序,而無需重複進行認證。希望本文能幫助讀者更能理解和應用Spring Security OAuth2的相關知識。

以上是如何使用Java開發一個基於Spring Security OAuth2的單一登入系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Java 中的平方根 Java 中的平方根 Aug 30, 2024 pm 04:26 PM

Java 中的平方根

Java 中的完美數 Java 中的完美數 Aug 30, 2024 pm 04:28 PM

Java 中的完美數

Java 中的隨機數產生器 Java 中的隨機數產生器 Aug 30, 2024 pm 04:27 PM

Java 中的隨機數產生器

Java中的Weka Java中的Weka Aug 30, 2024 pm 04:28 PM

Java中的Weka

Java 中的阿姆斯壯數 Java 中的阿姆斯壯數 Aug 30, 2024 pm 04:26 PM

Java 中的阿姆斯壯數

Java 中的史密斯數 Java 中的史密斯數 Aug 30, 2024 pm 04:28 PM

Java 中的史密斯數

Java Spring 面試題 Java Spring 面試題 Aug 30, 2024 pm 04:29 PM

Java Spring 面試題

突破或從Java 8流返回? 突破或從Java 8流返回? Feb 07, 2025 pm 12:09 PM

突破或從Java 8流返回?

See all articles