本教程是在oauth2-实现单点登录(一)最简示例的基础上进行修改了。
目标:将配置数据持久化到数据库,缓存token到redis。
一、接入mysql数据库
1. 创建数据库
- 创数据库oauth2,字符集utf8mb4,
- 执行数据库脚本:mysql脚本
2.引入依赖
加入mysql、mybatis、lombok(需要idea加入插件,不然会显示错误,不影响编译;如不需要,可以不引入再手动去实体类下 创建get/set)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
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/*Mapper.xml
4.创建模块
创建用户模块以及权限模块
就正常的三层架构:详细见文件夹下:mapper、模块
值得注意的是要创建一个查询用户方法
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Autowired
private PermissionService permissionService;
/**
* 查询数据库用户信息
*
* @param username 登录账户
* @return
* @throws UsernameNotFoundException
*/
@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<GrantedAuthority> authorities = new ArrayList<>();
//获取用户权限
List<PermissionDO> 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;
/**
* 配置用户登录验证服务
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
5.修改AuthConfig
// 开启认证服务
@Configuration
@EnableAuthorizationServer
public class AuthConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
public DataSource dataSource;
/**
* 放开token和checkToken 拦截
* @param oauthServer
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
}
@Bean
public TokenStore tokenStore() {
// 数据库存储key
return new JdbcTokenStore(dataSource);
}
/**
* 必须注入,验证密码需要使用
*
* @return
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public ClientDetailsService jdbcClientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
@Bean
public AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
/**
* 配置客户端
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(jdbcClientDetailsService());
}
/**
* 配置token和授权码存储
*
* @param endpoints
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore())
.authorizationCodeServices(authorizationCodeServices());
}
}
到此,已经完成用户数据、配置数据、token数据持久化到数据库;
这里有个点,多个应用共用一个clientId,才能实现单点登录,多个重定向地址在数据库是用“,”分隔的。
二、接入redis
1.加入依赖
<!-- redis依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
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