本文认证基于内存(后续会说基于jdbc),后续会推出基于spring cloud auth2的SSO实战服务。
- 本文基于gradle,有用maven的朋友可以移步maven仓库查找对应的jar包
implementation 'org.springframework.cloud:spring-cloud-starter-oauth2'
implementation 'org.springframework.cloud:spring-cloud-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
- maven仓库地址
[https://mvnrepository.com/](https://mvnrepository.com/)
- 推荐使用阿里云的仓库地址
maven { url = 'http://maven.aliyun.com/nexus/content/groups/public/' }
其实auth2服务还是蛮重要的,作为一个比较大的企业,可能会开发出各种自己公司的产品,这时候就需要单点登录支持,包括业务中台、技术中台的沉淀,这对一个公司来说是非常重要的,一个好公司的良好高效、快速的发展,离不开多年技术的积累,具体的要做什么可以咨询我哦
接下来就是实战了,写了一个比较简单的demo,大家可以在这个基础上进行优化!
1. 继承AuthorizationServerConfigurerAdapter
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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.InMemoryTokenStore;
/**
* AuthorizationServerConfigurerAdapter
*
* @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
* @date 2019/11/23 9:27
*/
@Configuration
@EnableAuthorizationServer
public class AuthorServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManagerBeans;
@Autowired
private TokenStore tokenStore;
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManagerBeans)
.tokenStore(tokenStore);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "USER")
.scopes("all")
.autoApprove(true)
.secret(passwordEncoder().encode("secret"));
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("isAuthenticated()");
security.tokenKeyAccess("isAuthenticated()");
security.allowFormAuthenticationForClients();
}
}
- clients
- clients直接存放在内存中,可以直接使用client.jdbc()注入datasource,导入数据库脚本,然后oauth2自动回去数据库进行校验,章节长度有限,后续更新SSO的文章会说、会用到!
- authorizedGrantTypes 认证的类型
- autoApprove这个是当你访问oauth/authorize的时候,会出现是否通过认证的页面!,这里设置了之后,就会自动通过,不同手动认证通过啦
- 本文直接用的token,也可以使用jwt,后续的SSO文章会讲到!
2. 继承WebSecurityConfigurerAdapter
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
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.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
* WebSecurityConfigurerAdapter
*
* @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
* @date 2019/11/23 9:34
*/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
PasswordEncoder passwordEncoder;
@Bean
public AuthenticationManager authenticationManagerBeans() throws Exception {
return super.authenticationManagerBean();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user = User.builder().username("user").password(passwordEncoder.encode("secret")).roles("USER").build();
UserDetails userAdmin = User.builder().username("admin").password(passwordEncoder.encode("secret")).roles("ADMIN").build();
return new InMemoryUserDetailsManager(user, userAdmin);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/customer");
}
}
- 这里有一个userDetailsService的bean,这里就是用来验证登录的用户,然后赋予他们的权限。但是你看到这,你自己是不是会思考一个问题,如果用户量很大,这里如果要是这样写,是不是要写疯掉。当然啦,后续的SSO章节会讲到,我们是会从数据库中拉数据进行验证和赋予权限的,这个不用担心0->-0.
3. 继承ResourceServerConfigurerAdapter
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.web.bind.annotation.RestController;
/**
* ResourceServerConfigurerAdapter
*
* @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
* @date 2019/11/23 9:37
*/
@EnableResourceServer
@RestController
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests().antMatchers("/oauth/token", "/oauth/authorize**", "/customer").permitAll()
// .anyRequest().authenticated();
http.requestMatchers().antMatchers("/private")
.and().authorizeRequests()
.antMatchers("/private").access("hasRole('USER')")
.and().requestMatchers().antMatchers("/admin")
.and().authorizeRequests()
.antMatchers("/admin").access("hasRole('ADMIN')").anyRequest().authenticated();
}
}
- 这个就是对访问的资源进行控制啦!
4. 写一个controller
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@RequestMapping("/admin")
public String admin() {
return "admin access successful";
}
@RequestMapping("/private")
public String user() {
return "private access successful";
}
@RequestMapping("/customer")
public String customer() {
return "customer access successful";
}
}
5. postman使用过程
- 本次采用的password认证方式,下一篇文章使用的是authorization_code的方式!
- 使用basic认证
- post参数调好,见下图,开启服务,就可以发起请求啦
- 获取到token,和jwt token还是有点区别的,一个长一个短
-
访问我们写的controller中的uri,你们看看是不是不同的用户登录是不是有些会访问不到呀!
image.png
image.png
网友评论