Spring Security功能多,组件抽象程度高,配置方式多样,导致了Spring Security强大且复杂的特性。Spring Security的学习成本几乎是Spring家族中最高的,Spring Security的精良设计值得我们学习,但是结合实际复杂的业务场景,我们不但需要理解Spring Security的扩展方式还需要去理解一些组件的工作原理和流程(否则怎么去继承并改写需要改写的地方呢?),这又带来了更高的门槛,因此,在决定使用Spring Security搭建整套安全体系(授权、认证、权限、审计)之前还是需要考虑一下将来我们的业务会多复杂,我们徒手写一套安全体系来的划算还是使用Spring Security更好。

短短的一篇文章不可能覆盖Spring Security的方方面面,在最近的工作中会比较多接触OAuth2,因此本文以这个维度来简单阐述一下如果使用Spring Security搭建一套OAuth2授权&SSO架构。

OAuth2简介

OAuth2.0是一套授权体系的开放标准,定义了四大角色:

  1. 资源拥有者,也就是用户,由用于授予三方应用权限
  2. 客户端,也就是三方应用程序,在访问用户资源之前需要用户授权
  3. 资源提供者,或者说资源服务器,提供资源,需要实现Token和ClientID的校验,以及做好相应的权限控制
  4. 授权服务器,验证用户身份,为客户端颁发Token,并且维护管理ClientID、Token以及用户

其中后三项都可以是独立的程序,在本文的例子中我们会为这三者建立独立的项目。OAuth2.0标准同时定义了四种授权模式,这里介绍最常用的三种,也是后面会演示的三种(在之后的介绍中令牌=Token,码=Code,可能会混合表达):

  1. 不管是哪种模式,通用流程如下:

    • 三方网站(或者说客户端)需要先向授权服务器去申请一套接入的ClientID+ClientSecret
    • 用任意一种模式拿到访问Token(流程见下)
    • 拿着访问Token去资源服务器请求资源
    • 资源服务器根据Token查询到Token对应的权限进行权限控制
  2. 授权码模式,最标准最安全的模式,适合和外部交互,流程是:
    • 三方网站客户端转到授权服务器,上送ClientID,授权范围Scope、重定向地址RedirectUri等信息
    • 用户在授权服务器进行登录并且进行授权批准(授权批准这步可以配置为自动完成)
    • 授权完成后重定向回到之前客户端提供的重定向地址,附上授权码
    • 三方网站服务端通过授权码+ClientID+ClientSecret去授权服务器换取Token(Token含访问Token和刷新Token,访问Token过去后用刷新Token去获得新的访问Token)
    • 你可能会问这个模式为什么这么复杂,为什么安全呢?因为我们不会对外暴露ClientSecret,不会对外暴露访问Token,使用授权码换取Token的过程是服务端进行,客户端拿到的只是一次性的授权码
  3. 密码凭证模式,适合内部系统之间使用的模式(客户端是自己人,客户端需要拿到用户帐号密码),流程是:
    • 用户提供帐号密码给客户端
    • 客户端凭着用户的帐号密码,以及客户端自己的ClientID+ClientSecret去授权服务器换取Token
  4. 客户端模式,适合内部服务端之间使用的模式:
    • 和用户没有关系,不是基于用户的授权
    • 客户端凭着自己的ClientID+ClientSecret去授权服务器换取Token

下面,我们来搭建程序实际体会一下这几种模式。

搭建授权服务器

首先来创建一个父POM,内含三个模块:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://maven.apache.org/POM/4.0.0"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>me.josephzhu</groupId>
  7. <artifactId>springsecurity101</artifactId>
  8. <packaging>pom</packaging>
  9. <version>1.0-SNAPSHOT</version>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>2.0.6.RELEASE</version>
  14. <relativePath/>
  15. </parent>
  16. <modules>
  17. <module>springsecurity101-cloud-oauth2-client</module>
  18. <module>springsecurity101-cloud-oauth2-server</module>
  19. <module>springsecurity101-cloud-oauth2-userservice</module>
  20. </modules>
  21. <properties>
  22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  24. <java.version>1.8</java.version>
  25. </properties>
  26. <dependencies>
  27. <dependency>
  28. <groupId>org.projectlombok</groupId>
  29. <artifactId>lombok</artifactId>
  30. <optional>true</optional>
  31. </dependency>
  32. </dependencies>
  33. <dependencyManagement>
  34. <dependencies>
  35. <dependency>
  36. <groupId>org.springframework.cloud</groupId>
  37. <artifactId>spring-cloud-dependencies</artifactId>
  38. <version>Finchley.SR2</version>
  39. <type>pom</type>
  40. <scope>import</scope>
  41. </dependency>
  42. </dependencies>
  43. </dependencyManagement>
  44. <build>
  45. <plugins>
  46. <plugin>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-maven-plugin</artifactId>
  49. </plugin>
  50. </plugins>
  51. </build>
  52. <repositories>
  53. <repository>
  54. <id>spring-milestones</id>
  55. <name>Spring Milestones</name>
  56. <url>https://repo.spring.io/libs-milestone</url>
  57. <snapshots>
  58. <enabled>false</enabled>
  59. </snapshots>
  60. </repository>
  61. </repositories>
  62. </project>

然后我们创建第一个模块,资源服务器:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://maven.apache.org/POM/4.0.0"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>springsecurity101</artifactId>
  7. <groupId>me.josephzhu</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>springsecurity101-cloud-oauth2-server</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-oauth2</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-jdbc</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>mysql</groupId>
  23. <artifactId>mysql-connector-java</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-web</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  32. </dependency>
  33. </dependencies>
  34. </project>

这边我们除了使用了Spring Cloud的OAuth2启动器之外还使用数据访问、Web等依赖,因为我们的资源服务器需要使用数据库来保存客户端的信息、用户信息等数据,我们同时也会使用thymeleaf来稍稍美化一下登录页面。

现在我们来创建一个配置文件application.yml:

  1. server:
  2. port: 8080
  3. spring:
  4. application:
  5. name: oauth2-server
  6. datasource:
  7. url: jdbc:mysql://localhost:3306/oauth?useSSL=false
  8. username: root
  9. password: root
  10. driver-class-name: com.mysql.jdbc.Driver

可以看到,我们会使用oauth数据库,授权服务器的端口是8080。

数据库中我们需要初始化一些表:

  1. 用户表users:存放用户名密码
  2. 授权表authorities:存放用户对应的权限
  3. 客户端信息表oauth_client_details:存放客户端的ID、密码、权限、允许访问的资源服务器ID以及允许使用的授权模式等信息
  4. 授权码表oauth_code:存放了授权码
  5. 授权批准表oauth_approvals:存放了用户授权第三方服务器的批准情况

DDL如下:

  1. -- ----------------------------
  2. -- Table structure for authorities
  3. -- ----------------------------
  4. DROP TABLE IF EXISTS `authorities`;
  5. CREATE TABLE `authorities` (
  6. `username` varchar(50) NOT NULL,
  7. `authority` varchar(50) NOT NULL,
  8. UNIQUE KEY `ix_auth_username` (`username`,`authority`),
  9. CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
  10. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
  11. -- ----------------------------
  12. -- Table structure for oauth_approvals
  13. -- ----------------------------
  14. DROP TABLE IF EXISTS `oauth_approvals`;
  15. CREATE TABLE `oauth_approvals` (
  16. `userId` varchar(256) DEFAULT NULL,
  17. `clientId` varchar(256) DEFAULT NULL,
  18. `partnerKey` varchar(32) DEFAULT NULL,
  19. `scope` varchar(256) DEFAULT NULL,
  20. `status` varchar(10) DEFAULT NULL,
  21. `expiresAt` datetime DEFAULT NULL,
  22. `lastModifiedAt` datetime DEFAULT NULL
  23. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  24. -- ----------------------------
  25. -- Table structure for oauth_client_details
  26. -- ----------------------------
  27. DROP TABLE IF EXISTS `oauth_client_details`;
  28. CREATE TABLE `oauth_client_details` (
  29. `client_id` varchar(255) NOT NULL,
  30. `resource_ids` varchar(255) DEFAULT NULL,
  31. `client_secret` varchar(255) DEFAULT NULL,
  32. `scope` varchar(255) DEFAULT NULL,
  33. `authorized_grant_types` varchar(255) DEFAULT NULL,
  34. `web_server_redirect_uri` varchar(255) DEFAULT NULL,
  35. `authorities` varchar(255) DEFAULT NULL,
  36. `access_token_validity` int(11) DEFAULT NULL,
  37. `refresh_token_validity` int(11) DEFAULT NULL,
  38. `additional_information` varchar(4096) DEFAULT NULL,
  39. `autoapprove` varchar(255) DEFAULT NULL,
  40. PRIMARY KEY (`client_id`)
  41. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
  42. -- ----------------------------
  43. -- Table structure for users
  44. -- ----------------------------
  45. DROP TABLE IF EXISTS `users`;
  46. CREATE TABLE `users` (
  47. `username` varchar(50) NOT NULL,
  48. `password` varchar(100) NOT NULL,
  49. `enabled` tinyint(1) NOT NULL,
  50. PRIMARY KEY (`username`)
  51. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
  52. -- ----------------------------
  53. -- Table structure for oauth_code
  54. -- ----------------------------
  55. DROP TABLE IF EXISTS `oauth_code`;
  56. CREATE TABLE `oauth_code` (
  57. `code` varchar(255) DEFAULT NULL,
  58. `authentication` blob
  59. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

在之后演示的时候会看到这些表中的数据。这里可以看到我们并没有在数据库中创建相应的表来存放访问令牌、刷新令牌,这是因为我们之后的实现会把令牌信息使用JWT来传输,不会存放到数据库中。基本上所有的这些表都是可以自己扩展的,只需要继承实现Spring的一些既有类即可,这里不做展开。

下面,我们创建一个最核心的类用于配置授权服务器:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.server;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.core.io.ClassPathResource;
  6. import org.springframework.security.authentication.AuthenticationManager;
  7. import org.springframework.security.crypto.password.NoOpPasswordEncoder;
  8. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  9. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  10. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  11. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  12. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  13. import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
  14. import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
  15. import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
  16. import org.springframework.security.oauth2.provider.token.TokenEnhancer;
  17. import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
  18. import org.springframework.security.oauth2.provider.token.TokenStore;
  19. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
  20. import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
  21. import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
  22. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  23. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  24. import javax.sql.DataSource;
  25. import java.util.Arrays;
  26. @Configuration
  27. @EnableAuthorizationServer
  28. public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {
  29. @Autowired
  30. private DataSource dataSource;
  31. @Autowired
  32. private AuthenticationManager authenticationManager;
  33. /**
  34. * 代码1
  35. * @param clients
  36. * @throws Exception
  37. */
  38. @Override
  39. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  40. clients.jdbc(dataSource);
  41. }
  42. /**
  43. * 代码2
  44. * @param security
  45. * @throws Exception
  46. */
  47. @Override
  48. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  49. security.checkTokenAccess("permitAll()")
  50. .allowFormAuthenticationForClients().passwordEncoder(NoOpPasswordEncoder.getInstance());
  51. }
  52. /**
  53. * 代码3
  54. * @param endpoints
  55. * @throws Exception
  56. */
  57. @Override
  58. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  59. TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
  60. tokenEnhancerChain.setTokenEnhancers(
  61. Arrays.asList(tokenEnhancer(), jwtTokenEnhancer()));
  62. endpoints.approvalStore(approvalStore())
  63. .authorizationCodeServices(authorizationCodeServices())
  64. .tokenStore(tokenStore())
  65. .tokenEnhancer(tokenEnhancerChain)
  66. .authenticationManager(authenticationManager);
  67. }
  68. @Bean
  69. public AuthorizationCodeServices authorizationCodeServices() {
  70. return new JdbcAuthorizationCodeServices(dataSource);
  71. }
  72. @Bean
  73. public TokenStore tokenStore() {
  74. return new JwtTokenStore(jwtTokenEnhancer());
  75. }
  76. @Bean
  77. public JdbcApprovalStore approvalStore() {
  78. return new JdbcApprovalStore(dataSource);
  79. }
  80. @Bean
  81. public TokenEnhancer tokenEnhancer() {
  82. return new CustomTokenEnhancer();
  83. }
  84. @Bean
  85. protected JwtAccessTokenConverter jwtTokenEnhancer() {
  86. KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "mySecretKey".toCharArray());
  87. JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
  88. converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
  89. return converter;
  90. }
  91. /**
  92. * 代码4
  93. */
  94. @Configuration
  95. static class MvcConfig implements WebMvcConfigurer {
  96. @Override
  97. public void addViewControllers(ViewControllerRegistry registry) {
  98. registry.addViewController("login").setViewName("login");
  99. }
  100. }
  101. }

分析下这个类:

  1. 首先我们可以看到,我们需要通过注解@EnableAuthorizationServer来开启授权服务器
  2. 代码片段1中,我们配置了使用数据库来维护客户端信息,当然在各种Demo中我们经常看到的是在内存中维护客户端信息,通过配置直接写死在这里,对于实际的应用我们一般都会用数据库来维护这个信息,甚至还会建立一套工作流来允许客户端自己申请ClientID
  3. 代码片段2中,针对授权服务器的安全,我们干了两个事情,首先打开了验证Token的访问权限(以便之后我们演示),然后允许ClientSecret明文方式保存并且可以通过表单提交(而不仅仅是Basic Auth方式提交),之后会演示到这个
  4. 代码片段3中,我们干了几个事情:
    • 配置我们的Token存放方式不是内存方式、不是数据库方式、不是Redis方式而是JWT方式,JWT是Json Web Token缩写也就是使用JSON数据格式包装的Token,由.句号把整个JWT分隔为头、数据体、签名三部分,JWT保存Token虽然易于使用但是不是那么安全,一般用于内部,并且需要走HTTPS+配置比较短的失效时间
    • 配置了JWT Token的非对称加密来进行签名
    • 配置了一个自定义的Token增强器,把更多信息放入Token中
    • 配置了使用JDBC数据库方式来保存用户的授权批准记录
  5. 代码片段4中,我们配置了登录页面的视图信息(其实可以独立一个配置类更规范)

针对刚才的代码,我们需要补充一些东西到资源目录下,首先需要在资源目录下创建一个templates文件夹然后创建一个login.html登录模板:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org" class="uk-height-1-1">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>OAuth2 Demo</title>
  6. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.26.3/css/uikit.gradient.min.css"/>
  7. </head>
  8. <body class="uk-height-1-1">
  9. <div class="uk-vertical-align uk-text-center uk-height-1-1">
  10. <div class="uk-vertical-align-middle" style="width: 250px;">
  11. <h1>Login Form</h1>
  12. <p class="uk-text-danger" th:if="${param.error}">
  13. 用户名或密码错误...
  14. </p>
  15. <form class="uk-panel uk-panel-box uk-form" method="post" th:action="@{/login}">
  16. <div class="uk-form-row">
  17. <input class="uk-width-1-1 uk-form-large" type="text" placeholder="Username" name="username"
  18. value="reader"/>
  19. </div>
  20. <div class="uk-form-row">
  21. <input class="uk-width-1-1 uk-form-large" type="password" placeholder="Password" name="password"
  22. value="reader"/>
  23. </div>
  24. <div class="uk-form-row">
  25. <button class="uk-width-1-1 uk-button uk-button-primary uk-button-large">Login</button>
  26. </div>
  27. </form>
  28. </div>
  29. </div>
  30. </body>
  31. </html>

然后,我们需要使用keytool工具生成密钥,把密钥文件jks保存到目录下,然后还要导出一个公钥留作以后使用。刚才在代码中我们还用到了一个自定义的Token增强器,实现如下:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.server;
  2. import org.springframework.security.core.Authentication;
  3. import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
  4. import org.springframework.security.oauth2.common.OAuth2AccessToken;
  5. import org.springframework.security.oauth2.provider.OAuth2Authentication;
  6. import org.springframework.security.oauth2.provider.token.TokenEnhancer;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. public class CustomTokenEnhancer implements TokenEnhancer {
  10. @Override
  11. public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
  12. Authentication userAuthentication = authentication.getUserAuthentication();
  13. if (userAuthentication != null) {
  14. Object principal = authentication.getUserAuthentication().getPrincipal();
  15. Map<String, Object> additionalInfo = new HashMap<>();
  16. additionalInfo.put("userDetails", principal);
  17. ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
  18. }
  19. return accessToken;
  20. }
  21. }

这段代码非常简单,就是把用户信息以userDetails这个Key存放到Token中去(如果授权模式是客户端模式这段代码无效,因为和用户没关系)。这是一个常见需求,默认情况下Token中只会有用户名这样的基本信息,我们往往需要把有关用户的更多信息返回给客户端(在实际应用中你可能会从数据库或外部服务查询更多的用户信息加入到JWT Token中去),这个时候就可以自定义增强器来丰富Token的内容。

到此授权服务器的核心配置已经完成,现在我们再来实现一下安全方面的配置:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.server;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.authentication.AuthenticationManager;
  6. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  9. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  10. import javax.sql.DataSource;
  11. @Configuration
  12. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  13. @Autowired
  14. private DataSource dataSource;
  15. @Override
  16. @Bean
  17. public AuthenticationManager authenticationManagerBean() throws Exception {
  18. return super.authenticationManagerBean();
  19. }
  20. @Override
  21. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  22. auth.jdbcAuthentication()
  23. .dataSource(dataSource)
  24. .passwordEncoder(new BCryptPasswordEncoder());
  25. }
  26. @Override
  27. protected void configure(HttpSecurity http) throws Exception {
  28. http.authorizeRequests()
  29. .antMatchers("/login", "/oauth/authorize")
  30. .permitAll()
  31. .anyRequest().authenticated()
  32. .and()
  33. .formLogin().loginPage("/login");
  34. }
  35. }

