0. 前言

  之前帐号认证用过自己写的进行匹配,现在要学会使用标准了。准备了解和使用这个OAuth2.0协议。

1. 配置

1.1 配置pom.xml

  有些可能会用不到,我把我项目中用到的所有包都贴出来。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-security</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.security.oauth</groupId>
  11. <artifactId>spring-security-oauth2</artifactId>
  12. <version>2.3.3.RELEASE</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-web</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.mybatis.spring.boot</groupId>
  20. <artifactId>mybatis-spring-boot-starter</artifactId>
  21. <version>1.3.2</version>
  22. </dependency>
  23. <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
  24. <dependency>
  25. <groupId>com.github.pagehelper</groupId>
  26. <artifactId>pagehelper-spring-boot-starter</artifactId>
  27. <version>1.2.5</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.cloud</groupId>
  31. <artifactId>spring-cloud-starter-oauth2</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.cloud</groupId>
  35. <artifactId>spring-cloud-starter-security</artifactId>
  36. </dependency>
  37.  
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-devtools</artifactId>
  41. <scope>runtime</scope>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.postgresql</groupId>
  45. <artifactId>postgresql</artifactId>
  46. <scope>runtime</scope>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. <scope>test</scope>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.springframework.security</groupId>
  55. <artifactId>spring-security-test</artifactId>
  56. <scope>test</scope>
  57. </dependency>

1.2 配置application.properties

  1. #server
  2. server.port=8080
  3. server.servlet.session.timeout=2520000
  4. #redis
  5. spring.redis.database=0
  6. spring.redis.host=172.16.23.203
  7. spring.redis.port=6379
  8. spring.redis.password=
  9. spring.redis.jedis.pool.max-active=8
  10. spring.redis.jedis.pool.max-wait=60
  11. spring.redis.jedis.pool.max-idle=8
  12. spring.redis.jedis.pool.min-idle=0
  13. spring.redis.timeout=10000

1.3 资源服务器配置

  1. /**
  2. * OAuth 资源服务器配置
  3. * @author
  4. * @date 2018-05-29
  5. */
  6. @Configuration
  7. @EnableResourceServer
  8. public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  9.  
  10. private static final String DEMO_RESOURCE_ID = "order";
  11.  
  12. @Override
  13. public void configure(ResourceServerSecurityConfigurer resources) {
  14. resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
  15. }
  16.  
  17. @Override
  18. public void configure(HttpSecurity http) throws Exception {
  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. http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
  22. .and()
  23. .requestMatchers().anyRequest()
  24. .and()
  25. .anonymous()
  26. .and()
  27. .authorizeRequests()
  28. .antMatchers("/order/**").authenticated();//配置order访问控制,必须认证过后才可以访问
  29. }
  30. }

1.4 授权服务器配置

  1. /**
  2. * OAuth 授权服务器配置
  3. * @author
  4. * @date 2018-05-29
  5. */
  6. @Configuration
  7. @EnableAuthorizationServer
  8. public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
  9.  
  10. private static final String DEMO_RESOURCE_ID = "order";
  11.  
  12. @Autowired
  13. AuthenticationManager authenticationManager;
  14. @Autowired
  15. RedisConnectionFactory redisConnectionFactory;
  16.  
  17. @Override
  18. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  19. String finalSecret = "{bcrypt}"+new BCryptPasswordEncoder().encode("123456");
  20. //配置两个客户端,一个用于password认证一个用于client认证
  21. clients.inMemory()
  22. .withClient("client_1")
  23. .resourceIds(DEMO_RESOURCE_ID)
  24. .authorizedGrantTypes("client_credentials", "refresh_token")
  25. .scopes("select")
  26. .authorities("oauth2")
  27. .secret(finalSecret)
  28. .and()
  29. .withClient("client_2")
  30. .resourceIds(DEMO_RESOURCE_ID)
  31. .authorizedGrantTypes("password", "refresh_token")
  32. .scopes("select")
  33. .authorities("oauth2")
  34. .secret(finalSecret);
  35. }
  36.  
  37. @Override
  38. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  39. endpoints
  40. .tokenStore(new RedisTokenStore(redisConnectionFactory))
  41. .authenticationManager(authenticationManager)
  42. .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
  43. }
  44.  
  45. @Override
  46. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  47. //允许表单认证
  48. oauthServer.allowFormAuthenticationForClients();
  49. }
  50. }

1.5 Spring Security配置

  1. /**
  2. * Spring-Security 配置<br>
  3. * 具体参考: https://github.com/lexburner/oauth2-demo
  4. * @author
  5. * @date 2018-05-28
  6. */
  7. @Configuration
  8. @EnableWebSecurity
  9. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  10.  
  11. @Bean
  12. @Override
  13. protected UserDetailsService userDetailsService(){
  14. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  15. BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
  16. String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("123456");
  17. manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build());
  18. finalPassword = "{noop}123456";
  19. manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("USER").build());
  20. return manager;
  21. }
  22.  
  23. @Override
  24. protected void configure(HttpSecurity http) throws Exception {
  25. http
  26. .requestMatchers().anyRequest()
  27. .and()
  28. .authorizeRequests()
  29. .antMatchers("/oauth/*").permitAll();
  30. }
  31.  
  32. /**
  33. * Spring Boot 2 配置,这里要bean 注入
  34. */
  35. @Bean
  36. @Override
  37. public AuthenticationManager authenticationManagerBean() throws Exception {
  38. AuthenticationManager manager = super.authenticationManagerBean();
  39. return manager;
  40. }
  41.  
  42. @Bean
  43. PasswordEncoder passwordEncoder() {
  44. return PasswordEncoderFactories.createDelegatingPasswordEncoder();
  45. }

