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 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 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地址

你可能感兴趣的:(springboot 集成oauth2)