springboot 集成oauth2

關(guān)于oauth2協(xié)議就不多說挂疆,本文使用redis存儲方式?jīng)]并發(fā)問題建議使用jwt改览,后續(xù)使用jwt,直接上代碼


ff643052b2ee135bebae585f19b5939.png
  • 客戶端Redis緩存key
package com.luyang.service.oauth.business.constants;

/**
 * Oauth2 Redis 常量類
 * @author: luyang
 * @date: 2020-03-21 20:21
 */
public class RedisKeyConstant {

    /** Oauth2 Client */
    public static final String OAUTH_CLIENT = "oauth2:client:";
}

  • token id唯一生成
package com.luyang.service.oauth.business;

import com.luyang.framework.util.core.IdUtil;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;

/**
 * 解決同一username每次登陸access_token都相同的問題
 * @author: luyang
 * @date: 2020-03-21 20:38
 */
public class RandomAuthenticationKeyGenerator implements AuthenticationKeyGenerator {

    @Override
    public String extractKey(OAuth2Authentication authentication) {
        return IdUtil.fastUuid();
    }
}

  • Redis 管理Client信息缤言,以免每次認證需要查詢關(guān)系型數(shù)據(jù)庫
package com.luyang.service.oauth.business;

import com.alibaba.fastjson.JSON;
import com.luyang.framework.util.core.StringUtil;
import com.luyang.service.oauth.business.constants.RedisKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

/**
 * Redis 管理Client信息
 * @author: luyang
 * @date: 2020-03-21 20:17
 */
@Component
public class RedisClientDetailsService extends JdbcClientDetailsService {

    /** StringRedisTemplate 會將數(shù)據(jù)先序列化成字節(jié)數(shù)組然后在存入Redis數(shù)據(jù)庫 */
    private @Autowired StringRedisTemplate stringRedisTemplate;

    public RedisClientDetailsService(@Qualifier("hikariDataSource") DataSource dataSource) {
        super(dataSource);
    }

    /**
     * 刪除Redis Client信息
     * @author: luyang
     * @create: 2020/3/21 20:22
     * @param clientId
     * @return void
     * @throws         
     */
    private void removeRedisCache(String clientId) {
        stringRedisTemplate.boundHashOps(RedisKeyConstant.OAUTH_CLIENT).delete(clientId);
    }

    /**
     * 將Client全表數(shù)據(jù)刷入Redis
     * @author: luyang
     * @create: 2020/3/21 20:22
     * @param
     * @return void
     * @throws
     */
    public void loadAllClientToCache () {

        // 如果Redis存在則返回
        if (stringRedisTemplate.hasKey(RedisKeyConstant.OAUTH_CLIENT)) {
            return;
        }

        // 查詢數(shù)據(jù)庫中Client數(shù)據(jù)信息
        List<ClientDetails> list = super.listClientDetails();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        // 將Client數(shù)據(jù)刷入Redis
        list.parallelStream().forEach( v -> {
            stringRedisTemplate.boundHashOps(RedisKeyConstant.OAUTH_CLIENT).put(v.getClientId(), JSON.toJSONString(v));
        });
    }


    /**
     * 緩存client并返回client
     * @author: luyang
     * @create: 2020/3/21 20:22
     * @param clientId
     * @return org.springframework.security.oauth2.provider.ClientDetails
     * @throws         
     */
    private ClientDetails cacheAndGetClient (String clientId) {

        // 從數(shù)據(jù)庫中讀取Client信息
        ClientDetails clientDetails = super.loadClientByClientId(clientId);
        if (null != clientDetails) {
            stringRedisTemplate.boundHashOps(RedisKeyConstant.OAUTH_CLIENT).put(clientId, JSON.toJSONString(clientDetails));
        }

        return clientDetails;
    }


    /**
     * 刪除Client信息
     * @author: luyang
     * @create: 2020/3/21 20:23
     * @param clientId
     * @return void
     * @throws         
     */
    @Override
    public void removeClientDetails(String clientId) throws NoSuchClientException {

        // 調(diào)用父類刪除Client信息
        super.removeClientDetails(clientId);
        // 刪除緩存Client信息
        removeRedisCache(clientId);
    }


