spring-securty-oauth2使用例子

源码研究入口

 

认证服务器的filter

org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter

 下发token的各个实现

org.springframework.security.oauth2.provider.endpoint.TokenEndpoint
OAuth2AuthenticationProcessingFilter org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter
resourceConfig的实现配置
org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration
security端点
org.springframework.security.web.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.引入依赖

 <!--        springSecurity-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--        Oauth2-->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.2.6.RELEASE</version>
        </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

 

posted @ 2024-04-27 15:02  意犹未尽  阅读(3)  评论(0编辑  收藏  举报