这里我们主要做了两个事情:

  1. 配置用户账户的认证方式,显然,我们把用户存在了数据库中希望配置JDBC的方式,此外,我们还配置了使用BCryptPasswordEncoder加密来保存用户的密码(生产环境的用户密码肯定不能是明文保存)
  2. 开放/login和/oauth/authorize两个路径的匿名访问,前者用于登录,后者用于换授权码,这两个端点访问的时候都在登录之前

最后配置一个主程序:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.server;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class OAuth2ServerApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(OAuth2ServerApplication.class, args);
  8. }
  9. }

至此,授权服务器的配置完成。

搭建资源服务器

先来创建项目:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://maven.apache.org/POM/4.0.0"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>springsecurity101</artifactId>
  7. <groupId>me.josephzhu</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>springsecurity101-cloud-oauth2-userservice</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-oauth2</artifactId>
  16. </dependency>
  17. </dependencies>
  18. </project>

配置及其简单,声明资源服务端口8081

  1. server:
  2. port: 8081

还记得在资源文件夹下放我们之前通过密钥导出的公钥文件,类似:

  1. -----BEGIN PUBLIC KEY-----
  2. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwR84LFHwnK5GXErnwkmD
  3. mPOJl4CSTtYXCqmCtlbF+5qVOosu0YsM2DsrC9O2gun6wVFKkWYiMoBSjsNMSI3Z
  4. w5JYgh+ldHvA+MIex2QXfOZx920M1fPUiuUPgmnTFS+Z3lmK3/T6jJnmciUPY1pe
  5. h4MXL6YzeI0q4W9xNBBeKT6FDGpduc0FC3OlXHfLbVOThKmAUpAWFDwf9/uUA//l
  6. 3PLchmV6VwTcUaaHp5W8Af/GU4lPGZbTAqOxzB9ukisPFuO1DikacPhrOQgdxtqk
  7. LciRTa884uQnkFwSguOEUYf3ni8GNRJauIuW0rVXhMOs78pKvCKmo53M0tqeC6ul
  8. +QIDAQAB
  9. -----END PUBLIC KEY-----

先来创建一个可以匿名访问的接口GET /hello:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.userservice;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. public class HelloController {
  6. @GetMapping("hello")
  7. public String hello() {
  8. return "Hello";
  9. }
  10. }

再来创建一个需要登录+授权才能访问到的一些接口:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.userservice;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.security.access.prepost.PreAuthorize;
  4. import org.springframework.security.oauth2.common.OAuth2AccessToken;
  5. import org.springframework.security.oauth2.provider.OAuth2Authentication;
  6. import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
  7. import org.springframework.security.oauth2.provider.token.TokenStore;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. @RestController
  13. @RequestMapping("user")
  14. public class UserController {
  15. @Autowired
  16. private TokenStore tokenStore;
  17. @PreAuthorize("hasAuthority('READ') or hasAuthority('WRITE')")
  18. @GetMapping("name")
  19. public String name(OAuth2Authentication authentication) {
  20. return authentication.getName();
  21. }
  22. @PreAuthorize("hasAuthority('READ') or hasAuthority('WRITE')")
  23. @GetMapping
  24. public OAuth2Authentication read(OAuth2Authentication authentication) {
  25. return authentication;
  26. }
  27. @PreAuthorize("hasAuthority('WRITE')")
  28. @PostMapping
  29. public Object write(OAuth2Authentication authentication) {
  30. OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
  31. OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
  32. return accessToken.getAdditionalInformation().getOrDefault("userDetails", null);
  33. }
  34. }

这里我们配置了三个接口,并且通过@PreAuthorize在方法执行前进行权限控制:

  1. GET /user/name接口读写权限都可以访问
  2. GET /user接口读写权限都可以访问,返回整个OAuth2Authentication
  3. POST /user接口只有写权限可以访问,返回之前的CustomTokenEnhancer加入到Token中的额外信息,Key是userDetails,这里也演示了使用TokenStore来解析Token的方式

下面我们来创建核心的资源服务器配置类:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.userservice;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.core.io.ClassPathResource;
  5. import org.springframework.core.io.Resource;
  6. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  9. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  10. import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  11. import org.springframework.security.oauth2.provider.token.TokenStore;
  12. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
  13. import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
  14. import org.springframework.util.FileCopyUtils;
  15. import java.io.IOException;
  16. @Configuration
  17. @EnableResourceServer
  18. @EnableGlobalMethodSecurity(prePostEnabled = true)
  19. public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  20. /**
  21. * 代码1
  22. * @param resources
  23. * @throws Exception
  24. */
  25. @Override
  26. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  27. resources.resourceId("foo").tokenStore(tokenStore());
  28. }
  29. @Bean
  30. public TokenStore tokenStore() {
  31. return new JwtTokenStore(jwtAccessTokenConverter());
  32. }
  33. @Bean
  34. protected JwtAccessTokenConverter jwtAccessTokenConverter() {
  35. JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
  36. Resource resource = new ClassPathResource("public.cert");
  37. String publicKey = null;
  38. try {
  39. publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. converter.setVerifierKey(publicKey);
  44. return converter;
  45. }
  46. /**
  47. * 代码2
  48. * @param http
  49. * @throws Exception
  50. */
  51. @Override
  52. public void configure(HttpSecurity http) throws Exception {
  53. http.authorizeRequests()
  54. .antMatchers("/user/**").authenticated()
  55. .anyRequest().permitAll();
  56. }
  57. }

这里我们干了四件事情:

  1. @EnableResourceServer启用资源服务器
  2. @EnableGlobalMethodSecurity(prePostEnabled = true)启用方法注解方式来进行权限控制
  3. 代码1,声明了资源服务器的ID是foo,声明了资源服务器的TokenStore是JWT以及公钥
  4. 代码2,配置了除了/user路径之外的请求可以匿名访问

我们想一下,如果授权服务器产生Token的话,资源服务器必须是要有一种办法来验证Token的,如果是非JWT的方式,我们可以这么办:

  1. Token可以保存在数据库或Redis中,资源服务器和授权服务器共享底层的TokenStore来验证
  2. 资源服务器可以使用RemoteTokenServices来从授权服务器的/oauth/check_token端点进行Token校验(还记得吗,我们之前开放过这个端口)

现在我们使用的是不落地的JWT方式+非对称加密,需要通过本地公钥进行验证,因此在这里我们配置了公钥的路径。

最后创建一个启动类:

  1. package me.josephzhu.springsecurity101.cloud.oauth2.userservice;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class UserServiceApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(UserServiceApplication.class, args);
  8. }
  9. }

至此,资源服务器配置完成,我们还在资源服务器中分别建了两个控制器,用于测试匿名访问和收到资源服务器权限保护的资源。

初始化数据配置

现在我们来看一下如何配置数据库实现:

  1. 两个用户,读用户reader具有读权限,写用户writer具有读写权限
  2. 两个权限,读和写
  3. 三个客户端:
    • userservice1这个客户端使用密码凭证模式
    • userservice2这个客户端使用客户端模式
    • userservice3这个客户端使用授权码模式

首先是oauth_client_details表:

  1. INSERT INTO `oauth_client_details` VALUES ('userservice1', 'foo', '1234', 'FOO', 'password,refresh_token', '', 'READ,WRITE', 7200, NULL, NULL, 'true');
  2. INSERT INTO `oauth_client_details` VALUES ('userservice2', 'foo', '1234', 'FOO', 'client_credentials,refresh_token', '', 'READ,WRITE', 7200, NULL, NULL, 'true');
  3. INSERT INTO `oauth_client_details` VALUES ('userservice3', 'foo', '1234', 'FOO', 'authorization_code,refresh_token', 'https://baidu.com', 'READ,WRITE', 7200, NULL, NULL, 'false');

如之前所说,这里配置了三条记录:

  1. 它们能使用的资源ID都是foo,对应我们资源服务器userservice的配置
  2. 它们的授权范围都是FOO,可以拿到的权限是读写(但对于用户关联的模式,最终拿到的权限还取决于客户端权限和用户权限的交集)
  3. 通过grant_types字段配置了支持的不同的授权模式,这里我们为了便于测试观察给三个客户端各自配置了一个模式,你完全可以为一个客户端配置支持OAuth2.0的那四种模式
  4. userservice1和2我们配置了用户自动批准授权(不会弹出一个页面要求用户进行授权那种)

然后是authorities表,其中我们配置了两条记录,配置reader用户具有读权限,writer用户具有写权限:

  1. INSERT INTO `authorities` VALUES ('reader', 'READ');
  2. INSERT INTO `authorities` VALUES ('writer', 'READ,WRITE');

最后是users表配置了两个用户的账户名和密码:

  1. INSERT INTO `users` VALUES ('reader', '$2a$04$C6pPJvC1v6.enW6ZZxX.luTdpSI/1gcgTVN7LhvQV6l/AfmzNU/3i', 1);
  2. INSERT INTO `users` VALUES ('writer', '$2a$04$M9t2oVs3/VIreBMocOujqOaB/oziWL0SnlWdt8hV4YnlhQrORA0fS', 1);

还记得吗,密码我们使用的是BCryptPasswordEncoder加密(准确说是哈希),可以使用一些在线工具进行哈希

演示三种授权模式

客户端模式

POST请求地址:

http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=userservice2&client_secret=1234

如下图所示,直接可以拿到Token:



这里注意到并没有提供刷新令牌,刷新令牌用于避免访问令牌失效后还需要用户登录,客户端模式没有用户概念,没有刷新令牌。我们把得到的Token粘贴到https://jwt.io/#debugger-io查看:



如果粘贴进去公钥的话还可以看到Token签名验证成功:



也可以试一下,如果我们的授权服务器没有allowFormAuthenticationForClients的话,客户端的凭证需要通过Basic Auth传而不是Post过去:



还可以访问授权服务器来校验Token:

http://localhost:8080/oauth/check_token?client_id=userservice1&client_secret=1234&token=...

得到如下结果:

密码凭证模式

POST请求地址:

http://localhost:8080/oauth/token?grant_type=password&client_id=userservice1&client_secret=1234&username=writer&password=writer

得到如下图结果:



再看下Token中的信息:



可以看到果然包含了我们TokenEnhancer加入的userDetails自定义信息。

授权码模式

首先打开浏览器访问地址:

http://localhost:8080/oauth/authorize?response_type=code&client_id=userservice3&redirect_uri=https://baidu.com

注意,我们客户端跳转地址需要和数据库中配置的一致,百度的URL我们之前已经在数据库中有配置了,访问后页面会跳转到登录界面,使用reader:reader登录:



由于我们数据库中设置的是禁用自动批准授权的模式,所以登录后来到了批准界面:



点击同意后可以看到数据库中也会产生授权通过记录:



然后我们可以看到浏览器转到了百度并且提供给了我们授权码:

https://www.baidu.com/?code=O8RiCe

数据库中也记录了授权码:



然后POST访问:http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=userservice3&client_secret=1234&code=O8RiCe&redirect_uri=https://baidu.com

可以得到访问令牌:



虽然userservice3客户端可以有READ和WRITE权限,但是我们登录的用户reader只有READ权限,最后拿到的权限只有READ

演示资源服务器权限控制

首先我们可以测试一下我们的安全配置,访问/hello端点不需要认证可以匿名访问:



访问/user需要身份认证:



不管以哪种模式拿到访问令牌,我们用具有读权限的访问令牌GET访问资源服务器如下地址(请求头加入Authorization: Bearer XXXXXXXXXX,其中XXXXXXXXXX代表Token):

http://localhost:8081/user/

可以得到如下结果:



以POST方式访问http://localhost:8081/user/显然是失败的:



我们换一个具有读写权限的令牌来试试:



果然可以成功,说明资源服务器的权限控制有效。

搭建客户端程序

在之前,我们使用的是裸HTTP请求手动的方式来申请和使用令牌,最后我们来搭建一个OAuth客户端程序自动实现这个过程:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://maven.apache.org/POM/4.0.0"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>springsecurity101</artifactId>
  7. <groupId>me.josephzhu</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <artifactId>springsecurity101-cloud-oauth2-client</artifactId>
  11. <modelVersion>4.0.0</modelVersion>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-oauth2</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-web</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  24. </dependency>
  25. </dependencies>
  26. </project>

配置文件如下:

  1. server:
  2. port: 8082
  3. servlet:
  4. context-path: /ui
  5. security:
  6. oauth2:
  7. client:
  8. clientId: userservice3
  9. clientSecret: 1234
  10. accessTokenUri: http://localhost:8080/oauth/token
  11. userAuthorizationUri: http://localhost:8080/oauth/authorize
  12. scope: FOO
  13. resource:
  14. jwt:
  15. key-value: |
  16. -----BEGIN PUBLIC KEY-----
  17. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwR84LFHwnK5GXErnwkmD
  18. mPOJl4CSTtYXCqmCtlbF+5qVOosu0YsM2DsrC9O2gun6wVFKkWYiMoBSjsNMSI3Z
  19. w5JYgh+ldHvA+MIex2QXfOZx920M1fPUiuUPgmnTFS+Z3lmK3/T6jJnmciUPY1pe
  20. h4MXL6YzeI0q4W9xNBBeKT6FDGpduc0FC3OlXHfLbVOThKmAUpAWFDwf9/uUA//l
  21. 3PLchmV6VwTcUaaHp5W8Af/GU4lPGZbTAqOxzB9ukisPFuO1DikacPhrOQgdxtqk
  22. LciRTa884uQnkFwSguOEUYf3ni8GNRJauIuW0rVXhMOs78pKvCKmo53M0tqeC6ul
  23. +QIDAQAB
  24. -----END PUBLIC KEY-----
  25. spring:
  26. thymeleaf:
  27. cache: false
  28. #logging:
  29. # level:
  30. # ROOT: DEBUG

