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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容