从零开始的Spring Security Oauth2(一)

使用配置

1.简易的分为三个步骤

  • 配置资源服务器

  • 配置认证服务器

  • 配置spring security

2.oauth2根据使用场景不同,分成了4种模式

  • 授权码模式(authorization code)

  • 简化模式(implicit)

  • 密码模式(resource owner password credentials)

  • 客户端模式(client credentials)

以下重点讲解接口对接中常使用的密码模式(以下简称password模式)和客户端模式(以下简称client模式)。授权码模式使用到了回调地址,是最为复杂的方式,通常网站中经常出现的微博,qq第三方登录,都会采用这个形式。简化模式不常用。

项目准备

主要的maven依赖如下

 
  1. <!-- 注意是starter,自动配置 -->

  2. <dependency>

  3. <groupId>org.springframework.boot</groupId>

  4. <artifactId>spring-boot-starter-security</artifactId>

  5. </dependency>

  6. <!-- 不是starter,手动配置 -->

  7. <dependency>

  8. <groupId>org.springframework.security.oauth</groupId>

  9. <artifactId>spring-security-oauth2</artifactId>

  10. </dependency>

  11. <dependency>

  12. <groupId>org.springframework.boot</groupId>

  13. <artifactId>spring-boot-starter-web</artifactId>

  14. </dependency>

  15. <!-- 将token存储在redis中 -->

  16. <dependency>

  17. <groupId>org.springframework.boot</groupId>

  18. <artifactId>spring-boot-starter-data-redis</artifactId>

  19. </dependency>

我们给自己先定个目标,要干什么事?既然说到保护应用,那必须得先有一些资源,我们创建一个endpoint作为提供给外部的接口:

 
  1. @RestController

  2. public class TestEndpoints {

  3.  
  4. @GetMapping("/product/{id}")

  5. public String getProduct(@PathVariable String id) {

  6. //for debug

  7. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

  8. return "product id : " + id;

  9. }

  10.  
  11. @GetMapping("/order/{id}")

  12. public String getOrder(@PathVariable String id) {

  13. //for debug

  14. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

  15. return "order id : " + id;

  16. }

  17.  
  18. }

暴露一个商品查询接口,后续不做安全限制,一个订单查询接口,后续添加访问控制。

配置资源服务器和授权服务器

由于是两个oauth2的核心配置,我们放到一个配置类中。 为了方便下载代码直接运行,我这里将客户端信息放到了内存中,生产中可以配置到数据库中。token的存储一般选择使用Redis,一是性能比较好,二是自动过期的机制,符合token的特性。

 
  1. @Configuration

  2. public class OAuth2ServerConfig {

  3.  
  4. private static final String DEMO_RESOURCE_ID = "order";

  5.  
  6. @Configuration

  7. @EnableResourceServer

  8. protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

  9.  
  10. @Override

  11. public void configure(ResourceServerSecurityConfigurer resources) {

  12. resources.resourceId(DEMO_RESOURCE_ID).stateless(true);

  13. }

  14.  
  15. @Override

  16. public void configure(HttpSecurity http) throws Exception {

  17. // @formatter:off

  18. http

  19. // Since we want the protected resources to be accessible in the UI as well we need

  20. // session creation to be allowed (it's disabled by default in 2.0.6)

  21. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)

  22. .and()

  23. .requestMatchers().anyRequest()

  24. .and()

  25. .anonymous()

  26. .and()

  27. .authorizeRequests()

  28. // .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')")

  29. .antMatchers("/order/**").authenticated();//配置order访问控制,必须认证过后才可以访问

  30. // @formatter:on

  31. }

  32. }

  33.  
  34. @Configuration

  35. @EnableAuthorizationServer

  36. protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

  37.  
  38. @Autowired

  39. AuthenticationManager authenticationManager;

  40. @Autowired

  41. RedisConnectionFactory redisConnectionFactory;

  42.  
  43. @Override

  44. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

  45. //配置两个客户端,一个用于password认证一个用于client认证

  46. clients.inMemory().withClient("client_1")

  47. .resourceIds(DEMO_RESOURCE_ID)

  48. .authorizedGrantTypes("client_credentials", "refresh_token")

  49. .scopes("select")

  50. .authorities("client")

  51. .secret("123456")

  52. .and().withClient("client_2")

  53. .resourceIds(DEMO_RESOURCE_ID)

  54. .authorizedGrantTypes("password", "refresh_token")

  55. .scopes("select")

  56. .authorities("client")

  57. .secret("123456");

  58. }

  59.  
  60. @Override

  61. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

  62. endpoints

  63. .tokenStore(new RedisTokenStore(redisConnectionFactory))

  64. .authenticationManager(authenticationManager);

  65. }

  66.  
  67. @Override

  68. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {

  69. //允许表单认证

  70. oauthServer.allowFormAuthenticationForClients();

  71. }

  72.  
  73. }

  74.  
  75. }

spring security oauth2的认证思路

  • client模式,没有用户的概念,直接与认证服务器交互,用配置中的客户端信息去申请accessToken,客户端有自己的client_id,client_secret对应于用户的username,password,而客户端也拥有自己的authorities,当采取client模式认证时,对应的权限也就是客户端自己的authorities。

  • password模式,自己本身有一套用户体系,在认证时需要带上自己的用户名和密码,以及客户端的client_id,client_secret。此时,accessToken所包含的权限是用户本身的权限,而不是客户端的权限。

我对于两种模式的理解便是,如果你的系统已经有了一套用户体系,每个用户也有了一定的权限,可以采用password模式;如果仅仅是接口的对接,不考虑用户,则可以使用client模式。

