摘要


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)用户在认证服务器进行登录并授权;
  • ©认证服务器返回授权码给客户端;
  • (D)客户端通过授权码和跳转地址向认证服务器获取访问令牌;
  • (E)认证服务器发放访问令牌(有需要带上刷新令牌)。
授权码模式

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

Oauth2的使用


创建oauth2-server模块

这里我们创建一个oauth2-server模块作为认证服务器来使用。

  • 在pom.xml中添加相关依赖:
<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>
  • 在application.yml中进行配置:
server:port: 9401
spring:application:name: oauth2-service
  • 添加UserService实现UserDetailsService接口,用于加载用户信息:
/*** Created by macro on 2019/9/30.*/
@Service
public class UserService implements UserDetailsService {private List<User> userList;@Autowiredprivate PasswordEncoder passwordEncoder;@PostConstructpublic 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")));}@Overridepublic 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注解开启:
/*** 认证服务器配置* Created by macro on 2019/9/30.*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserService userService;/*** 使用密码模式需要配置*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {endpoints.authenticationManager(authenticationManager).userDetailsService(userService);}@Overridepublic 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,表示授权类型}
}
  • 添加资源服务器配置,使用@EnableResourceServer注解开启
/*** 资源服务器配置* Created by macro on 2019/9/30.*/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().requestMatchers().antMatchers("/user/**");//配置需要保护的资源路径}
}
  • 添加SpringSecurity配置,允许认证相关路径的访问及表单登录:
/*** SpringSecurity配置* Created by macro on 2019/10/8.*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overridepublic void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/oauth/**", "/login/**", "/logout/**").permitAll().anyRequest().authenticated().and().formLogin().permitAll();}
}
  • 添加需要登录的接口用于测试:
/*** Created by macro on 2019/9/30.*/
@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=norma
  • 输入账号密码进行登录操作:
  • 登录后进行授权操作:
  • 之后会浏览器会带着授权码跳转到我们指定的路径:

https://www.baidu.com/?code=eTsADY&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认证测试服务

项目源码地址


https://github.com/macrozheng/springcloud-learning

Spring Cloud Security:Oauth2使用入门相关推荐

  1. gateway oauth2 对称加密_深入理解Spring Cloud Security OAuth2及JWT

    因项目需要,需要和三方的oauth2服务器进行集成.网上关于spring cloud security oauth2的相关资料,一般都是讲如何配置,而能把这块原理讲透彻的比较少,这边自己做一下总结和整 ...

  2. 玩转Spring Cloud Security OAuth2身份认证扩展——电话号码+验证码认证

    在程序的认证过程中,除了常规的用户名和密码方式(可以参考深入理解Spring Cloud Security OAuth2身份认证),也经常会出现电话号码+密码的方式:电话号码+验证码的方式:或者第三方 ...

  3. 【java_wxid项目】【第七章】【Spring Cloud Security Oauth2集成】

    主项目链接:https://gitee.com/java_wxid/java_wxid 项目架构及博文总结: 点击:[使用Spring Boot快速构建应用] 点击:[使用Spring Cloud O ...

  4. Spring Cloud Security OAuth2结合网关

    文章目录 一.需求分析 二.服务搭建 2.1 注册中心 Eureka 搭建 2.2 网关 Zuul 搭建 2.2.1 转发明文token给微服务 2.2.2 微服务处理 token 2.2.3 Spr ...

  5. Spring Cloud Security:Oauth2实现单点登录

    摘要 Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2可以实现单点登录功能,本文将对其单点登录用法进行详细介绍. 单点登录简介 单 ...

  6. Spring Cloud Security:Oauth2结合JWT使用

    摘要 Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2还可以实现更多功能,比如使用JWT令牌存储信息,刷新令牌功能,本文将对其结合 ...

  7. java B2B2C springmvc mybatis电子商务平台源码-Spring Cloud Security

    一.SpringCloud Security简介           Spring Cloud Security提供了一组原语,用于构建安全的应用程序和服务,而且操作简便.可以在外部(或集中)进行大量 ...

  8. 微服务集成cas_Spring Cloud(四) Spring Cloud Security集成CAS (单点登录)对微服务认证...

    一.前言 由于leader要求在搭好的spring cloud 框架中加入对微服务的认证包括单点登录认证,来确保系统的安全,所以研究了Spring Cloud Security这个组件.在前面搭好的d ...

  9. 「springcloud 2021 系列」Spring Cloud Gateway + OAuth2 + JWT 实现统一认证与鉴权

    通过认证服务进行统一认证,然后通过网关来统一校验认证和鉴权. 将采用 Nacos 作为注册中心,Gateway 作为网关,使用 nimbus-jose-jwt JWT 库操作 JWT 令牌 理论介绍 ...

最新文章

  1. CORS在Spring中的实现
  2. bug4 导入新工程时报 Target runtime com.genuitec.runtime.generic.jee60 is not defined
  3. 产品经理这个岗位是否真的可有可无?
  4. ORB-SLAM(四)追踪
  5. python鼠标事件 详解_Python selenium键盘鼠标事件实现过程详解
  6. aidl使用_Android进阶之AIDL如何使用自定义类型
  7. WWDC 2018: Shortcuts 快速入门
  8. 火车站售票系统_好消息!海门火车站自助售取票机增加自助退票功能
  9. JAVA面试要点003_Mybatis中#和$的区别
  10. UE4在VR模式下使用3D控件
  11. Android 自定义字体(otf,ttf等等)
  12. CVonline: Image Databases
  13. 软件测试工程师怎么写okr,测试工程师提高质量的OKR该如何写?
  14. 长连接如何转换为短连接格式呢?
  15. java 句柄无效_Java 关于java.io.IOException: 句柄无效。
  16. 【剑指offer】面试题46:把数字翻译成字符串【C++版本】
  17. 多元统计分析——聚类分析——K-均值聚类(K-中值、K-众数)
  18. 树莓派开发系列教程5——树莓派常用软件及服务(vi、远程桌面、ssh、samba、u盘)
  19. win32 - 保存路径对话框(SelectFolderDialog)
  20. BT结束,高宽带有何用?

热门文章

  1. 关于php 高并发解决的一点思路
  2. 【翻译自mos文章】job 不能自己主动运行的解决方法
  3. java取主机的网卡物理地址
  4. css箭头超链接,css超链接
  5. seo html空格影响,这一对HTML标签嵌套对SEO优化的影响,居然99%的人不知道!
  6. qqkey获取原理_获取QQKEY源码[C++版]
  7. sift分类java_使用SIFT / SURF进行特征匹配是否可以用于类似对象的分类?
  8. java归还线程_再谈java线程
  9. linux 文件权限 rwt,linux 文件权限
  10. mac photoshop install无法安装_MAC安装应用报错:无法打开或文件损坏的处理方法~...