spring boot +spring security + oauth 2 實現 gitee授權登錄


1.前言

oauth2 是現在比較流行的授權機制,它可以不用讓用戶輸入用戶和密碼通過別的網站的授權直接登錄應用.

spring 全家桶也提供了關於oauth2的解決方案: oauth2-client 和 oauth2-resource-server.   server是服務端的用來驗證token,我們這里使用client,用來獲取token,服務端是國內的gitee.

2.實現

使用springboot引入依賴

implementation 'org.webjars:jquery:3.4.1'
implementation 'org.webjars:js-cookie:2.1.0'
implementation 'org.webjars:bootstrap:4.3.1'
implementation 'org.webjars:webjars-locator-core'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

在application.yml文件里面輸入gitee的client-id和client-secret

這個在gitee的用戶管理里面新建

 

 

 

 

spring:
  security:
    user:
      password: password
    oauth2:
      client:
        registration:
          github:
            client-id: 8800a24423a23376
            client-secret: 41aed2a18cb0094b0b1edf22e2
          gitee:
            client-id: e402cf266b38b5666992dfe99c94002a0b6b08186e
            client-secret: 4d0872ea166be4aa7f843ddb479e68d3764ff
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
            client-name: gitee
            provider: gitee
            scope:
            - user_info

authorization-grant-typ 一般是authorization_code,這個要看每個授權服務器的文檔的要求.

redirect-uri要和gitee上設置的回調地址一樣{baseUrl}就是應用的原始地址.{registrationId}就是gitee.

scope加上user_info,這樣我們就可以獲取用戶信息

 

因為oauth-client官方只提供了github和google的登錄,所以其他方式需要自己定義provider

spring:
  security:
    user:
      password: password
    oauth2:
      client:
        provider:
          gitee:
            authorization-uri: https://gitee.com/oauth/authorize
            token-uri: https://gitee.com/oauth/token            
            user-info-uri: https://gitee.com/api/v5/user
            user-name-attribute: name

authorization-uri 是gitee進行授權的地址,token-uri是用來獲取access_token的地址,user-info-uri用來獲取用戶信息,user-name-attribute獲取用戶名

定義好后添加spring security 的配置

@SpringBootApplication
@RestController
public class OauthTest3Application extends WebSecurityConfigurerAdapter {
@GetMapping("/user")
public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) {
return Collections.singletonMap("name", principal.getAttribute("name"));
}

public static void main(String[] args) {
SpringApplication.run(OauthTest3Application.class, args);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(a -> a
.antMatchers("/", "/error", "/webjars/**").permitAll()
.anyRequest().authenticated()
)

.oauth2Login();
http.logout(l -> l
.logoutSuccessUrl("/").permitAll()
)
.csrf().disable();
// @formatter:on
}
}

注意有個oauth2Login和controller

最后自己做一個登錄頁面放到resources的static文件夾下

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Demo</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
<base href="/" />
<link rel="stylesheet" type="text/css"
    href="/webjars/bootstrap/css/bootstrap.min.css" />
<script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
<script type="text/javascript"
    src="/webjars/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/webjars/js-cookie/js.cookie.js"></script>
</head>
<body>
    <h1>Demo</h1>
    <div class="container">
        <div class="container unauthenticated">
            With GitHub: <a href="/oauth2/authorization/gitee">click here</a>
        </div>
        <div class="container authenticated" style="display: none">
            Logged in as: <span id="user"></span>
        </div>
        <div class="container authenticated">
            Logged in as: <span id="user"></span>
            <div>
                <button onClick="logout()" class="btn btn-primary">Logout</button>
            </div>
        </div>
        <div id="login_container"></div>
    </div>
    <script
        src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
    <script type="text/javascript">
        $.ajaxSetup({
            beforeSend : function(xhr, settings) {
                if (settings.type == 'POST' || settings.type == 'PUT'
                        || settings.type == 'DELETE') {
                    if (!(/^http:.*/.test(settings.url) || /^https:.*/
                            .test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-XSRF-TOKEN", Cookies
                                .get('XSRF-TOKEN'));
                    }
                }
            }
        });
        $.get("/user", function(data) {
            $("#user").html(data.name);
            $(".unauthenticated").hide()
            $(".authenticated").show()
        });
        var logout = function() {
            $.post("/logout", function() {
                $("#user").html('');
                $(".unauthenticated").show();
                $(".authenticated").hide();
            })
            return true;
        }
    </script>
</body>
</html>

3.驗證

 

 

 

 

 

 

 

 

 

 

 

和我gitee賬戶定義的一個名稱沒有問題

 

 

 

目前還不知道access_token是怎么獲取的,官網文檔還不完善,有大佬知道的話可以留言指導我一下,不勝感激.

從這點來說,spring security 比 shiro 強了一點,支持 oauth 2,配合 spring boot 非常簡便.

因為使用的是框架,整個流程簡化了許多,不排除spring boot security 框架以后會發生變化,鼓勵參考官方文檔.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM