spring security oauth2 client_credentials模

本文主要简单介绍一下spring security oauth2的client_credentials模式

maven

  1. <dependency>
  2. <groupId>org.springframework.security.oauth</groupId>
  3. <artifactId>spring-security-oauth2</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.boot</groupId>
  11. <artifactId>spring-boot-starter-web</artifactId>
  12. </dependency>

auth server config

  1. @Configuration
  2. @EnableAuthorizationServer //提供/oauth/authorize,/oauth/token,/oauth/check_token,/oauth/confirm_access,/oauth/error
  3. public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
  4. @Override
  5. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  6. oauthServer
  7. .tokenKeyAccess("permitAll()")
  8. .checkTokenAccess("isAuthenticated()") //allow check token
  9. .allowFormAuthenticationForClients();
  10. }
  11. @Override
  12. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  13. clients.inMemory()
  14. .withClient("demoApp")
  15. .secret("demoAppSecret")
  16. .authorizedGrantTypes("client_credentials", "password", "refresh_token")
  17. .scopes("all")
  18. .resourceIds("oauth2-resource")
  19. .accessTokenValiditySeconds(1200)
  20. .refreshTokenValiditySeconds(50000);
  21. }
  22. }

resource server config

  1. @Configuration
  2. @EnableResourceServer
  3. public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  4. }

demo controller

  1. @RestController
  2. @RequestMapping("/api")
  3. public class DemoController {
  4. @GetMapping("/blog/{id}")
  5. public String getBlogById(@PathVariable long id) {
  6. return "this is blog "+id;
  7. }
  8. }

验证

没有token请求资源

  1. curl -i -H "Accept: application/json" -X GET http://localhost:8080/api/blog/1

返回

  1. HTTP/1.1 401
  2. X-Content-Type-Options: nosniff
  3. X-XSS-Protection: 1; mode=block
  4. Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  5. Pragma: no-cache
  6. Expires: 0
  7. X-Frame-Options: DENY
  8. Cache-Control: no-store
  9. Pragma: no-cache
  10. WWW-Authenticate: Bearer realm="oauth2-resource", error="unauthorized", error_description="Full authentication is required to access this resource"
  11. Content-Type: application/json;charset=UTF-8
  12. Transfer-Encoding: chunked
  13. Date: Sat, 02 Dec 2017 14:31:51 GMT
  14. {"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

client_credentials请求授权

  1. curl -H "Accept: application/json" demoApp:demoAppSecret@localhost:8080/oauth/token -d grant_type=client_credentials

或者

  1. curl -H "Accept: application/json" http://localhost:8080/oauth/token -d "grant_type=client_credentials&client_id=demoApp&client_secret=demoAppSecret"

返回

  1. {"access_token":"6d0ee2b2-c803-49bf-a813-a25bfb59a976","token_type":"bearer","expires_in":1199,"scope":"all"}

携带token请求资源

  1. curl -i -H "Accept: application/json" -H "Authorization: Bearer 6d0ee2b2-c803-49bf-a813-a25bfb59a976" -X GET http://localhost:8080/api/blog/1

或者

  1. curl -i -X GET http://localhost:8080/api/blog/1?access_token=fe8bcab3-1d33-4ef1-b1d0-bd142a480af2

不过这种把token暴露在url中不是太安全

返回

  1. HTTP/1.1 200
  2. X-Content-Type-Options: nosniff
  3. X-XSS-Protection: 1; mode=block
  4. Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  5. Pragma: no-cache
  6. Expires: 0
  7. X-Frame-Options: DENY
  8. X-Application-Context: application
  9. Content-Type: application/json;charset=UTF-8
  10. Content-Length: 14
  11. Date: Sat, 02 Dec 2017 14:31:09 GMT
  12. this is blog 1

check token

  1. curl -i -X POST -H "Accept: application/json" -u "demoApp:demoAppSecret" http://localhost:8080/oauth/check_token?token=3d47e053-de16-4e6f-8ec7-f9247f425a8e

返回

  1. HTTP/1.1 403
  2. X-Content-Type-Options: nosniff
  3. X-XSS-Protection: 1; mode=block
  4. Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  5. Pragma: no-cache
  6. Expires: 0
  7. X-Frame-Options: DENY
  8. Content-Type: application/json;charset=UTF-8
  9. Transfer-Encoding: chunked
  10. Date: Sat, 02 Dec 2017 14:50:32 GMT
  11. {"timestamp":1512226232386,"status":403,"error":"Forbidden","message":"Access is denied","path":"/oauth/check_token"}

需要配置

  1. @Override
  2. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  3. oauthServer
  4. .tokenKeyAccess("permitAll()")
  5. .checkTokenAccess("isAuthenticated()") //allow check token
  6. .allowFormAuthenticationForClients();
  7. }

