成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Spring Security OAuth2 大揭秘

開發 架構
OAuth2 是一個授權框架, 允許用戶授權第三方應用訪問他們的資源(比如 GitHub 上的個人信息), 而無需直接提供密碼。

一、OAuth2是什么?為什么需要它?

OAuth2 是一個授權框架, 允許用戶授權第三方應用訪問他們的資源(比如 GitHub 上的個人信息), 而無需直接提供密碼。

例如: 你想用 GitHub 賬號登錄某個網站, 這個網站會跳轉到 GitHub 讓你授權, 授權成功后, 網站就能獲取你的 GitHub 基本信息(比如用戶名、頭像), 但不會拿到你的密碼. 

OAuth2核心角色: 

  1. 資源所有者(Resource Owner): 就是用戶本人
  2. 客戶端(Client): 我們的Spring Boot應用
  3. 授權服務器(Authorization Server): 比如GitHub、Google的OAuth2服務
  4. 資源服務器(Resource Server): 存儲用戶數據的服務器

OAuth2的核心實現流程圖: 

圖片圖片

二、Spring Security OAuth2快速入門

1) 添加依賴

首先, 在你的 pom.xml 里加入 Spring Security OAuth2 的依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

2) 配置application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: your-github-client-id
            client-secret: your-github-client-secret
            scope: user:email,read:user

1. client-id 和 client-secret: 去 GitHub Developer Settings 申請 OAuth App 獲取. 

2. scope: 定義你要獲取的用戶權限, 比如 user:email 可以獲取用戶的郵箱. 

3) 創建Security配置類

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login**").permitAll()
                .anyRequest().authenticated()
            .and()
            .oauth2Login();  // 啟用 OAuth2 登錄
    }
}

現在, 訪問你的網站, 點擊登錄, 就會自動跳轉到 GitHub 授權頁面了. 

三、自定義OAuth2用戶信息

默認情況下, Spring Security 只會返回基本的用戶信息(如 nameemail). 但如果你想獲取更多信息(比如 GitHub 的 biolocation),就需要自定義 OAuth2UserService. 

@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {


    private final OAuth2UserService<OAuth2UserRequest, OAuth2User> defaultService = new DefaultOAuth2UserService();


    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        // 1. 先讓默認的 Service 加載用戶信息
        OAuth2User user = defaultService.loadUser(userRequest);


        // 2. 獲取額外的用戶信息(GitHub API)
        if ("github".equals(userRequest.getClientRegistration().getRegistrationId())) {
            String accessToken = userRequest.getAccessToken().getTokenValue();
            Map<String, Object> extraAttributes = fetchGitHubUserDetails(accessToken);
            user = new DefaultOAuth2User(user.getAuthorities(), extraAttributes, "login");  // "login" 是 GitHub 的主鍵字段
        }


        return user;
    }


    private Map<String, Object> fetchGitHubUserDetails(String accessToken) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(accessToken);
        HttpEntity<String> entity = new HttpEntity<>(headers);


        ResponseEntity<Map> response = restTemplate.exchange(
            "https://api.github.com/user",
            HttpMethod.GET,
            entity,
            Map.class
        );


        return response.getBody();
    }
}

更新Security配置: 

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private CustomOAuth2UserService customOAuth2UserService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login**").permitAll()
                .anyRequest().authenticated()
            .and()
            .oauth2Login()
                .userInfoEndpoint()
                    .userService(customOAuth2UserService);  // 使用自定義的 UserService
    }
}

四、獲取登錄用戶信息

1) 通過SecurityContextHolder獲取:

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.user.OAuth2User;


@GetMapping("/user")
public String getUserInfo() {
    OAuth2User principal = (OAuth2User) SecurityContextHolder.getContext()
                            .getAuthentication()
                            .getPrincipal();


    return "User: " + principal.getAttributes();
}

2)  通過@AuthenticationPrincipal注解獲取: 

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;


@GetMapping("/user")
public String getUserInfo(@AuthenticationPrincipal OAuth2User principal) {
    // GitHub返回的屬性示例
    String name = principal.getAttribute("login"); // GitHub用戶名
    String email = principal.getAttribute("email"); 
    String avatar = principal.getAttribute("avatar_url");


    return "Hello, " + name + "! Email: " + email;
}


責任編輯:武曉燕 來源: 全棧程序員老馬
相關推薦

2022-02-15 07:35:12

服務器KeycloakOAuth2

2021-08-29 18:36:57

項目

2022-04-11 07:34:46

OAuth2UAA節點

2025-04-29 09:07:21

2021-11-15 13:58:00

服務器配置授權

2013-05-02 14:13:44

Android開發OAuth2服務認證

2017-08-04 18:10:09

2023-08-31 08:34:07

Users對象序列化

2023-08-29 08:00:38

2025-04-01 05:00:00

OAuth2服務器身份驗證

2021-08-02 12:50:45

sessiontokenJava

2021-08-29 23:33:44

OAuth2服務器Keycloak

2025-01-13 08:04:24

2025-05-12 03:02:00

SpringOAuth2客戶端

2022-06-29 08:37:11

授權碼模式底層

2022-06-20 08:37:28

接口tokenAO

2014-04-21 14:56:45

NodeJSOAuth2服務器

2020-11-12 09:55:02

OAuth2

2014-09-24 11:47:41

微信企業號開發

2022-11-16 14:02:44

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 成人在线视频一区 | 欧美日本韩国一区二区 | 在线看h| 日韩综合在线视频 | 欧美多人在线 | 欧美一级免费 | 日韩精品一区二区三区 | 日本免费一区二区三区 | 婷婷在线免费 | aaa一区| 一级免费在线视频 | 日韩成人av在线 | 国产精品一区二区精品 | 国产一二三区在线 | 国产精品久久久久一区二区 | 亚洲成av人影片在线观看 | 久久久久久亚洲 | 国产欧美视频一区二区三区 | 91色在线视频 | 欧美成人手机在线 | 日韩中文字幕在线视频观看 | 蜜桃精品视频在线 | 欧美日韩专区 | 久久久久久久一区 | 日韩欧美视频免费在线观看 | 久久久国产精品一区 | 国产精品不卡一区 | 亚洲精品一二三区 | 夜夜爽99久久国产综合精品女不卡 | 久久成人激情 | 亚洲啊v在线 | 中文字幕亚洲视频 | 国产免费一区二区 | 呦呦在线视频 | 日韩精品1区2区3区 国产精品国产成人国产三级 | 欧美福利| 久久久久久99 | 波多野结衣二区 | 一级爱爱片 | 亚洲成人免费av | 欧美一级片中文字幕 |