配置spring security

在spring security的版本迭代中,产生了多种配置方式,建造者模式,适配器模式等等设计模式的使用,spring security内部的认证flow也是错综复杂,在我一开始学习ss也产生了不少困惑,总结了一下配置经验:使用了springboot之后,spring security其实是有不少自动配置的,我们可以仅仅修改自己需要的那一部分,并且遵循一个原则,直接覆盖最需要的那一部分。这一说法比较抽象,举个例子。比如配置内存中的用户认证器。有两种配置方式

planA:

 
  1. @Bean

  2. protected UserDetailsService userDetailsService(){

  3. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();

  4. manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());

  5. manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());

  6. return manager;

  7. }

planB:

 
  1. @Configuration

  2. @EnableWebSecurity

  3. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  4.  
  5. @Override

  6. protected void configure(AuthenticationManagerBuilder auth) throws Exception {

  7. auth.inMemoryAuthentication()

  8. .withUser("user_1").password("123456").authorities("USER")

  9. .and()

  10. .withUser("user_2").password("123456").authorities("USER");

  11. }

  12.  
  13. @Bean

  14. @Override

  15. public AuthenticationManager authenticationManagerBean() throws Exception {

  16. AuthenticationManager manager = super.authenticationManagerBean();

  17. return manager;

  18. }

  19. }

你最终都能得到配置在内存中的两个用户,前者是直接替换掉了容器中的UserDetailsService,这么做比较直观;后者是替换了AuthenticationManager,当然你还会在SecurityConfiguration 复写其他配置,这么配置最终会由一个委托者去认证。如果你熟悉spring security,会知道AuthenticationManager和AuthenticationProvider以及UserDetailsService的关系,他们都是顶级的接口,实现类之间错综复杂的聚合关系…配置方式千差万别,但理解清楚认证流程,知道各个实现类对应的职责才是掌握spring security的关键。

下面给出我最终的配置:

 
  1. @Configuration

  2. @EnableWebSecurity

  3. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  4.  
  5. @Bean

  6. @Override

  7. protected UserDetailsService userDetailsService(){

  8. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();

  9. manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());

  10. manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());

  11. return manager;

  12. }

  13.  
  14. @Override

  15. protected void configure(HttpSecurity http) throws Exception {

  16. // @formatter:off

  17. http

  18. .requestMatchers().anyRequest()

  19. .and()

  20. .authorizeRequests()

  21. .antMatchers("/oauth/*").permitAll();

  22. // @formatter:on

  23. }

  24. }

重点就是配置了一个UserDetailsService,和ClientDetailsService一样,为了方便运行,使用内存中的用户,实际项目中,一般使用的是数据库保存用户,具体的实现类可以使用JdbcDaoImpl或者JdbcUserDetailsManager。

获取token

进行如上配置之后,启动springboot应用就可以发现多了一些自动创建的endpoints:

 
  1. {[/oauth/authorize]}

  2. {[/oauth/authorize],methods=[POST]

  3. {[/oauth/token],methods=[GET]}

  4. {[/oauth/token],methods=[POST]}

  5. {[/oauth/check_token]}

  6. {[/oauth/error]}

重点关注一下/oauth/token,它是获取的token的endpoint。启动springboot应用之后,使用http工具访问 :

  • password模式:http://localhost:8080/oauth/token? username=user_1&password=123456& grant_type=password&scope=select& client_id=client_2&client_secret=123456,响应如下:
 
  1. {

  2. "access_token":"950a7cc9-5a8a-42c9-a693-40e817b1a4b0",

  3. "token_type":"bearer",

  4. "refresh_token":"773a0fcd-6023-45f8-8848-e141296cb3cb",

  5. "expires_in":27036,

  6. "scope":"select"

  7. }

  • client模式:http://localhost:8080/oauth/token? grant_type=client_credentials& scope=select& client_id=client_1& client_secret=123456,响应如下:
 
  1. {

  2. "access_token":"56465b41-429d-436c-ad8d-613d476ff322",

  3. "token_type":"bearer",

  4. "expires_in":25074,

  5. "scope":"select"

  6. }

在配置中,我们已经配置了对order资源的保护,如果直接访问:http://localhost:8080/order/1,会得到这样的响应:

 
  1. "error":"unauthorized",

  2. "error_description":"Full authentication is required to access this resource"

  3. }

(这样的错误响应可以通过重写配置来修改) 而对于未受保护的product资源 http://localhost:8080/product/1 则可以直接访问,得到响应 product id : 1

携带accessToken参数访问受保护的资源: 使用password模式获得的token: http://localhost:8080/order/1?access_token=950a7cc9-5a8a-42c9-a693-40e817b1a4b0 得到了之前匿名访问无法获取的资源: order id : 1

使用client模式获得的token: http://localhost:8080/order/1?access_token=56465b41-429d-436c-ad8d-613d476ff322 同上的响应 order id : 1

我们重点关注一下debug后,对资源访问时系统记录的用户认证信息,可以看到如下的debug信息

password模式:

password模式

client模式:

client模式

和我们的配置是一致的,仔细看可以发现两者的身份有些许的不同。想要查看更多的debug信息,可以选择下载demo代码自己查看,为了方便读者调试和验证,我去除了很多复杂的特性,基本实现了一个最简配置,涉及到数据库的地方也尽量配置到了内存中,这点记住在实际使用时一定要修改。

到这儿,一个简单的oauth2入门示例就完成了,一个简单的配置教程。token的工作原理是什么,它包含了哪些信息?spring内部如何对身份信息进行验证?以及上述的配置到底影响了什么?这些内容会放到后面的文章中去分析。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值