    /**
     * 修改Client 安全碼
     * @author: luyang
     * @create: 2020/3/21 20:23
     * @param clientId
     * @param secret
     * @return void
     * @throws         
     */
    @Override
    public void updateClientSecret(String clientId, String secret) throws NoSuchClientException {

        // 調(diào)用父類修改方法修改數(shù)據(jù)庫
        super.updateClientSecret(clientId, secret);
        // 重新刷新緩存
        cacheAndGetClient(clientId);
    }


    /**
     * 更新Client信息
     * @author: luyang
     * @create: 2020/3/21 20:23
     * @param clientDetails
     * @return void
     * @throws         
     */
    @Override
    public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException {

        // 調(diào)用父類修改方法修改數(shù)據(jù)庫
        super.updateClientDetails(clientDetails);
        // 重新刷新緩存
        cacheAndGetClient(clientDetails.getClientId());
    }

    /**
     * 緩存Client的Redis Key 防止Client信息意外丟失補償
     * @author: luyang
     * @create: 2020/3/21 20:24
     * @param clientId
     * @return org.springframework.security.oauth2.provider.ClientDetails
     * @throws
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {

        // 從Redis 獲取Client信息
        String clientDetail = (String) stringRedisTemplate.boundHashOps(RedisKeyConstant.OAUTH_CLIENT).get(clientId);
        // 如果為空則查詢Client信息緩存
        if (StringUtil.isBlank(clientDetail)) {
            return cacheAndGetClient(clientId);
        }

        // 已存在則轉(zhuǎn)換BaseClientDetails對象
        return JSON.parseObject(clientDetail, BaseClientDetails.class);
    }
}

  • 自定義授權(quán)
package com.luyang.service.oauth.config;

import com.luyang.service.oauth.business.RandomAuthenticationKeyGenerator;
import com.luyang.service.oauth.business.RedisClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
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.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 自定義授權(quán)認證
 * @author: luyang
 * @date: 2020-03-21 20:16
 */
@Configuration
@EnableAuthorizationServer
@DependsOn("liquibase")
public class AuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {

    /** 驗證管理器 {@link WebSecurityConfig#authenticationManager()} */
    private @Autowired AuthenticationManager authenticationManager;

    /** Client 信息 */
    private @Autowired RedisClientDetailsService redisClientDetailsService;

    /** Redis 連接工廠 */
    private @Autowired RedisConnectionFactory redisConnectionFactory;

    /**
     * Redis 存儲Token令牌
     * @author: luyang
     * @create: 2020/3/21 20:40
     * @param 
     * @return org.springframework.security.oauth2.provider.token.TokenStore
     * @throws         
     */
    public @Bean TokenStore tokenStore () {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setAuthenticationKeyGenerator(new RandomAuthenticationKeyGenerator());
        return redisTokenStore;
    }

    /**
     * 客戶端配置
     * @author: luyang
     * @create: 2020/3/21 20:44
     * @param clients
     * @return void
     * @throws         
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(redisClientDetailsService);
        redisClientDetailsService.loadAllClientToCache();
    }

    /**
     * 授權(quán)配置 Token存儲
     * @author: luyang
     * @create: 2020/3/21 20:42
     * @param endpoints
     * @return void
     * @throws
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 用于密碼授權(quán)驗證
        endpoints.authenticationManager(this.authenticationManager);
        // Token 存儲
        endpoints.tokenStore(tokenStore());
        // 接收GET 和 POST
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        // refreshToken是否可以重復(fù)使用 默認 true
        endpoints.reuseRefreshTokens(false);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允許表單認證
        security.allowFormAuthenticationForClients();
    }
}

  • 密碼校驗器
package com.luyang.service.oauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 密碼校驗器
 * @author: luyang
 * @date: 2020-03-21 20:27
 */
@Configuration
public class PasswordEncoderConfig {

    public @Bean BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

  • Oauth2 安全配置
package com.luyang.service.oauth.config;

import com.luyang.service.oauth.service.impl.DomainUserDetailsServiceImpl;
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.builders.HttpSecurity;
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;

/**
 * Oauth2 安全配置
 * @author: luyang
 * @date: 2020-03-21 20:26
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    /** 用戶信息 */
    private @Autowired DomainUserDetailsServiceImpl userDetailsService;

    /** 密碼校驗器 */
    private @Autowired BCryptPasswordEncoder passwordEncoder;

