2021-10-27

Spring Cloud Security:Oauth2使用

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

OAuth 2.0是用于授权的行业标准协议。OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等。我们了解一下相关角色:

  • Resource owner(资源拥有者):拥有该资源的最终用户,他有访问资源的账号密码;
  • Resource server(资源服务器):拥有受保护资源的服务器,如果请求包含正确的访问令牌,可以访问资源;
  • Client(客户端):访问资源的客户端,会使用访问令牌去获取资源服务器的资源,可以是浏览器、移动设备或者服务器;
  • Authorization server(认证服务器):用于认证用户的服务器,如果客户端认证通过,发放访问资源服务器的令牌。

一、授权模式

OAuth有四种授权模式:

  • Authorization Code(授权码模式):正宗的OAuth2的授权模式,客户端先将用户导向认证服务器,登录后获取授权码,然后进行授权,最后根据授权码获取访问令牌;
  • Implicit(简化模式):和授权码模式相比,取消了获取授权码的过程,直接获取访问令牌;
  • Resource Owner Password Credentials(密码模式):客户端直接向用户获取用户名和密码,之后向认证服务器获取访问令牌;
  • Client Credentials(客户端模式):客户端直接通过客户端认证(比如client_id和client_secret)从认证服务器获取访问令牌。

我们来看一下我们常用的两种模式:授权码模式,密码模式。
授权码模式
在这里插入图片描述
流程:
(A)客户端将用户导向认证服务器;
(B)用户在认证服务器进行登录并授权;
©认证服务器返回授权码给客户端;
(D)客户端通过授权码和跳转地址向认证服务器获取访问令牌;
(E)认证服务器发放访问令牌(有需要带上刷新令牌)。

密码模式

流程:
(A)客户端从用户获取用户名和密码;
(B)客户端通过用户的用户名和密码访问认证服务器;
©认证服务器返回访问令牌(有需要带上刷新令牌)。

二、使用步骤

1.配置

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
server:
  port: 9401
spring:
  application:
    name: oauth2-service

2.加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("macro", 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("用户名或密码错误");
        }
    }
}

3.添加认证服务器配置,使用@EnableAuthorizationServer注解开启

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    /**
     * 使用密码模式需要配置
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("admin")//配置client_id
                .secret(passwordEncoder.encode("admin123456"))//配置client_secret
                .accessTokenValiditySeconds(3600)//配置访问token的有效期
                .refreshTokenValiditySeconds(864000)//配置刷新token的有效期
                .redirectUris("http://www.baidu.com")//配置redirect_uri,用于授权成功后跳转
                .scopes("all")//配置申请的权限范围
                .authorizedGrantTypes("authorization_code","password");//配置grant_type,表示授权类型
    }
}

4.添加资源服务器配置,使用@EnableResourceServer注解开启

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .requestMatchers()
                .antMatchers("/user/**");//配置需要保护的资源路径
    }
}

5.添加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
    public 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();
    }
}

我们在使用授权码模式和密码模式之前,我们先回顾一下授权码模式和密码模式的区别:

.授权码模式
1、封装参数,访问授权服务器登录与授权接口
   接口:http://localhost:8080/oauth/authorize
   参数:response_type client_id scope redirect_uri state
   返回值:code
2、拿到code,获取token
   接口:http://localhost:8080/oauth/token
   参数:client_id client_secret grant_type code redirect_uri state
   返回值:access_token
3、根据token,访问资源
   接口:http://localhost:8080/api/test/hello
   参数:access_token

二.密码模式
1、根据用户名密码等参数直接获取token
   接口:http://localhost:8080/oauth/token
   参数:username password grant_type client_id client_secret redirect_uri
   返回值:access_token
2、根据token,访问资源
   接口:http://localhost:8080/api/test/hello
   参数:access_token


授权码模式多了一步就是登陆。密码模式直接把用户名和密码交给授权服务器了,所以不用再人为登陆,这也要求用户非常信任该应用。

授权码模式使用

1.启动oauth2-server服务;
2.在浏览器访问该地址进行登录授权:
http://localhost:9401/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all&state=normal;
3.输入账号密码进行登录操作;
4.登录后进行授权操作;
5.之后会浏览器会带着授权码跳转到我们指定的路径;
6.使用授权码请求该地址获取访问令牌:http://localhost:9401/oauth/token;
7.使用Basic认证通过client_id和client_secret构造一个Authorization头信息;
8.在body中添加以下参数信息,通过POST请求获取访问令牌;
9.在请求头中添加访问令牌,访问需要登录认证的接口进行测试。

密码模式

密码模式流程比授权码模式要短,主要就是少了获取code的过程。


总结

在以上的四种模式中,我们需要掌握的就是授权码模式,掌握了授权码模式,密码模式就很容易懂了,然后我们再去了解其他两种模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值