概述
SpringBoot版本为 2.0.6.RELEASE;
数据库使用的是MySQL;
配置Spring Security OAuth2大概可以分为4各部分:
- 实现UserDetailsService;
- 配置安全配置(继承WebSecurityConfigurerAdapter)
- 配置认证服务器(继承AuthorizationServerConfigurerAdapter)
- 配置资源服务器(继承ResourceServerConfigurerAdapter)
本文主要讲述配置以上4个方面,其实如果你是基于RBAC角色管理或者其他的,仍需要另外的配置UserDetails(USER实体类去实现)等等。配置上有不懂的地方可以先查看注解以及代码块下有备注,因为是公司项目最近自己搭建的安全框架,配置UserDetails和权限这种就不另外发布了。
pom.xml
添加依赖(部分包看自己情况选择)
com.google.code.gson
gson
2.8.2
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-lang3
3.6
mysql
mysql-connector-java
5.1.47
org.projectlombok
lombok
1.16.8
provided
org.apache.poi
poi
3.14
org.apache.poi
poi-ooxml
3.14
org.apache.httpcomponents
httpclient
4.5
org.apache.httpcomponents
httpmime
4.5
org.springframework.boot
spring-boot-devtools
true
org.springframework.boot
spring-boot-starter-actuator
commons-io
commons-io
2.4
com.alibaba
fastjson
1.2.37
org.springframework.boot
spring-boot-starter-quartz
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-starter-amqp
org.springframework.boot
spring-boot-starter-reactor-netty
com.vaadin.external.google
android-json
0.0.20131108.vaadin1
compile
org.apache.commons
commons-math
2.2
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.security
spring-security-test
test
org.springframework.boot
spring-boot-starter-security
org.springframework.security.oauth
spring-security-oauth2
2.3.4.RELEASE
org.junit.jupiter
junit-jupiter
5.5.2
test
org.junit.jupiter
junit-jupiter-api
5.5.2
org.junit.jupiter
junit-jupiter-engine
5.5.2
org.assertj
assertj-core
org.springframework.boot
spring-boot-test
org.springframework
spring-test
实现UserDetailsService
/**
* @author lewis
* @date 2019/12/23 14:24
*/
public class UserDetailsServiceImpl implements UserDetailsService {
private final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
List userList = userRepository.findByLoginNo(s);
if (userList != null && userList.size() != 0){
User user = userList.get(0);
logger.info("账号loginNo:" + user.getLoginNo() +"," + user.getPassword());
Collection collection = new HashSet<>();
List roles = roleRepository.findByUser(user.getId());
if (roles != null && roles.size() != 0){
Iterator iterator = roles.iterator();
while (iterator.hasNext()){
collection.add(new SimpleGrantedAuthority(iterator.next().getName()));
}
}
return new org.springframework.security.core.userdetails.User(user.getLoginNo(),user.getPassword(),user.isEnabled(),
user.isAccountNonExpired(),user.isCredentialsNonExpired(),
user.isAccountNonLocked(),collection);
}
throw new UsernameNotFoundException("没有这个用户");
}
}
备注:user实体类要先实现UserDetails,看自己情况配置。但是user.isEnabled(),user.isAccountNonExpired(),user.isCredentialsNonExpired(),user.isAccountNonLocked()这几项属性一般都为true。
配置安全配置(继承WebSecurityConfigurerAdapter)
/**
* @author lewis
* @date 2019/12/23 14:24
*/
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
private final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
@Bean
@Override
public UserDetailsService userDetailsService(){
return new UserDetailsServiceImpl();
}
@Bean
public PasswordEncoder passwordEncoder() {
// 加密方式
return new BCryptPasswordEncoder();
}
@Autowired
protected void globalUserDetails(AuthenticationManagerBuilder auth)throws Exception{
auth
.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
/*
spring security 先通过ResourceSecurityConfiguration的配置先执行
,再执行webSecurityConfiguration的配置,所以要规划好不同断点对应的过滤链不冲突,需要清晰规划好。
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
logger.info("web_security");
// 配置开放与限制的断点有顺序之分,顺序错了,某些版本可能用不了
http
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/oauth/**",
"/v1.1/**",
"/v1.0/**",
"/open/**") //
.permitAll()// 在webSecurityConfiguration都不需要web的认证
.and()
.authorizeRequests()
.anyRequest().authenticated()//除了上面的,任何请求都要认证
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable()
.sessionManagement().maximumSessions(1);// 最大会话数设置
}
/**
* 给认证服务器使用
* @return
* @throws Exception
*/
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
配置认证服务器(继承AuthorizationServerConfigurerAdapter)
/**
* @author lewis
* @date 2019/12/23 14:24
*/
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter{
@Resource(description = "dataSource")
private DataSource dataSource;
/*
管理access_token的发放
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// 存数据库
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager()).approvalStore(approvalStore())
.userDetailsService(userDetailsService())
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST) ;
// 配置tokenServices参数
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(endpoints.getTokenStore());
tokenServices.setSupportRefreshToken(true);//可以使用refresh_token
tokenServices.setReuseRefreshToken(false);// 刷新token后,不复用refresh_token
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
tokenServices.setAccessTokenValiditySeconds(accessTokenValiditySecond); // 30天
tokenServices.setRefreshTokenValiditySeconds(refreshTokenValiditySecond);
endpoints.tokenServices(tokenServices);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.allowFormAuthenticationForClients()
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(passwordEncoder());
}
@Bean
public TokenStore tokenStore() {
//token保存在内存中(也可以保存在数据库、Redis中)。
//如果保存在中间件(数据库、Redis),那么资源服务器与认证服务器可以不在同一个工程中。
//注意:如果不保存access_token,则没法通过access_token取得用户信息
// return new InMemoryTokenStore();
return new JdbcTokenStore(dataSource); /// 使用Jdbctoken store
}
@Bean // 声明 ClientDetails实现
public ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
@Bean
public ApprovalStore approvalStore() throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
// 设置添加用户信息,正常应该从数据库中读取
@Bean
UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl();
}
@Bean
PasswordEncoder passwordEncoder() {
// 加密方式
return new BCryptPasswordEncoder();
}
@Bean
AuthenticationManager authenticationManager() {
AuthenticationManager authenticationManager = new AuthenticationManager() {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return daoAuhthenticationProvider().authenticate(authentication);
}
};
return authenticationManager;
}
@Bean
public AuthenticationProvider daoAuhthenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService());
daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
}
备注:配置完认证服务器,需要在数据库创建几个表,如下:
CREATE TABLE `clientdetails` (
`appId` varchar(128) NOT NULL,
`resourceIds` varchar(256) DEFAULT NULL,
`appSecret` varchar(256) DEFAULT NULL,
`scope` varchar(256) DEFAULT NULL,
`grantTypes` varchar(256) DEFAULT NULL,
`redirectUrl` varchar(256) DEFAULT NULL,
`authorities` varchar(256) DEFAULT NULL,
`access_token_validity` int(11) DEFAULT NULL,
`refresh_token_validity` int(11) DEFAULT NULL,
`additionalInformation` varchar(4096) DEFAULT NULL,
`autoApproveScopes` varchar(256) DEFAULT NULL,
PRIMARY KEY (`appId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_access_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication_id` varchar(128) NOT NULL,
`user_name` varchar(256) DEFAULT NULL,
`client_id` varchar(256) DEFAULT NULL,
`authentication` blob,
`refresh_token` varchar(256) DEFAULT NULL,
PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_approvals` (
`userId` varchar(256) DEFAULT NULL,
`clientId` varchar(256) DEFAULT NULL,
`scope` varchar(256) DEFAULT NULL,
`status` varchar(10) DEFAULT NULL,
`expiresAt` timestamp NULL DEFAULT NULL,
`lastModifiedAt` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_client_details` (
`client_id` varchar(128) NOT NULL,
`resource_ids` varchar(256) DEFAULT NULL,
`client_secret` varchar(256) DEFAULT NULL,
`scope` varchar(256) DEFAULT NULL,
`authorized_grant_types` varchar(256) DEFAULT NULL,
`web_server_redirect_uri` varchar(256) DEFAULT NULL,
`authorities` varchar(256) DEFAULT NULL,
`access_token_validity` int(11) DEFAULT NULL,
`refresh_token_validity` int(11) DEFAULT NULL,
`additional_information` varchar(4096) DEFAULT NULL,
`autoapprove` varchar(256) DEFAULT NULL,
PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_client_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication_id` varchar(128) NOT NULL,
`user_name` varchar(256) DEFAULT NULL,
`client_id` varchar(256) DEFAULT NULL,
PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_code` (
`code` varchar(256) DEFAULT NULL,
`authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_refresh_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建完后,仍需要在oauth_client_details
表插入上面代码在认证服务器上的客户端配置相应的信息。
--按照上面客户端配置的相应的插入语句
INSERT INTO `navigation_server`.`oauth_client_details` (`client_id`, `resource_ids`, `client_secret`, `scope`, `authorized_grant_types`, `web_server_redirect_uri`, `authorities`, `access_token_validity`, `refresh_token_validity`, `additional_information`, `autoapprove`) VALUES ('kangCloud', NULL, '$2a$10$GBiczT2GQgEY.VTY1oUXT.Ey6MSvJpU2UOBe2hRFnu.G6xWqvNzuC', 'all', 'password,authorization_code,refresh_token,implicit,client_credentials', NULL, NULL, NULL, NULL, NULL, 'true');
其中因为我设定了客户端密码是密文,相应表上的client_secret
也是密文;
还可以在密文上添加{bcrypt}
的标识,告诉服务器这是哪一种加密方式,例如:
{bcrypt}$2a$10$GBiczT2GQgEY.VTY1oUXT.Ey6MSvJpU2UOBe2hRFnu.G6xWqvNzuC
配置资源服务器(继承ResourceServerConfigurerAdapter)
@Configuration
@EnableResourceServer
public class ResServerConfig extends ResourceServerConfigurerAdapter{
private final Logger logger = LoggerFactory.getLogger(ResServerConfig.class);
@Autowired
private TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources
.tokenStore(tokenStore)
.resourceId("resource_id")// resourceId要跟认证服务器客户端配置的resourceId一致
.stateless(true);
}
/*
spring security 先通过ResourceSecurityConfiguration的配置先执行
,再执行webSecurityConfiguration的配置,所以要规划好不同断点对应的过滤链不冲突,需要清晰规划好。
*/
@Override
public void configure(HttpSecurity http) throws Exception {
logger.info("=======================================ResServerConfig=================================================");
http
.authorizeRequests()
.antMatchers("/v1.1/**",
"/v1.0/**").authenticated()// 在resource配置需要认证
.antMatchers("/oauth/**",
"/open/**").permitAll() // 不需要认证
.and()
.csrf().disable();
}
}
备注:
1. 调整过滤器链可以在配置头部加上@Order(int顺序)1->2->3
2. 即使在application设置了server.servlet.context-path
,在以上的配置类上也无需补上context-path
最后可以打开postman来调用是否搭建成功!
地址:http://localhost/api/oauth/token?grant_type=password&username=xxx&password=xxx&client_id=client&client_secret=secret (密码模式)