Spring Cloud Security 整合 Oauth2

一、环境搭建

  • 添加依赖

    <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: 8080
    spring:
      application:
        name: oauth
    
  • 创建业务实现类

    @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("admin", password, 		
                              AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
            userList.add(new User("zhangsan", password, 
                             AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
            userList.add(new User("lisi", 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("用户名不存在!");
            }
        }
    }
    
  • 创建认证服务器配置类

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @Autowired
        private UserDetailServiceImpl userDetailsService;
    
        /**
         * 使用密码模式所需配置
         */
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints.authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService);
        }
    
        @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.my.com") 
                	// 配置scope,申请的权限范围
                    .scopes("all") 
                  // 配置grant_type,授权的模式
                  .authorizedGrantTypes("authorization_code", "password", "refresh_token"); 
        }
    }
    
  • 创建资源服务器配置类

    @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
        public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/oauth/**", "/login/**")
                    .permitAll()
                    .anyRequest()
                    .authenticated()
                    .and()
                    .formLogin()
                    .permitAll();
        }
    }
    
  • 添加控制器类

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @GetMapping("/info")
        public Object getUserInfo(Authentication authentication) {
            return authentication.getPrincipal();
        }
    }
    

二、授权码模式测试

  • 登录授权获取授权码

    访问地址:
    http://localhost:8080/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.my.com&scope=all&state=normal

    在这里插入图片描述

    在这里插入图片描述

    # 查看跳转的请求路径
    https://www.my.com/?code=eTsADY&state=normal
    
  • 获取访问令牌

    使用Postman工具

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

  • 测试获取用户信息

    在这里插入图片描述

    在这里插入图片描述

三、密码模式测试

  • 获取访问令牌

    使用Postman工具

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

  • 测试获取用户信息

    在这里插入图片描述

    在这里插入图片描述

四、刷新令牌

在这里插入图片描述


【源码地址】:GitHub

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程小吉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值