    /**
     * 用戶配置
     * @author: luyang
     * @create: 2020/3/21 20:29
     * @param auth
     * @return void
     * @throws         
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.userDetailsService).passwordEncoder(this.passwordEncoder);
    }


    /**
     * 認證管理器
     * @author: luyang
     * @create: 2020/3/21 20:30
     * @param 
     * @return org.springframework.security.authentication.AuthenticationManager
     * @throws         
     */
    @Override
    public @Bean AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * http安全配置
     * @author: luyang
     * @create: 2020/3/21 20:45
     * @param http
     * @return void
     * @throws
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .anyRequest().authenticated().and()
                .httpBasic().and().csrf().disable();
    }
}

  • 用戶信息獲取
package com.luyang.service.oauth.service.impl;

import com.luyang.framework.util.core.StringUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;

/**
 * 用戶信息獲取 校驗 授權(quán)
 * @author: luyang
 * @date: 2020-03-21 20:28
 */
@Service
public class DomainUserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StringUtil.isEmpty(username)) {
            throw new UsernameNotFoundException("用戶不存在");
        }

        Collection<GrantedAuthority> collection = new HashSet<>();
        return new User("admin", "$2a$10$KCokILJ9PwNq6T8RIB9uiu/5CKS25LbgN3Rt9pmgsrBkrj.pPbP1a", collection);
    }
}
  
  • 客戶端數(shù)據(jù)表
--liquibase formatted sql

--changeset LU YANG:1576570763558
drop table if exists `oauth_client_details`;
create table `oauth_client_details`
(
    `client_id`               varchar(128) not null comment '客戶端標識',
    `resource_ids`            varchar(256)  default null,
    `client_secret`           varchar(256)  default null comment '客戶端安全碼',
    `scope`                   varchar(256)  default null comment '授權(quán)范圍',
    `authorized_grant_types`  varchar(256)  default null comment '授權(quán)方式',
    `web_server_redirect_uri` varchar(256)  default null,
    `authorities`             varchar(256)  default null,
    `access_token_validity`   int(11)       default null comment 'access_token有效期 (單位:min)',
    `refresh_token_validity`  int(11)       default null comment 'refresh_token有效期(單位:min)',
    `additional_information`  varchar(4096) default null,
    `autoapprove`             varchar(256)  default null,
    primary key (`client_id`)
) engine = innodb
  default charset = utf8mb4 comment ='客戶端信息表';

insert into `oauth_client_details` (client_id, client_secret, scope, authorized_grant_types, access_token_validity)
values ('PC', '$2a$10$buSwJ4/J6sJ8XhnZU3MOsOE/jOJQpbHeULbYVAyXBoeMsSqV8wgqy', 'WEB', 'authorization_code,password,refresh_token', 28800);
  • 客戶端表生成依靠liquibase 則自定義認證類的時候需要注意注入先后順序
    gitee地址
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宝当,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子胆萧,更是在濱河造成了極大的恐慌今妄,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鸳碧,死亡現(xiàn)場離奇詭異盾鳞,居然都是意外死亡,警方通過查閱死者的電腦和手機瞻离,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進店門腾仅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人套利,你說我怎么就攤上這事推励。” “怎么了肉迫?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵验辞,是天一觀的道長。 經(jīng)常有香客問我喊衫,道長跌造,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任族购,我火速辦了婚禮壳贪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘寝杖。我一直安慰自己违施,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布瑟幕。 她就那樣靜靜地躺著磕蒲,像睡著了一般留潦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上辣往,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天愤兵,我揣著相機與錄音,去河邊找鬼排吴。 笑死秆乳,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的钻哩。 我是一名探鬼主播屹堰,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼街氢!你這毒婦竟也來了扯键?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤珊肃,失蹤者是張志新(化名)和其女友劉穎荣刑,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體伦乔,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡厉亏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了烈和。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片爱只。...
    茶點故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖招刹,靈堂內(nèi)的尸體忽然破棺而出恬试,到底是詐尸還是另有隱情,我是刑警寧澤疯暑,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布训柴,位于F島的核電站,受9級特大地震影響妇拯,放射性物質(zhì)發(fā)生泄漏幻馁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一乖阵、第九天 我趴在偏房一處隱蔽的房頂上張望宣赔。 院中可真熱鬧,春花似錦瞪浸、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽钩蚊。三九已至,卻和暖如春蹈矮,著一層夾襖步出監(jiān)牢的瞬間砰逻,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工泛鸟, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蝠咆,地道東北人。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓北滥,卻偏偏與公主長得像刚操,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子再芋,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容