1. 程式人生 > >Spring Security OAuth2 Demo —— 授權碼模式

Spring Security OAuth2 Demo —— 授權碼模式

本文可以轉載,但請註明出處https://www.cnblogs.com/hellxz/p/oauth2_oauthcode_pattern.html

寫在前邊

在文章OAuth 2.0 概念及授權流程梳理 中我們談到OAuth 2.0的概念與流程,這裡我準備分別記一記這幾種授權模式的demo,一方面為自己的最近的學習做個總結,另一方面做下知識輸出,如果文中有錯誤的地方,請評論指正,在此不勝感激

受眾前提

閱讀本文,預設讀者已經過Spring Security有一定的瞭解,對OAuth2流程有一定了解

本文目標

帶領讀者對Spring Security OAuth2框架的授權碼模式有一個比較直觀的概念,能使用框架搭建授權碼模式授權伺服器與資源伺服器(分離版本)

授權碼模式流程回顧

授權碼模式要求:使用者登入並對第三方應用(客戶端)進行授權,出示授權碼交給客戶端,客戶端憑授權碼換取access_token(訪問憑證)

此模式要求授權伺服器與使用者直接互動,在此過程中,第三方應用是無法獲取到使用者輸入的密碼等資訊的,這個模式也是OAuth 2.0中最安全的一個

Demo基本結構

這裡主要關注authorization-code-authorization-serverauthorization-code-resource-server這兩個模組

本文以及後續文章的demo均放在GitHub上,歡迎大家Star & Fork,原始碼地址:https://github.com/hellxz/spring-security-oauth2-learn

authorization-code-client-resttemplate-jdbc這個專案是用來測試非OAuth2服務使用RestTemplate與JdbcTemplate對接OAuth2授權服務的,流程這裡不講,有興趣可以debug看看,可能會讓您對整個流程會有更清晰的感受

Maven依賴

        <!--Spring Security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--Spring Boot Starter Web 所有demo均使用web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Security OAuth2 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>${spring-security-oauth2.version}</version>
        </dependency>

搭建授權伺服器(Authorization Server)

文中伺服器均使用demo級別配置,請勿直接使用到生產環境

授權伺服器結構主體如下:


啟動類自不多說,先說下SecurityConfig

package com.github.hellxz.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collections;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // @formatter: off
        auth.inMemoryAuthentication()
                .withUser("hellxz")
                .password(passwordEncoder().encode("xyz"))
                .authorities(Collections.emptyList());
        // @formatter: on
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated() //所有請求都需要通過認證
                .and()
                .httpBasic() //Basic登入
                .and()
                .csrf().disable(); //關跨域保護
    }
}

通過@Configuration@EnableWebSecurity開啟Spring Security配置,繼承WebSecurityConfigurerAdapter的方法,實現個性化配置,這裡我們使用記憶體儲存一個名為hellxz、密碼為xyz的使用者,與授權伺服器互動的使用者就是他了

除了配置使用者,我們需要對服務的資源進行保護,這裡將所有的請求都要求通過認證才可以訪問,使用者登入需要使用httpBasic形式(就是那種網頁彈個窗要求登入的那種