使用Spring Security Oauth2實現第三方登錄認證

   最近接手一個需求,在已有的登錄系統下,爲第三方平臺提供一個登錄認證功能。這裏涉及的協議是OAuth2,關於該協議的具體內容不是本文講述的主要內容,具體可以參考如下鏈接:
   Oauth2協議相關:
   http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
   https://github.com/jeansfish/RFC6749.zh-cn/blob/master/SUMMARY.md
    Spring Security Oauth2框架相關:
    https://docs.spring.io/spring-security-oauth2-boot/docs/current-SNAPSHOT/reference/htmlsingle/#oauth2-boot-authorization-server-authentication-manager

本文分爲兩部分,第一部分介紹如何搭建一個認證授權的服務器,第二部分將從Spring Security Oauth2框架源碼出發,簡單分析其工作流程及原理,最後分享幾個我在完成這個項目過程中踩過的坑。廢話少說,我們一起來看第一部分。

Part One : 快速搭建認證授權服務器

技術選型:Spring Boot 、Spring Security Oauth2、thymeleaf、Mybatis....
這裏簡單闡述下爲什麼選擇Spring Security Oauth2框架:Oauth2實際上是一個關於授權(authorization)的開放網絡標準,它僅僅是定義了一些列的規範、認證的交互流程,而不涉及任何具體的實現細節。因此若想要基於Oauth2協議實現認證授權功能,你可能會面臨這些問題:授權碼如何生成?令牌如何存儲?令牌時效如何設定等等,諸如這些問題,若手動實現Oauth2協議,你可能會被淹沒在大量的細節實現上,而無暇顧及核心的業務需求。Spring Security Oauth2本身已經提供Oauth2協議的實現,且依賴Spring、Spring Security的強大後臺,能夠更好的兼容整合項目。
  1. 引入主要的依賴:
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/>
    </parent>
     <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.3.RELEASE</version>
      </dependency>
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

Part Two:流程分析&源碼解析

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章