Spring Boot Security OAuth2 实现支持 JWT令牌的授权服务器

本文详细介绍了如何使用keytool生成JKS证书文件及导出公钥,并深入解析了OAuth2认证服务器与资源服务器的安全配置流程,包括权限注解、客户端详情服务配置、令牌服务与访问端点设置。

生成证书

(1) 生成JKS Java KeyStore文件

使用命令行工具keytool生成证书

keytool -genkeypair -alias mytest -keyalg RSA -keypass mypass -keystore mytest.jks -storepass mypass

此命令将生成一个名为mytest.jks的文件,其中包含我们的密钥(公钥和私钥)。

(2) 导出公钥

我们可以使用下面的命令从生成的JKS中导出我们的公钥:

keytool -list -rfc --keystore mytest.jks | openssl x509 -inform pem -pubkey

结果如下:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgIK2Wt4x2EtDl41C7vfp
OsMquZMyOyteO2RsVeMLF/hXIeYvicKr0SQzVkodHEBCMiGXQDz5prijTq3RHPy2
/5WJBCYq7yHgTLvspMy6sivXN7NdYE7I5pXo/KHk4nz+Fa6P3L8+L90E/3qwf6j3
DKWnAgJFRY8AbSYXt1d5ELiIG1/gEqzC0fZmNhhfrBtxwWXrlpUDT0Kfvf0QVmPR
xxCLXT+tEe1seWGEqeOLL5vXRLqmzZcBe1RZ9kQQm43+a9Qn5icSRnDfTAesQ3Cr
lAWJKl2kcWU1HwJqw+dZRSZ1X4kEXNMyzPdPBbGmU6MHdhpywI7SKZT7mX4BDnUK
eQIDAQAB
-----END PUBLIC KEY-----
-----BEGIN CERTIFICATE-----
MIIDCzCCAfOgAwIBAgIEGtZIUzANBgkqhkiG9w0BAQsFADA2MQswCQYDVQQGEwJ1
czELMAkGA1UECBMCY2ExCzAJBgNVBAcTAmxhMQ0wCwYDVQQDEwR0ZXN0MB4XDTE2
MDMxNTA4MTAzMFoXDTE2MDYxMzA4MTAzMFowNjELMAkGA1UEBhMCdXMxCzAJBgNV
BAgTAmNhMQswCQYDVQQHEwJsYTENMAsGA1UEAxMEdGVzdDCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBAICCtlreMdhLQ5eNQu736TrDKrmTMjsrXjtkbFXj
Cxf4VyHmL4nCq9EkM1ZKHRxAQjIhl0A8+aa4o06t0Rz8tv+ViQQmKu8h4Ey77KTM
urIr1zezXWBOyOaV6Pyh5OJ8/hWuj9y/Pi/dBP96sH+o9wylpwICRUWPAG0mF7dX
eRC4iBtf4BKswtH2ZjYYX6wbccFl65aVA09Cn739EFZj0ccQi10/rRHtbHlhhKnj
iy+b10S6ps2XAXtUWfZEEJuN/mvUJ+YnEkZw30wHrENwq5QFiSpdpHFlNR8CasPn
WUUmdV+JBFzTMsz3TwWxplOjB3YacsCO0imU+5l+AQ51CnkCAwEAAaMhMB8wHQYD
VR0OBBYEFOGefUBGquEX9Ujak34PyRskHk+WMA0GCSqGSIb3DQEBCwUAA4IBAQB3
1eLfNeq45yO1cXNl0C1IQLknP2WXg89AHEbKkUOA1ZKTOizNYJIHW5MYJU/zScu0
yBobhTDe5hDTsATMa9sN5CPOaLJwzpWV/ZC6WyhAWTfljzZC6d2rL3QYrSIRxmsp
/J1Vq9WkesQdShnEGy7GgRgJn4A8CKecHSzqyzXulQ7Zah6GoEUD+vjb+BheP4aN
hiYY1OuXD+HsdKeQqS+7eM5U7WW6dz2Q8mtFJ5qAxjY75T0pPrHwZMlJUhUZ+Q2V
FfweJEaoNB9w9McPe1cAiE+oeejZ0jq0el3/dJsx3rlVqZN+lMhRJJeVHFyeb3XF
lLFCUGhA7hxn2xf3x1JW
-----END CERTIFICATE-----

这里我们只需要复制公钥到资源服务的resources目录下的leesky.crt(txt yekeyi)文件中

 

认证服务器 安全相关的配置