成功返回

  1. HTTP/1.1 200
  2. X-Content-Type-Options: nosniff
  3. X-XSS-Protection: 1; mode=block
  4. Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  5. Pragma: no-cache
  6. Expires: 0
  7. X-Frame-Options: DENY
  8. X-Application-Context: application
  9. Content-Type: application/json;charset=UTF-8
  10. Transfer-Encoding: chunked
  11. Date: Sat, 02 Dec 2017 14:48:33 GMT
  12. {"aud":["oauth2-resource"],"scope":["read"],"exp":1512227200,"client_id":"demoApp"}

token非法

  1. HTTP/1.1 400
  2. X-Content-Type-Options: nosniff
  3. X-XSS-Protection: 1; mode=block
  4. Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  5. Pragma: no-cache
  6. Expires: 0
  7. X-Frame-Options: DENY
  8. X-Application-Context: application
  9. Cache-Control: no-store
  10. Pragma: no-cache
  11. Content-Type: application/json;charset=UTF-8
  12. Transfer-Encoding: chunked
  13. Date: Sat, 02 Dec 2017 14:51:33 GMT
  14. Connection: close
  15. {"error":"invalid_token","error_description":"Token was not recognised"}

doc

增加了文件,另外mvn依赖需要写版本号

<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>

  1. package com.italkbb.homesecurity.alertmessage.security;
  2.  
  3. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.security.authentication.AuthenticationManager;
  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.password.PasswordEncoder;
  10. import org.springframework.web.cors.CorsConfiguration;
  11. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  12. import org.springframework.web.filter.CorsFilter;
  13. //import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
  14.  
  15. /**
  16. * Created by wangyunfei on 2017/6/9.
  17. */
  18. @Configuration
  19. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  20. // @Autowired
  21. // private DomainUserDetailsService userDetailsService;
  22.  
  23. @Override
  24. protected void configure(HttpSecurity http) throws Exception {
  25. http
  26. .csrf().disable()
  27. .anonymous().disable()
  28. .authorizeRequests()
  29. // .antMatchers("/api-docs/**").permitAll();
  30. }
  31.  
  32. @Bean
  33. public FilterRegistrationBean corsFilter() {
  34. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  35. CorsConfiguration config = new CorsConfiguration();
  36. config.setAllowCredentials(true);
  37. config.addAllowedOrigin("*");
  38. config.addAllowedHeader("*");
  39. config.addAllowedMethod("*");
  40. source.registerCorsConfiguration("/**", config);
  41. FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
  42. bean.setOrder(0);
  43. return bean;
  44. }
  45.  
  46. /*
  47. @Bean
  48. public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
  49. return new SecurityEvaluationContextExtension();
  50. }
  51. */
  52. //不定义没有password grant_type
  53. @Override
  54. @Bean
  55. public AuthenticationManager authenticationManagerBean() throws Exception {
  56. return super.authenticationManagerBean();
  57. }
  58.  
  59. /* 替换这个不工作,报 null 当调用userDetailsService loadUser时候。
  60. @Override
  61. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  62. auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
  63. }
  64. */
  65.  
  66. /* @Autowired
  67. public void configure(AuthenticationManagerBuilder auth) throws Exception {
  68. System.out.println("");
  69.  
  70. auth.userDetailsService(userDetailsService)
  71. .passwordEncoder(passwordEncoder());
  72. }
  73. */
  74.  
  75. @Bean
  76. public PasswordEncoder passwordEncoder(){
  77. // return new BCryptPasswordEncoder();
  78. return new PasswordEncoder() {
  79.  
  80. @Override
  81. public boolean matches(CharSequence rawPassword, String encodedPassword) {
  82. System.out.println("PasswordEncoder: raw password:" + rawPassword.toString() + " encoded:" + encodedPassword
  83. + "================================");
  84. return true;
  85. }
  86.  
  87. @Override
  88. public String encode(CharSequence rawPassword) {
  89. System.out.println("PasswordEncoder: raw password:" + rawPassword.toString() + "================================");
  90. return rawPassword.toString();
  91. }
  92. };
  93. }
  94.  
  95. }

