springboot 集成oauth2

关于oauth2协议就不多说,本文使用redis存储方式没并发问题建议使用jwt,后续使用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信息,以免每次认证需要查询关系型数据库
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 会将数据先序列化成字节数组然后在存入Redis数据库 */
    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全表数据刷入Redis
     * @author: luyang
     * @create: 2020/3/21 20:22
     * @param
     * @return void
     * @throws
     */
    public void loadAllClientToCache () {

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

        // 查询数据库中Client数据信息
        List<ClientDetails> list = super.listClientDetails();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        // 将Client数据刷入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) {

        // 从数据库中读取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 {

        // 调用父类删除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 {

        // 调用父类修改方法修改数据库
        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 {

        // 调用父类修改方法修改数据库
        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);
        }

        // 已存在则转换BaseClientDetails对象
        return JSON.parseObject(clientDetail, BaseClientDetails.class);
    }
}

  • 自定义授权
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;

/**
 * 自定义授权认证
 * @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();
    }

    /**
     * 授权配置 Token存储
     * @author: luyang
     * @create: 2020/3/21 20:42
     * @param endpoints
     * @return void
     * @throws
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 用于密码授权验证
        endpoints.authenticationManager(this.authenticationManager);
        // Token 存储
        endpoints.tokenStore(tokenStore());
        // 接收GET 和 POST
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        // refreshToken是否可以重复使用 默认 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;

/**
 * 用户信息获取 校验 授权
 * @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);
    }
}
  
  • 客户端数据表
--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 '授权范围',
    `authorized_grant_types`  varchar(256)  default null comment '授权方式',
    `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地址
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,478评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,825评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,482评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,726评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,633评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,018评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,168评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,320评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,264评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,288评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,995评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,587评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,909评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,284评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,862评论 2 339

推荐阅读更多精彩内容