如需转载,请根据 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 许可,附上本文作者及链接。
本文作者: 执笔成念
作者昵称: zbcn
本文链接: https://1363653611.github.io/zbcn.github.io/2021/01/14/springcloud14-security-author2%E5%85%A5%E9%97%A8/
Spring Cloud Security:Oauth2使用入门
Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2可以实现单点登录、令牌中继、令牌交换等功能,本文将对其结合Oauth2入门使用进行详细介绍。
OAuth2 简介
OAuth 2.0是用于授权的行业标准协议。OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等。
OAuth2 相关名词解释
- Resource owner(资源拥有者):拥有该资源的最终用户,他有访问资源的账号密码;
- Resource server(资源服务器):拥有受保护资源的服务器,如果请求包含正确的访问令牌,可以访问资源;
- Client(客户端):访问资源的客户端,会使用访问令牌去获取资源服务器的资源,可以是浏览器、移动设备或者服务器;
- Authorization server(认证服务器):用于认证用户的服务器,如果客户端认证通过,发放访问资源服务器的令牌。
四种授权模式
- Authorization Code(授权码模式):正宗的OAuth2的授权模式,客户端先将用户导向认证服务器,登录后获取授权码,然后进行授权,最后根据授权码获取访问令牌;
- Implicit(简化模式):和授权码模式相比,取消了获取授权码的过程,直接获取访问令牌;
- Resource Owner Password Credentials(密码模式):客户端直接向用户获取用户名和密码,之后向认证服务器获取访问令牌;
- Client Credentials(客户端模式):客户端直接通过客户端认证(比如client_id和client_secret)从认证服务器获取访问令牌。
两种常用的授权模式
授权码模式
- (A)客户端将用户导向认证服务器;
- (B)用户在认证服务器进行登录并授权;
- (C)认证服务器返回授权码给客户端;
- (D)客户端通过授权码和跳转地址向认证服务器获取访问令牌;
- (E)认证服务器发放访问令牌(有需要带上刷新令牌)。
密码模式
- (A)客户端从用户获取用户名和密码;
- (B)客户端通过用户的用户名和密码访问认证服务器;
- (C)认证服务器返回访问令牌(有需要带上刷新令牌)。
Oauth2的使用
创建oauth2-server模块
这里我们创建一个oauth2-server模块作为认证服务器来使用。
- 在pom.xml中添加相关依赖:
1 | <dependency> |
2 | <groupId>org.springframework.cloud</groupId> |
3 | <artifactId>spring-cloud-starter-oauth2</artifactId> |
4 | </dependency> |
5 | <dependency> |
6 | <groupId>org.springframework.cloud</groupId> |
7 | <artifactId>spring-cloud-starter-security</artifactId> |
8 | </dependency> |
9 | <dependency> |
10 | <groupId>org.springframework.boot</groupId> |
11 | <artifactId>spring-boot-starter-web</artifactId> |
12 | </dependency> |
- 在application.yml中进行配置:
1 | server: |
2 | port: 9401 |
3 | spring: |
4 | application: |
5 | name: oauth2-service |
- 添加UserService实现UserDetailsService接口,用于加载用户信息:
1 | |
2 |
|
3 | public class UserService implements UserDetailsService { |
4 | private List<User> userList; |
5 | |
6 | private PasswordEncoder passwordEncoder; |
7 | |
8 | |
9 | public void initData() { |
10 | String password = passwordEncoder.encode("123456"); |
11 | userList = new ArrayList<>(); |
12 | userList.add(new User("macro", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"))); |
13 | userList.add(new User("andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); |
14 | userList.add(new User("mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); |
15 | } |
16 | |
17 | |
18 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { |
19 | List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList()); |
20 | if (!CollectionUtils.isEmpty(findUserList)) { |
21 | return findUserList.get(0); |
22 | } else { |
23 | throw new UsernameNotFoundException("用户名或密码错误"); |
24 | } |
25 | } |
26 | } |
- 添加认证服务器配置,使用@EnableAuthorizationServer注解开启:
1 |
|
2 |
|
3 | public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { |
4 | |
5 | |
6 | private PasswordEncoder passwordEncoder; |
7 | |
8 | |
9 | private AuthenticationManager authenticationManager; |
10 | |
11 | |
12 | private UserService userService; |
13 | |
14 | /** |
15 | * 使用密码模式需要配置 |
16 | */ |
17 | |
18 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) { |
19 | endpoints.authenticationManager(authenticationManager) |
20 | .userDetailsService(userService); |
21 | } |
22 | |
23 | |
24 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { |
25 | clients.inMemory() |
26 | .withClient("admin")//配置client_id |
27 | .secret(passwordEncoder.encode("admin123456"))//配置client_secret |
28 | .accessTokenValiditySeconds(3600)//配置访问token的有效期 |
29 | .refreshTokenValiditySeconds(864000)//配置刷新token的有效期 |
30 | .redirectUris("http://www.baidu.com")//配置redirect_uri,用于授权成功后跳转 |
31 | .scopes("all")//配置申请的权限范围 |
32 | .authorizedGrantTypes("authorization_code","password");//配置grant_type,表示授权类型 |
33 | } |
34 | } |
- 添加资源服务器配置,使用@EnableResourceServer注解开启:
1 |
|
2 |
|
3 | public class ResourceServerConfig extends ResourceServerConfigurerAdapter { |
4 | |
5 | public void configure(HttpSecurity http) throws Exception { |
6 | http.authorizeRequests() |
7 | .anyRequest() |
8 | .authenticated() |
9 | .and() |
10 | .requestMatchers() |
11 | .antMatchers("/user/**");//配置需要保护的资源路径 |
12 | } |
13 | } |
- 添加SpringSecurity配置,允许认证相关路径的访问及表单登录:
1 |
|
2 |
|
3 | public class SecurityConfig extends WebSecurityConfigurerAdapter { |
4 | |
5 | public PasswordEncoder passwordEncoder() { |
6 | return new BCryptPasswordEncoder(); |
7 | } |
8 | |
9 | |
10 | |
11 | public AuthenticationManager authenticationManagerBean() throws Exception { |
12 | return super.authenticationManagerBean(); |
13 | } |
14 | |
15 | |
16 | public void configure(HttpSecurity http) throws Exception { |
17 | http.csrf() |
18 | .disable() |
19 | .authorizeRequests() |
20 | .antMatchers("/oauth/**", "/login/**", "/logout/**") |
21 | .permitAll() |
22 | .anyRequest() |
23 | .authenticated() |
24 | .and() |
25 | .formLogin() |
26 | .permitAll(); |
27 | } |
28 | } |
- 添加需要登录的接口用于测试:
1 |
|
2 | "/user") ( |
3 | public class UserController { |
4 | |
5 | "/getCurrentUser") ( |
6 | public Object getCurrentUser(Authentication authentication) { |
7 | return authentication.getPrincipal(); |
8 | } |
9 | } |
授权码模式使用
- 启动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=xFHehO&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请求获取访问令牌;
使用到的模块
1 | ZBCN-SERVER |
2 | └── zbcn-author/oauth2-server -- oauth2认证测试服务 |