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: <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();
    }
}

具體請下載源碼。。。源碼下載

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