# SpringBoot Security中GitHub單點登錄的操作方法
## 1. 單點登錄(SSO)與OAuth2.0簡介
單點登錄(Single Sign-On, SSO)是一種身份驗證機制,允許用戶通過單一憑證訪問多個關聯系統。OAuth2.0是當前主流的授權框架,GitHub等平臺均提供基于OAuth2.0的SSO支持。
### 核心概念
- **OAuth2.0角色**:資源所有者(用戶)、客戶端(應用)、授權服務器(GitHub)、資源服務器(GitHub API)
- **授權流程**:授權碼模式(Authorization Code)最常用
## 2. 準備工作
### 2.1 GitHub應用注冊
1. 訪問 [GitHub Developer Settings](https://github.com/settings/developers)
2. 創建新OAuth應用("New OAuth App")
3. 填寫關鍵信息:
```plaintext
Application name: 您的應用名稱
Homepage URL: http://localhost:8080
Authorization callback URL: http://localhost:8080/login/oauth2/code/github
Client ID
和Client Secret
<!-- pom.xml 關鍵依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
// SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/login")
.defaultSuccessUrl("/home", true)
);
return http.build();
}
}
# application.yml
spring:
security:
oauth2:
client:
registration:
github:
client-id: ${GITHUB_CLIENT_ID}
client-secret: ${GITHUB_CLIENT_SECRET}
scope: user:email
最佳實踐:將敏感信息存儲在環境變量中而非代碼庫
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
@Override
public OAuth2User loadUser(OAuth2UserRequest request) {
DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();
OAuth2User user = delegate.loadUser(request);
Map<String, Object> attributes = user.getAttributes();
// 可在此處進行用戶信息處理或數據庫存儲
return user;
}
}
// 更新SecurityConfig
.oauth2Login(oauth2 -> oauth2
.userInfoEndpoint(userInfo -> userInfo
.userService(customOAuth2UserService)
)
)
@GetMapping("/api/user")
@ResponseBody
public Map<String, Object> userInfo(@AuthenticationPrincipal OAuth2User user) {
return Collections.singletonMap("name", user.getAttribute("name"));
}
<!-- templates/home.html -->
<div th:if="${#authentication.principal}">
<h2>Welcome, <span th:text="${#authentication.principal.attributes['login']}"></span>!</h2>
<img th:src="${#authentication.principal.attributes['avatar_url']}" width="100"/>
</div>
spring:
security:
oauth2:
client:
registration:
github:
client-name: GitHub
provider: github
github-enterprise:
client-name: GitHub Enterprise
client-id: enterprise-client-id
client-secret: enterprise-secret
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
scope: user,repo
client-authentication-method: post
// 添加JWT依賴后配置
.oauth2Login(oauth2 -> oauth2
.successHandler((request, response, authentication) -> {
String token = generateJwtToken(authentication);
response.sendRedirect("/dashboard?token=" + token);
})
)
重定向URI不匹配:
application.yml
完全一致403禁止訪問:
// 添加CSRF配置
http.csrf(csrf -> csrf
.ignoringRequestMatchers("/login/oauth2/code/**")
);
范圍權限不足:
scope: read:user,user:email
HTTPS強制:
server.ssl.enabled=true
會話管理:
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
)
限流保護:
http.requestCache().disable()
.headers().frameOptions().sameOrigin()
.and().exceptionHandling().accessDeniedPage("/403");
通過Spring Security OAuth2 Client集成GitHub登錄,開發者可以快速實現安全可靠的SSO方案。本文介紹的配置方法可擴展至其他OAuth2提供商(如Google、Facebook),只需替換相應配置即可。建議在實際項目中結合JWT、Redis等組件構建更完善的認證體系。
完整示例代碼:可訪問 GitHub示例倉庫 “`
(注:實際字數約1500字,可根據需要調整章節深度。關鍵代碼已提供完整實現路徑,建議配合實際調試使用)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。