import com.haha.xixi.service.IuserBaseService;
import org.springframework.beans.factory.annotation.Autowired;
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.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 *
 * @author admin
 * @date 2020/3/25
 * @Param 认证服务器 安全相关的配置WebSecurityConfig
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 即权限注解@PreAuthorize("hasRole('Admin')")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private IuserBaseService userServiceDetail;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userServiceDetail);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
package com.haha.xixi.config;

import com.haha.xixi.exception.CustomWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
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;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.sql.DataSource;
import java.util.Arrays;


/**
 * @author admin
 * @Date 2020/3/25
 * @description: 认证服务器 认证相关的配置Oauth2AuthorizationServerConfig
 **/
@Configuration
@EnableAuthorizationServer
public class Oauth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Value("${access.token.validity:360}") // 默认值过期时间360
    private int accessTokenValiditySeconds;

    @Value("${access.refresh.validity:420}") // 默认值7分钟
    private int refreshTokenValiditySeconds;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private CustomWebResponseExceptionTranslator customException;

    @Autowired
    private AuthenticationManager authenticationManager;//如果要使用密码授权模式 就要用到这个

    /**
     * @desc 用来配置客户端详情服务(ClientDetailsService),客户端详情信息在这里进行初始化,
     * @desc 你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
     * @desc 允许的客户端用户名和密码 参见数据表oauth_client_details
     * @desc 注意client_secret字段存储内容方式, 密码前增加:{bcrypt}
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }


    /**
     * @Auther: admin
     * @Date: 2018/10/28 17:24
     * @Description: <li>1、配置tokenStore</li>
     * <li>2、声明加密方式使用AuthenticationManager</li>
     * <li>3、用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)。</li>
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//        // 将增强的token设置到增强链中
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtTokenConverter(), customTokenEnhancer()));

        // 配置TokenServices参数
        DefaultTokenServices services = new DefaultTokenServices();
        services.setSupportRefreshToken(false);// refresh_token存放到数据表oauth_refresh_token
        services.setTokenStore(jdbcTokenStores());// 生成的token存放在数据库表oauth_access_token
        services.setTokenEnhancer(tokenEnhancerChain);
        services.setAccessTokenValiditySeconds(accessTokenValiditySeconds);//token过期时间 设置-1时,永不过期
        services.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds);

        endpoints
                .tokenServices(services)
                .exceptionTranslator(customException)
                .authenticationManager(authenticationManager);
    }


    @Bean
    protected JwtAccessTokenConverter jwtTokenConverter() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("leesky.jks"), "pwd123".toCharArray());
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("keyPair"));
        return converter;
    }

    @Bean
    public JwtEnhance customTokenEnhancer() {
        return new JwtEnhance();
    }
    @Bean
    public JdbcTokenStores jdbcTokenStores() {
        return new JdbcTokenStores(dataSource);
    }
    /**
     * @authour :admin
     * @data :2019/5/29 13:06
     * @desc://授权端点开放
     **/
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .tokenKeyAccess("permitAll()")//  开启/oauth/token_key验证端口无权限访问
                .checkTokenAccess("isAuthenticated()") // 开启/oauth/check_token验证端口认证权限访问
                .allowFormAuthenticationForClients();
    }

}

 

资源服务器

package com.haha.xixi.config;

import com.haha.xixi.exception.AuthExceptionEntryPoint;
import com.haha.xixi.exception.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * @author admin
 * @desc <li>WebSecurityConfigurerAdapter是默认情况下SpringSecurity的http配置;
 * <li>ResourceServerConfigurerAdapter是默认情况下spring security oauth 的http配置。
 */

@Configuration
@EnableResourceServer // 声明为资源服务器。此注解自动增加了 OAuth2AuthenticationProcessingFilter的过滤器链,
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级服务,支持@PreAuthorize("hasRole('Admin')")方式
public class OAuth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final TokenStore tokenStore;
    private final CustomAccessDeniedHandler customHandler;

    @Autowired
    public OAuth2ResourceServerConfiguration(TokenStore tokenStore, CustomAccessDeniedHandler customHandler) {
        this.tokenStore = tokenStore;
        this.customHandler = customHandler;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenStore(tokenStore);
        resources.authenticationEntryPoint(CustomAuthentication()).accessDeniedHandler(customHandler);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers(Global.PASS_ADDRESS).permitAll()
                .anyRequest().authenticated();

    }

    /**
     * @authour :admin
     * @data :2019/5/31 14:45
     * @desc:TODO 自定义输出 401 未授权,需要token 错误
     **/
    @Bean
    public AuthenticationEntryPoint CustomAuthentication() {
        return new AuthExceptionEntryPoint();
    }
}

具体请下载源码。。。源码下载

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丢了尾巴的猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值