客户端项目端口8082,几个需要说明的地方:

  1. 本地测试的时候一个坑就是我们需要配置context-path否则可能会出现客户端和授权服务器服务端Cookie干扰导致CSRF防御触发的问题,这个问题出现后程序没有任何错误日志输出,只有开启DEBUG模式后才能看到DEBUG日志里有提示,这个问题非常难以排查,也不知道Spring为啥不把这个信息作为WARN级别
  2. 作为OAuth客户端,我们需要配置OAuth服务端获取令牌的地址以及授权(获取授权码)的地址,以及需要配置客户端的ID和密码,以及授权范围
  3. 因为使用的是JWT Token,我们需要配置公钥(当然,如果不在这里直接配置公钥的话也可以配置公钥从授权服务器服务端获取)

首先实现MVC的配置:

  1. package me.josephzhu.springsecurity101.cloud.auth.client;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.context.request.RequestContextListener;
  5. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  6. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  8. @Configuration
  9. @EnableWebMvc
  10. public class WebMvcConfig implements WebMvcConfigurer {
  11. @Bean
  12. public RequestContextListener requestContextListener() {
  13. return new RequestContextListener();
  14. }
  15. @Override
  16. public void addViewControllers(ViewControllerRegistry registry) {
  17. registry.addViewController("/")
  18. .setViewName("forward:/index");
  19. registry.addViewController("/index");
  20. }
  21. }

这里做了两个事情:

  1. 配置RequestContextListener用于启用session scope的Bean
  2. 配置了index路径的首页Controller

    然后实现安全方面的配置:
  1. package me.josephzhu.springsecurity101.cloud.auth.client;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.core.annotation.Order;
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  5. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  6. @Configuration
  7. @Order(200)
  8. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  9. @Override
  10. protected void configure(HttpSecurity http) throws Exception {
  11. http
  12. .authorizeRequests()
  13. .antMatchers("/", "/login**")
  14. .permitAll()
  15. .anyRequest()
  16. .authenticated();
  17. }
  18. }

这里我们实现的是/路径和/login路径允许访问,其它路径需要身份认证后才能访问。

然后我们来创建一个控制器:

  1. package me.josephzhu.springsecurity101.cloud.auth.client;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.http.ResponseEntity;
  4. import org.springframework.security.oauth2.client.OAuth2RestTemplate;
  5. import org.springframework.security.oauth2.provider.OAuth2Authentication;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.servlet.ModelAndView;
  9. @RestController
  10. public class DemoController {
  11. @Autowired
  12. OAuth2RestTemplate restTemplate;
  13. @GetMapping("/securedPage")
  14. public ModelAndView securedPage(OAuth2Authentication authentication) {
  15. return new ModelAndView("securedPage").addObject("authentication", authentication);
  16. }
  17. @GetMapping("/remoteCall")
  18. public String remoteCall() {
  19. ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8081/user/name", String.class);
  20. return responseEntity.getBody();
  21. }
  22. }

这里可以看到:

  1. 对于securedPage,我们把用户信息作为模型传入了视图
  2. 我们引入了OAuth2RestTemplate,在登录后就可以使用凭据直接从资源服务器拿资源,不需要繁琐的实现获得访问令牌,在请求头里加入访问令牌的过程

    在开始的时候我们定义了index页面,模板如下:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5. <title>Spring Security SSO Client</title>
  6. <link rel="stylesheet"
  7. href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
  8. </head>
  9. <body>
  10. <div class="container">
  11. <div class="col-sm-12">
  12. <h1>Spring Security SSO Client</h1>
  13. <a class="btn btn-primary" href="securedPage">Login</a>
  14. </div>
  15. </div>
  16. </body>
  17. </html>

现在又定义了securedPage页面,模板如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5. <title>Spring Security SSO Client</title>
  6. <link rel="stylesheet"
  7. href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
  8. </head>
  9. <body>
  10. <div class="container">
  11. <div class="col-sm-12">
  12. <h1>Secured Page</h1>
  13. Welcome, <span th:text="${authentication.name}">Name</span>
  14. <br/>
  15. Your authorities are <span th:text="${authentication.authorities}">authorities</span>
  16. </div>
  17. </div>
  18. </body>
  19. </html>

接下去最关键的一步是启用@EnableOAuth2Sso,这个注解包含了@EnableOAuth2Client:

  1. package me.josephzhu.springsecurity101.cloud.auth.client;
  2. import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.oauth2.client.OAuth2ClientContext;
  6. import org.springframework.security.oauth2.client.OAuth2RestTemplate;
  7. import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
  8. @Configuration
  9. @EnableOAuth2Sso
  10. public class OAuthClientConfig {
  11. @Bean
  12. public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oAuth2ClientContext,
  13. OAuth2ProtectedResourceDetails details) {
  14. return new OAuth2RestTemplate(details, oAuth2ClientContext);
  15. }
  16. }

此外,我们这里还定义了OAuth2RestTemplate,网上一些比较老的资料给出的是手动读取配置文件来实现,最新版本已经可以自动注入OAuth2ProtectedResourceDetails。

最后是启动类:

  1. package me.josephzhu.springsecurity101.cloud.auth.client;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class OAuth2ClientApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(OAuth2ClientApplication.class, args);
  8. }
  9. }

演示单点登录

启动客户端项目,打开浏览器访问http://localhost:8082/ui/securedPage:

可以看到页面自动转到了授权服务器的登录页面:



点击登录后出现如下错误:



显然,之前我们数据库中配置的redirect_uri是百度首页,需要包含我们的客户端地址,我们把字段内容修改为4个地址:

https://baidu.com,http://localhost:8082/ui/login,http://localhost:8083/ui/login,http://localhost:8082/ui/remoteCall

