springsecurity04-springsecurity oauth2實現單點登錄之-github客戶端模擬

申請github oauth應用

地址:springsecurity04-springsecurity oauth2實現單點登錄之-github客戶端模擬
在這裏插入圖片描述
點擊註冊成功後,可以獲取到對應客戶端id和客戶端密鑰
在這裏插入圖片描述

測試github路徑

獲取授權碼

使用之前獲取授權碼的路徑測試
https://github.com/login/oauth/authorize?client_id=你的客戶端id&response_type=code&redirect_uri=http://localhost:8886/callback 彈出授權頁即正常
如果你的redirect_uri和註冊的不一致,會拋出

http://localhost:8886/callback?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-authorization-request-errors%2F%23redirect-uri-mismatch

獲取token

使用client_id、client_secret和code這三個參數獲取用戶的access_token,即用戶身份標識
https://github.com/login/oauth/access_token?client_id=xxxxxxxxxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxxx&code=xxxxxxxxxxxxxxxxxxx

https://github.com/login/oauth/access_token?client_id=xxxxxxxxxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxxx&code=xxxxxxxxxxxxxxxxxxx&redirect_uri=http://localhost:8080/login

讀取github資源

使用access_token獲取用戶信息
https://api.github.com/user?access_token=xxxxxxxxxxxxxxxxx

springboot單點登錄github

登錄github操作參考官方文檔 https://docs.spring.io/spring-boot/docs/2.0.8.RELEASE/reference/htmlsingle/#boot-features-security-oauth2-client
添加客戶端依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-oauth2-client -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </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>nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.6.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

thymeleaf-extras-springsecurity4

其中 thymeleaf-extras-springsecurity4 用於在模板中判斷是否授權或者獲取資源信息
具體關於thymeleaf和springsecurity參考官網https://www.thymeleaf.org/doc/articles/springsecurity.html
簡單介紹一下:

  • sec:authorize用戶判斷用戶授權信息
  • sec:authentication 用於打印用戶授權信息
    打印信息
    內置對象principal表示OAuth2Authentication對象(表示oauth認證過的用戶信息【包含用戶名,用戶detail詳細信息,圖片啊等】)
    principal中還有一個 principal 是OAuth2User其中的getAttributes存放着github上所有的個人信息
<div sec:authorize="isAuthenticated()"> 
  This content is only shown to authenticated users.
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
  This content is only shown to administrators.
</div>
<div sec:authorize="hasRole('ROLE_USER')">
  This content is only shown to users.
</div>
The sec:authentication attribute is used to print logged user name and roles:

Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>

客戶端具體配置

application.properties配置

spring.security.oauth2.client.registration是自定義客戶端的前綴
my-client-1名字可以隨意
1. client-id:表示客戶端編號,github上申請了就可以看到
2. client-secret:客戶端密鑰,github上申請了就拷貝過來
3. client-name:一般設置是登陸頁顯示的名字,可以隨便取,是個客戶端的標識label
4. provider:表示下面定義的provider相關的認證服務器,資源服務器的路徑
5. scope:表示服務器運行你訪問的範圍
6. redirect-uri-template:你定義在github服務器上的Authorization callback URL,必須一致否則報錯
7. client-authentication-method:客戶端認證方式
8. authorization-grant-type:授權方式,一般就使用授權碼模式
spring.security.oauth2.client.provider表示授權服務器和資源服務器提供商
my-oauth-provider就是上面指定提供商的名字

  1. authorization-uri表示授權登錄的url,自動跳轉到回調地址參數返回code=授權碼
  2. token-uri 表示通過授權碼token
  3. user-info-uri 表示獲取用戶信息的地址
  4. user-name-attribute表示通過user-info-uri獲取鍵值對map中用戶名對應屬性
    在這裏插入圖片描述
    這些屬性中 id表示你在github上的id,avatar_url表示你上傳到github上的圖像,具體參考github官網
spring.security.oauth2.client.registration.my-client-1.client-id=9b408a36daab230c563e
spring.security.oauth2.client.registration.my-client-1.client-secret=cacd3593a1a9c7c840e03e03da38490759b5e960
spring.security.oauth2.client.registration.my-client-1.client-name=my-client-1
spring.security.oauth2.client.registration.my-client-1.provider=my-oauth-provider
spring.security.oauth2.client.registration.my-client-1.scope=all
spring.security.oauth2.client.registration.my-client-1.redirect-uri-template=http://localhost:8886/callback
spring.security.oauth2.client.registration.my-client-1.client-authentication-method=basic
spring.security.oauth2.client.registration.my-client-1.authorization-grant-type=authorization_code

spring.security.oauth2.client.provider.my-oauth-provider.authorization-uri=https://github.com/login/oauth/authorize
spring.security.oauth2.client.provider.my-oauth-provider.token-uri=https://github.com/login/oauth/access_token
spring.security.oauth2.client.provider.my-oauth-provider.user-info-uri=https://api.github.com/user
spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=name
server.port=8886
spring.thymeleaf.cache=false
spring.thymeleaf.mode=LEGACYHTML5
debug=false

添加控制層index跳轉到index模板

/**
 * @author 廖敏
 * 創建日期 2019-03-12 16:03
 **/
@Controller
public class TestController {
    @GetMapping("/index")
    public String index(Principal principal, Model model) {
        if(principal == null ){
            return "index";
        }
        System.out.println(principal.toString());
        model.addAttribute("principal", principal);
        return "index";
    }
}

添加index.html模板

<body>
<div class="container">
    <div class="mt-3">
        <h2>Hello Spring Security</h2>
    </div>
    <div sec:authorize="isAuthenticated()" th:if="${principal}" th:object="${principal}">
        <p>已有用戶登錄</p>
        <p>登錄的用戶爲: <span sec:authentication="name"></span></p>
        <p>用戶權限爲: <span th:text="*{authorities}"></span></p>
        <p>用戶頭像爲: <img alt="" class="avatar width-full rounded-2" height="230" th:src="*{principal.getAttributes().avatar_url}" width="230"></p>

    </div>
    <div sec:authorize="isAnonymous()">
        <p>未有用戶登錄</p>
    </div>
</div>
</body>

添加權限配置類

/*
  任何註解都不需要只需要權限的註解EnableWebSecurity
*/
@EnableWebSecurity
@Configuration
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .redirectionEndpoint()
                .baseUri("/callback");//注意一定要是回調地址,不加模板只攔截/login/oauth2/code/*
    }

}

添加啓動main

@SpringBootApplication
public class Client1Main {
    public static void main(String[] args) {
        SpringApplication.run(Client1Main.class);
    }
}

啓動 訪問 http://localhost:8886/index,返現跳轉到一個頁面,上面有個鏈接顯示配置客戶端名稱
spring.security.oauth2.client.registration.my-client-1.client-name=my-client-1
cookie是一般的session
在這裏插入圖片描述
查看源代碼

<a href="/oauth2/authorization/my-client-1">my-client-1</a>

說明/oauth2/authorization/你的名稱 會自動過濾去判斷是否github授權
點擊 my-client-1鏈接(目前未登錄github),自動跳轉到github上
在這裏插入圖片描述
輸入用戶名和密碼,此時自動跳轉回 index頁面 此時就可以顯示用戶名等信息(圖片偶爾顯示不出來【牆】)
在這裏插入圖片描述
此時多了github的cookie信息
github登錄的信息和當前session綁定一起,,之後在訪問index或者其他頁面,就無需登錄了【除非清空緩存】
補一張正確顯示圖片的效果(我沒有修改github上圖片)
在這裏插入圖片描述

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