spring-securty-oauth2使用例子

源碼研究入口

security端點
FilterChainProxy
自動註冊類
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration
斷點入口
org.springframework.security.oauth2.provider.endpoint.TokenEndpoint

--git地址
https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql

 

oauth2概念

https://www.cnblogs.com/LQBlog/p/16996125.html

環境搭建

1.引入依賴

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

 

憑證模式

package com.yxt.datax.auth;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/*
[/oauth/authorize]
[/oauth/token]
[/oauth/check_token]
[/oauth/confirm_access]
[/oauth/token_key]
[/oauth/error]
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final BCryptPasswordEncoder passwordEncoder= new BCryptPasswordEncoder();
    /**
     * :用來配置客戶端詳情信息,一般使用數據庫來存儲或讀取應用配置的詳情信息(client_id ,client_secret,redirect_uri 等配置信息)。
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
        //基於內存模式定義一個oauth2客戶端
        clients.inMemory()
                .withClient("client_1") //客戶端id
                .authorizedGrantTypes("client_credentials")//oatuh2 憑證模式
                .scopes("all","read", "write")
                .authorities("client_credentials")//oatuh2 憑證模式
                .accessTokenValiditySeconds(7200)//token有效期
                 //使用passwordEncoder對密碼進行加密,正常是存在數據庫裏面
                .secret(passwordEncoder.encode("123456"));//客戶端secret
    }

    /**
     * 用來配置令牌端點(Token Endpoint)的安全與權限訪問。
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
        //後續根據用戶輸入的密碼來做encode後做比較
        security.passwordEncoder(passwordEncoder);
    }

    /**
     * 用來配置授權以及令牌(Token)的訪問端點和令牌服務(比如:配置令牌的簽名與存儲方式)
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
    }
}

posman調用

crul

curl --location 'http://localhost:8080/oauth/token' \
--header 'Authorization: Basic Y2xpZW50XzE6MTIzNDU2' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: JSESSIONID=E1211820CB66DAA0880897446BEEB01A' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'scope=read'
View Code

 

密碼模式 

密碼模式可以理解爲需要用戶進行輸入賬號密碼獲取token信息,所以需要接入spring security 登錄流程

1.接入web登錄方式

package com.yxt.datax.auth;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class DataWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    private final BCryptPasswordEncoder passwordEncoder= new BCryptPasswordEncoder();
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         *  inMemoryAuthentication 開啓在內存中定義用戶
         *  多個用戶通過and隔開
         */
        auth.inMemoryAuthentication()
                .withUser("liqiang").password(passwordEncoder.encode("123456")).roles("admin")
                .and()
                .withUser("admin").password("admin").roles("admin").and().passwordEncoder(passwordEncoder);
    }

    /**
     * 獲取web 登錄的AuthenticationManager,登錄流程就是走的這裏
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

 

2.oauthserver修改

package com.yxt.datax.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/*
[/oauth/authorize]
[/oauth/token]
[/oauth/check_token]
[/oauth/confirm_access]
[/oauth/token_key]
[/oauth/error]
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final BCryptPasswordEncoder passwordEncoder= new BCryptPasswordEncoder();


     @Autowired
     private AuthenticationManager authenticationManager;
     @Autowired
     private UserDetailsService userDetailsService;
    /**
     * :用來配置客戶端詳情信息,一般使用數據庫來存儲或讀取應用配置的詳情信息(client_id ,client_secret,redirect_uri 等配置信息)。
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
        //基於內存模式定義一個oauth2客戶端
        clients.inMemory()
                .withClient("client_1") //客戶端id
                .authorizedGrantTypes("client_credentials")//支持什麼模式換取token 可設置多個
                .scopes("all","read", "write")
                .authorities("client_credentials")//oatuh2 憑證模式 可設置多個
                .accessTokenValiditySeconds(7200)//token有效期
                 //使用passwordEncoder對密碼進行加密,正常是存在數據庫裏面
                .secret(passwordEncoder.encode("123456"))//客戶端secret

                 //密碼模式
                .and().withClient("client_2")
                .authorizedGrantTypes("password", "refresh_token") //密碼模式,同時支持refresh_token刷新token
                .scopes("all","read", "write")
                .accessTokenValiditySeconds(7200)
                .refreshTokenValiditySeconds(10000)
                .authorities("password")
                .secret(passwordEncoder.encode("123456"));
    }

    /**
     * 用來配置令牌端點(Token Endpoint)的安全與權限訪問。
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
        //後續根據用戶輸入的密碼來做encode後做比較
        security.passwordEncoder(passwordEncoder).tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    /**
     * 用來配置授權以及令牌(Token)的訪問端點和令牌服務(比如:配置令牌的簽名與存儲方式)
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
        //密碼模式需要配置這個,因爲是用戶通過賬號密碼走登錄邏輯判斷是否下發token
        endpoints.authenticationManager(authenticationManager)
                //refresh_token 需要獲取用戶信息
                .userDetailsService(userDetailsService);
    }
}

 

oauth2配置修改

package com.yxt.datax.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/*
[/oauth/authorize]
[/oauth/token]
[/oauth/check_token]
[/oauth/confirm_access]
[/oauth/token_key]
[/oauth/error]
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final BCryptPasswordEncoder passwordEncoder= new BCryptPasswordEncoder();


     @Autowired
     private AuthenticationManager authenticationManager;
     @Autowired
     private UserDetailsService userDetailsService;
    /**
     * :用來配置客戶端詳情信息,一般使用數據庫來存儲或讀取應用配置的詳情信息(client_id ,client_secret,redirect_uri 等配置信息)。
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
        //基於內存模式定義一個oauth2客戶端
        clients.inMemory()
                .withClient("client_1") //客戶端id
                .authorizedGrantTypes("client_credentials")//支持什麼模式換取token 可設置多個
                .scopes("all","read", "write")
                .authorities("client_credentials")//oatuh2 憑證模式 可設置多個
                .accessTokenValiditySeconds(7200)//token有效期
                 //使用passwordEncoder對密碼進行加密,正常是存在數據庫裏面
                .secret(passwordEncoder.encode("123456"))//客戶端secret

                 //密碼模式
                .and().withClient("client_2")
                .authorizedGrantTypes("password", "refresh_token") //密碼模式,同時支持refresh_token刷新token
                .scopes("all","read", "write")
                .accessTokenValiditySeconds(7200)
                .refreshTokenValiditySeconds(10000)
                .authorities("password")
                .secret(passwordEncoder.encode("123456"));
    }

    /**
     * 用來配置令牌端點(Token Endpoint)的安全與權限訪問。
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
        //後續根據用戶輸入的密碼來做encode後做比較
        security.passwordEncoder(passwordEncoder).tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    /**
     * 用來配置授權以及令牌(Token)的訪問端點和令牌服務(比如:配置令牌的簽名與存儲方式)
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
        //密碼模式需要配置這個,因爲是用戶通過賬號密碼走登錄邏輯判斷是否下發token
        endpoints.authenticationManager(authenticationManager)
                //refresh_token 需要獲取用戶信息
                .userDetailsService(userDetailsService);
    }
}

1.獲取token

curl

curl --location --request POST 'http://localhost:8080/oauth/token?grant_type=password&client_id=client_2&client_secret=123456&username=liqiang&password=123456' \
--header 'Cookie: JSESSIONID=A120BD04654503D212BF08FE74E43170'
View Code

 

2.刷新token

curl

curl --location --request POST 'http://localhost:8080/oauth/token?grant_type=refresh_token&client_id=client_2&client_secret=123456&refresh_token=4d4354b4-56b3-493e-875d-d180d4e3e236' \
--header 'Cookie: JSESSIONID=21B0171EF2A8DDFD0B084A7A3FAE1C2C; JSESSIONID=D4FD201B53490E10E11A0515350CE972'
View Code

 

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