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

生成证书

(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: 
  • 1、配置tokenStore
  • *
  • 2、声明加密方式使用AuthenticationManager
  • *
  • 3、用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)。
  • */ @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 
  • WebSecurityConfigurerAdapter是默认情况下SpringSecurity的http配置; *
  • 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(); } }
  • 具体请下载源码。。。源码下载

    你可能感兴趣的:(Security,OAuth2,JWT,SpringBoot)