1.6 定义一个资源点

  1. @RestController
  2. @RequestMapping(value="/")
  3. public class TestController {
  4.  
  5. @RequestMapping(value="order/demo")
  6. public YYModel getDemo() {
  7. Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  8. System.out.println(auth);
  9. YYModel yy = new YYModel();
  10. yy.setYy("中文");
  11. yy.setZz(3);
  12. return yy;
  13. }
  14.  
  15. @GetMapping("/test")
  16. public String getTest() {
  17. YYModel yy = new YYModel();
  18. yy.setYy("中文");
  19. yy.setZz(3);
  20. return yy.toJSONString();
  21. }
  22. }

2. 工具测试

  

  

  参考: http://blog.didispace.com/spring-security-oauth2-xjf-1/

Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1的更多相关文章

  1. Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式2

    0.前言 经过前面一小节已经基本配置好了基于SpringBoot+SpringSecurity+OAuth2.0的环境.这一小节主要对一些写固定InMemory的User和Client进行扩展.实现动 ...

  2. Spring Boot 2(一):Spring Boot 2.0新特性

    Spring Boot 2(一):Spring Boot 2.0新特性 Spring Boot依赖于Spring,而Spring Cloud又依赖于Spring Boot,因此Spring Boot2 ...

  3. Spring Boot 多站点利用 Redis 实现 Session 共享

    如何在不同站点(web服务进程)之间共享会话 Session 呢,原理很简单,就是把这个 Session 独立存储在一个地方,所有的站点都从这个地方读取 Session. 通常我们使用 Redis 来 ...

  4. spring boot 是如何利用jackson进行序列化的?

    接上一篇:spring boot 是如何利用jackson进行反序列化的? @RestController public class HelloController { @RequestMapping ...

  5. spring boot rest 接口集成 spring security(2) - JWT配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  6. spring boot rest 接口集成 spring security(1) - 最简配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. Spring Boot配置篇(基于Spring Boot 2.0系列)

    1:概述 SpringBoot支持外部化配置,配置文件格式如下所示: properties files yaml files environment variables command-line ar ...

  8. (转)Spring Boot 2 (八):Spring Boot 集成 Memcached

    http://www.ityouknow.com/springboot/2018/09/01/spring-boot-memcached.html Memcached 介绍 Memcached 是一个 ...

  9. Spring Boot 2 (八):Spring Boot 集成 Memcached

    Spring Boot 2 (八):Spring Boot 集成 Memcached 一.Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数 ...

随机推荐

  1. Xamarin.Android之SlidingMenu

    一.前言 有位网友在评论中希望能够出个在Xamarin.Android下实现SlidingMenu效果的随笔,刚好昨天在观看官网示例项目的时候也看到这个SlidingMenu,但是最终的效果并不是我们 ...

  2. txt文件匹配脚本

    # -*- coding:utf-8 -*- import time start = time.clock() data=open("Data.txt","r" ...

  3. 读书笔记——spring cloud 中 HystrixCommand的四种执行方式简述

    读了<Spring Cloud 微服务实战>第151-154页, 总结如下: Hystrix存在两种Command,一种是HystrixCommand,另一种是HystrixObserva ...

  4. layer.js 弹窗组件API文档

      基础参数 type title content skin area offset icon btn closeBtn shade shadeClose time id shift maxmin f ...

  5. 【phpstudy】安装Oracle 客户端 并连接

    参考连接:https://blog.csdn.net/liuquan007/article/details/77508518 phpstudy2016是32位版 phpstudy2014是64位版本[ ...

  6. Linux-/etc/rc.local 或 service 中使用 sudo -u xxx cmd 执行失败(sorry, you must have a tty to run sudo)解决办法

    使用 visudo 命令编辑 /etc/sudoers 1)Defaults requiretty,修改为 #Defaults requiretty,表示不需要控制终端. 2)Defaults req ...

  7. [转载]virtual&nbsp;box如何生成新的UUID

    原文地址:virtual box如何生成新的UUID作者:阿昭 问题描述:在为Virtual Box加载多台虚拟机器(显然这些虚拟机器都来自一个模板)的时候,出现如下错误: "Cannot ...

  8. <转>Boost库之asio io_service以及run、run_one、poll、poll_one区别

    本文转自:http://blog.csdn.net/byxdaz/article/details/71088812 一.io_service的作用 io_servie 实现了一个任务队列,这里的任务就 ...

  9. Bean的加载过程

    参考地址: http://blog.csdn.net/jy0902/article/details/50519115 http://blog.csdn.net/architect0719/articl ...

  10. linux下磁盘相关工具(待整理)

    一.概述: fsck tune2fs mke2fs badblocks mkfs* fdisk mount umount mknod e2label blkid hdparm mkswap swapo ...