项目使用的Spring Cloud为Hoxton版本,Spring Boot为2.2.2.RELEASE版本
序号 | 内容 | 链接地址 |
---|---|---|
1 | Spring Cloud入门-十分钟了解Spring Cloud | https://blog.csdn.net/ThinkWon/article/details/103715146 |
2 | Spring Cloud入门-Eureka服务注册与发现(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103726655 |
3 | Spring Cloud入门-Ribbon服务消费者(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103729080 |
4 | Spring Cloud入门-Hystrix断路器(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103732497 |
5 | Spring Cloud入门-Hystrix Dashboard与Turbine断路器监控(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103734664 |
6 | Spring Cloud入门-OpenFeign服务消费者(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103735751 |
7 | Spring Cloud入门-Zuul服务网关(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103738851 |
8 | Spring Cloud入门-Config分布式配置中心(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103739628 |
9 | Spring Cloud入门-Bus消息总线(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103753372 |
10 | Spring Cloud入门-Sleuth服务链路跟踪(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103753896 |
11 | Spring Cloud入门-Consul服务注册发现与配置中心(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103756139 |
12 | Spring Cloud入门-Gateway服务网关(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103757927 |
13 | Spring Cloud入门-Admin服务监控中心(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103758697 |
14 | Spring Cloud入门-Oauth2授权的使用(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103761687 |
15 | Spring Cloud入门-Oauth2授权之JWT集成(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103763364 |
16 | Spring Cloud入门-Oauth2授权之基于JWT完成单点登录(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103766368 |
17 | Spring Cloud入门-Nacos实现注册和配置中心(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103769680 |
18 | Spring Cloud入门-Sentinel实现服务限流、熔断与降级(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103770879 |
19 | Spring Cloud入门-Seata处理分布式事务问题(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103786102 |
20 | Spring Cloud入门-汇总篇(Hoxton版本) | https://blog.csdn.net/ThinkWon/article/details/103786588 |
Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2可以实现单点登录、令牌中继、令牌交换等功能,本文将对其结合Oauth2入门使用进行详细介绍。
OAuth 2.0是用于授权的行业标准协议。OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等。
这里我们创建一个oauth2-server模块作为授权服务器来使用。
在pom.xml中添加相关依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-oauth2artifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-securityartifactId>
dependency>
在application.yml中进行配置:
server:
port: 9401
spring:
application:
name: oauth2-server
添加UserService实现UserDetailsService接口,用于加载用户信息:
@Service
public class UserService implements UserDetailsService {
private List<User> userList;
@Autowired
private PasswordEncoder passwordEncoder;
@PostConstruct
public void initData() {
String password = passwordEncoder.encode("123456");
userList = new ArrayList<>();
userList.add(new User("jourwon",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
userList.add(new User("andy",password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
userList.add(new User("mark",password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(findUserList)) {
return findUserList.get(0);
} else {
throw new UsernameNotFoundException("用户名或密码错误");
}
}
}
添加授权服务器配置,使用@EnableAuthorizationServer注解开启:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserService userService;
/**
* 使用密码模式需要配置
*
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userService);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
// 配置client_id
.withClient("admin")
// 配置client_secret
.secret(passwordEncoder.encode("admin123456"))
// 配置访问token的有效期
.accessTokenValiditySeconds(3600)
// 配置刷新token的有效期
.refreshTokenValiditySeconds(864000)
// 配置redirect_uri,用于授权成功后的跳转
.redirectUris("http://www.baidu.com")
// 配置申请的权限范围
.scopes("all")
// 配置grant_type,表示授权类型
.authorizedGrantTypes("authorization_code", "password");
}
}
添加资源服务器配置,使用@EnableResourceServer注解开启:
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.requestMatchers()
// 配置需要保护的资源路径
.antMatchers("/user/**");
}
}
添加SpringSecurity配置,允许授权相关路径的访问及表单登录:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/oauth/**", "/login/**", "logout/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.permitAll();
}
}
添加需要登录的接口用于测试:
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/getCurrentUser")
public Object getCurrentUser(Authentication authentication) {
return authentication.getPrincipal();
}
}
启动oauth2-server服务;
在浏览器访问该地址进行登录授权:http://localhost:9401/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all&state=normal
输入账号密码进行登录操作:
登录后进行授权操作:
之后会浏览器会带着授权码跳转到我们指定的路径:
https://www.baidu.com/?code=cbM53v&state=normal
使用授权码请求该地址获取访问令牌:http://localhost:9401/oauth/token
使用Basic授权通过client_id和client_secret构造一个Authorization头信息;
在body中添加以下参数信息,通过POST请求获取访问令牌;
在请求头中添加访问令牌,访问需要登录授权的接口进行测试,发现已经可以成功访问:http://localhost:9401/user/getCurrentUser
使用密码请求该地址获取访问令牌:http://localhost:9401/oauth/token
使用Basic授权通过client_id和client_secret构造一个Authorization头信息;
在body中添加以下参数信息,通过POST请求获取访问令牌;
springcloud-learning
└── oauth2-server -- oauth2授权测试服务
GitHub项目源码地址