栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

oauth2-实现单点登录(二)数据持久化

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

oauth2-实现单点登录(二)数据持久化

本教程是在oauth2-实现单点登录(一)最简示例的基础上进行修改了。

目标:将配置数据持久化到数据库,缓存token到redis。

一、接入mysql数据库 1. 创建数据库
  1. 创数据库oauth2,字符集utf8mb4,
  2. 执行数据库脚本:mysql脚本
2.引入依赖

加入mysql、mybatis、lombok(需要idea加入插件,不然会显示错误,不影响编译;如不需要,可以不引入再手动去实体类下 创建get/set)

        
            mysql
            mysql-connector-java
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.1
        
        
            org.projectlombok
            lombok
            true
        
3. 配置文件加入配置
#配置mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/oauth2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=

#配置mybatis
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath:mapper
   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       UserDO tbUser = userService.getUserByUsername(username);
       //验证账户为username的用户是否存在
       if (null == tbUser){
           throw new UsernameNotFoundException("username:  " + username + "is not exist!");
       }

       List authorities = new ArrayList<>();
       //获取用户权限
       List permissions = permissionService.getByUserid(tbUser.getId());
       //设置用户权限
       permissions.forEach(permission -> {
           authorities.add(new SimpleGrantedAuthority(permission.getEname()));
       });

       //返回认证用户
       return new User(tbUser.getUsername(), tbUser.getPassword(), authorities);
   }
}
4. 修改WebSecurityConfig

将原来写死的两个用户,改为查询数据库数据。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

}
5.修改AuthConfig
// 开启认证服务
@Configuration
@EnableAuthorizationServer
public class AuthConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    public DataSource dataSource;

    
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }


    @Bean
    public TokenStore tokenStore() {
        // 数据库存储key
         return new JdbcTokenStore(dataSource);
    }

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

    @Bean
    public ClientDetailsService jdbcClientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }


    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(jdbcClientDetailsService());
    }

    
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore())
                .authorizationCodeServices(authorizationCodeServices());
    }
}

到此,已经完成用户数据、配置数据、token数据持久化到数据库;
这里有个点,多个应用共用一个clientId,才能实现单点登录,多个重定向地址在数据库是用“,”分隔的。

二、接入redis 1.加入依赖
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
2.配置redis
#配置redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=xxxxxx
3.修改AuthConfig
    @Autowired
    private RedisConnectionFactory connectionFactory;
	
	~~~~~
	
	@Bean
    public TokenStore tokenStore() {
        // 数据库存储key
        // return new JdbcTokenStore(dataSource);
        // redis存储key
        return new RedisTokenStore(connectionFactory);
    }
4.验证


代码见f_02_data分支:f_02_data
END

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351164.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号