刷新页面,登录成功:



我们再启动另一个客户端网站,端口改为8083,然后访问同样地址:



可以看到同样是登录状态,SSO单点登录测试成功,是不是很方便。

演示客户端请求资源服务器资源

最后,我们来访问一下remoteCall接口:



可以看到输出了用户名,对应的资源服务器服务端是:

  1. @PreAuthorize("hasAuthority('READ') or hasAuthority('WRITE')")
  2. @GetMapping("name")
  3. public String name(OAuth2Authentication authentication) {
  4. return authentication.getName();
  5. }

换一个用户登录试试:

总结

本文以OAuth 2.0这个维度来小窥了一下Spring Security的功能,介绍了OAuth 2.0的基本概念,体验了三种常用模式,也使用Spring Security实现了OAuth 2.0的三个组件,客户端、授权服务器和资源服务器,实现了资源服务器的权限控制,最后还使用客户端测试了一下SSO和OAuth2RestTemplate使用,所有代码见我的Github https://github.com/JosephZhu1983/SpringSecurity101 ,希望本文对你有用。

朱晔和你聊Spring系列S1E10:强大且复杂的Spring Security(含OAuth2三角色+三模式完整例子)的更多相关文章

  1. Spring系列9:基于注解的Spring容器配置

    写在前面 前面几篇中我们说过,Spring容器支持3种方式进行bean定义信息的配置,现在具体说明下: XML:bean的定义和依赖都在xml文件中配置,比较繁杂. Annotation-based ...

  2. Spring Cloud(6):保护微服务(Security) - OAuth2.0

    OAuth2是一个授权(Authorization)协议.我们要和Spring Security的认证(Authentication)区别开来,认证(Authentication)证明的你是不是这个人 ...

  3. Spring 系列: Spring 框架简介 -7个部分

    Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...

  4. Spring 系列: Spring 框架简介

    Spring AOP 和 IOC 容器入门(转载) 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级的.强壮的 J2EE 应用程序.dev ...

  5. Spring 系列: Spring 框架简介(转载)

    Spring 系列: Spring 框架简介 http://www.ibm.com/developerworks/cn/java/wa-spring1/ Spring AOP 和 IOC 容器入门 在 ...

  6. [JavaEE] IBM - Spring 系列: Spring 框架简介

    Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级的.强壮的 J2EE 应用程序.develop ...

  7. 朱晔和你聊Spring系列S1E8:凑活着用的Spring Cloud(含一个实际业务贯穿所有组件的完整例子)

    本文会以一个简单而完整的业务来阐述Spring Cloud Finchley.RELEASE版本常用组件的使用.如下图所示,本文会覆盖的组件有: Spring Cloud Netflix Zuul网关 ...

  8. 朱晔和你聊Spring系列S1E2:SpringBoot并不神秘

    朱晔和你聊Spring系列S1E2:SpringBoot并不神秘 [编辑器丢失了所有代码的高亮,建议查看PDF格式文档] 文本我们会一步一步做一个例子来看看SpringBoot的自动配置是如何实现的, ...

  9. 朱晔和你聊Spring系列S1E1:聊聊Spring家族的几大件

    朱晔和你聊Spring系列S1E1:聊聊Spring家族的几大件 [下载本文PDF进行阅读] Spring家族很庞大,从最早先出现的服务于企业级程序开发的Core.安全方面的Security.到后来的 ...

随机推荐

  1. Centos 中无法上网的问题

    我是 Centos 最小化安装的,安装网后 Centos 竟然无法上网...有点奇葩, 应该是网卡没有激活的问题了,下面是解决的过程 查看网卡 ip addr 其中 lo 是 Loop back ad ...

  2. SQL 中事务的分类

    先讲下事务执行流程: BEGIN和COMMIT PRINT @@TRANCOUNT --@@TRANCOUNT统计事务数量 BEGIN TRAN PRINT @@TRANCOUNT BEGIN TRA ...

  3. C#核心基础--类的声明

    C#核心基础--类的声明 类是使用关键字 class 声明的,如下面的示例所示: 访问修饰符 class 类名 { //类成员: // Methods, properties, fields, eve ...

  4. js获取地址栏中的数据

    window.location.href:设置或获取整个 URL 为字符串window.location.pathname:设置或获取对象指定的文件名或路径window.location.search ...

  5. mysql 数据库 命令行的操作——对库的操作

    1.查看所有数据库 show databaese; 2.查看当前所用的数据库 show databases(): 3.切换数据库 use(数据库名): 4.创建数据库 create database ...

  6. 在MFC Dialog中显示cmd窗口

    打开Project -> Properties,在Build Events -> Post-Build Event里的Command Line中输入: editbin /SUBSYSTEM ...

  7. 详解 JSONP跨域请求的实现

          跨域问题是由于浏览器为了防止CSRF攻击(Cross-site request forgery跨站请求伪造),避免恶意攻击而带来的风险而采取的同源策略限制.当一个页面中使用XMLHTTPR ...

  8. 16.Python网络爬虫之Scrapy框架(CrawlSpider)

    引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法 ...

  9. 【漫画解读】HDFS存储原理

    根据Maneesh Varshney的漫画改编,以简洁易懂的漫画形式讲解HDFS存储机制与运行原理,非常适合Hadoop/HDFS初学者理解. 一.角色出演 如上图所示,HDFS存储相关角色与功能如下 ...

  10. E. Magic Stones CF 思维题

    E. Magic Stones time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...