spring security oauth2 client_credentials模的更多相关文章

  1. Spring security oauth2 client_credentials认证 最简单示例代码

    基于spring-boot-2.0.0 1,在pom.xml中添加: <!-- security --> <!-- https://mvnrepository.com/artifac ...

  2. Spring Security Oauth2 的配置

    使用oauth2保护你的应用,可以分为简易的分为三个步骤 配置资源服务器 配置认证服务器 配置spring security 前两点是oauth2的主体内容,但前面我已经描述过了,spring sec ...

  3. 转 - spring security oauth2 password授权模式

    原贴地址: https://segmentfault.com/a/1190000012260914#articleHeader6 序 前面的一篇文章讲了spring security oauth2的c ...

  4. Re:从零开始的Spring Security Oauth2(二)

    本文开始从源码的层面,讲解一些Spring Security Oauth2的认证流程.本文较长,适合在空余时间段观看.且涉及了较多的源码,非关键性代码以…代替. 准备工作 首先开启debug信息: l ...

  5. Re:从零开始的Spring Security Oauth2(一)

    前言 今天来聊聊一个接口对接的场景,A厂家有一套HTTP接口需要提供给B厂家使用,由于是外网环境,所以需要有一套安全机制保障,这个时候oauth2就可以作为一个方案. 关于oauth2,其实是一个规范 ...

  6. Spring Security OAuth2 Demo —— 客户端模式(ClientCredentials)

    前情回顾 前几节分享了OAuth2的流程与其它三种授权模式,这几种授权模式复杂程度由大至小:授权码模式 > 隐式授权模式 > 密码模式 > 客户端模式 本文要讲的是最后一种也是最简单 ...

  7. Spring Security 解析(五) —— Spring Security Oauth2 开发

    Spring Security 解析(五) -- Spring Security Oauth2 开发   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决 ...

  8. 基于spring boot2.0+spring security +oauth2.0+ jwt微服务架构

    github地址:https://github.com/hankuikuide/microservice-spring-security-oauth2 项目介绍 该项目是一个演示项目,主要演示了,基于 ...

  9. Spring Cloud 学习 (十) Spring Security, OAuth2, JWT

    通过 Spring Security + OAuth2 认证和鉴权,每次请求都需要经过 OAuth Server 验证当前 token 的合法性,并且需要查询该 token 对应的用户权限,在高并发场 ...

随机推荐

  1. 如何程序化的构造Hibernate配置 // How to initialize Hibernate programmably

    Java为什么被人诟病,因为一切都是过度设计.Hibernate其实就是实现了一套JPA的ORM,不过用极度冗赘的配置方式,nodejs Sequelize.js,甚至Python SQLAlchem ...

  2. MySQL外键设置中的的 Cascade、NO ACTION、Restrict、SET NULL

    例如: ALTER TABLE stuinfo ADD CONSTRAINT fk_stuinfo FOREIGN KEY(gradeid) REFERENCES grade(id) ON DELET ...

  3. 使用 Dashboard - 每天5分钟玩转 Docker 容器技术(174)

    上一节我们完成了 Kubernetes Dashboard 的安装,本节就来实践一下. Dashboard 界面结构 Dashboard 的界面很简洁,分为三个大的区域. 顶部操作区在这里用户可以搜索 ...

  4. fiddler几种功能强大的用法

    参考网址: http://caibaojian.com/fiddler.html http://www.cnblogs.com/tangdongchu/p/4178552.html 1.fiddler ...

  5. c# 多线程委托传参方式

    1.定义一个线程调用的方法函数 private void RTPServer(object _Serverip) { IPEndPoint Serverip = _Serverip as IPEndP ...

  6. Clickhouse v18编译记录

    简介 ClickHouse是"战斗民族"俄罗斯搜索巨头Yandex公司开源的一个极具"战斗力"的实时数据分析数据库,是面向 OLAP 的分布式列式DBMS,圈内 ...

  7. Boosting Static Representation Robustness for Binary Clone Search against Code Obfuscation and Compiler Optimization(一)

    接着上一篇,现在明确问题:在汇编克隆搜索文献中,有四种类型的克隆[15][16][17]:Type1.literally identical(字面相同):Type2.syntactically equ ...

  8. 《Effective Java中文版第二版》读书笔记

    说明 这里是阅读<Effective Java中文版第二版>的读书笔记,这里会记录一些个人感觉稍微有些重要的内容,方便以后查阅,可能会因为个人实力原因导致理解有误,若有发现欢迎指出.一些个 ...

  9. html+css 制作简易导航栏

    二话不说直接上代码(萌新:实在也没什么好说的) <!DOCTYPE html> <html lang="en" xmlns="http://www.w3 ...

  10. CSS---内外边距

    1.内外边距含义 内边距是div边框内的距离.背景色会覆盖内边距,内边距会使宽高变大. 外边距是div边框外的距离.背景色不会覆盖外边距 内外边距都会撑高父元素,外边距会提高div与div之间的距离 ...