spring security oauth2 client_credentials模

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

maven

        <dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

auth server config

@Configuration
@EnableAuthorizationServer //提供/oauth/authorize,/oauth/token,/oauth/check_token,/oauth/confirm_access,/oauth/error
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter { @Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()") //allow check token
.allowFormAuthenticationForClients();
} @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("demoApp")
.secret("demoAppSecret")
.authorizedGrantTypes("client_credentials", "password", "refresh_token")
.scopes("all")
.resourceIds("oauth2-resource")
.accessTokenValiditySeconds(1200)
.refreshTokenValiditySeconds(50000);
} }

resource server config

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter { }

demo controller

@RestController
@RequestMapping("/api")
public class DemoController { @GetMapping("/blog/{id}")
public String getBlogById(@PathVariable long id) {
return "this is blog "+id;
}
}

验证

没有token请求资源

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

返回

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

client_credentials请求授权

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

或者

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

返回

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

携带token请求资源

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

或者

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

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

返回

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

check token

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

返回

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

需要配置

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()") //allow check token
.allowFormAuthenticationForClients();
}

成功返回

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

token非法

HTTP/1.1 400
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
X-Application-Context: application
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 02 Dec 2017 14:51:33 GMT
Connection: close {"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>

package com.italkbb.homesecurity.alertmessage.security;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
//import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; /**
* Created by wangyunfei on 2017/6/9.
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// @Autowired
// private DomainUserDetailsService userDetailsService; @Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
// .antMatchers("/api-docs/**").permitAll();
} @Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
} /*
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
*/
//不定义没有password grant_type
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
} /* 替换这个不工作,报 null 当调用userDetailsService loadUser时候。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}
*/ /* @Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println(""); auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
*/ @Bean
public PasswordEncoder passwordEncoder(){
// return new BCryptPasswordEncoder();
return new PasswordEncoder() { @Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
System.out.println("PasswordEncoder: raw password:" + rawPassword.toString() + " encoded:" + encodedPassword
+ "================================");
return true;
} @Override
public String encode(CharSequence rawPassword) {
System.out.println("PasswordEncoder: raw password:" + rawPassword.toString() + "================================");
return rawPassword.toString();
}
};
} }

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. java 中文乱码以及转码

    查看此文章需要对字符集编码有一定的认识:任意门:字符集编码基础 一.字符串的内部表示? 重点:字符串在java(指在JVM中.在内存中)中统一用unicode表示( 即utf-16 LE) , 下面解 ...

  2. 解决Win10系统本地主机,网络受限占用CPU过高的问题

    Win10版本为2015年第一个版本,第一次安装时没有这个问题,后面每次安装后开机正常,但是只要运行一段时间后(机子有运行各种软件的情况),发现CPU使用率为100% 即使结束所有在运行的程序,依然居 ...

  3. Session, Token, OAuth 鉴权那些事儿

    鉴权那些事 整体思路 无论什么样的服务, Web 服务总是不能绕开鉴权这个话题的, 通过有效的鉴权手段来保护网站数据, 来为特定用户提供服务. 整体来说, 有三种方式: Session-Cookie ...

  4. Ubuntu忘记密码后强制修改密码

    环境:Ubuntu 16.04 由于很久不用我的Ubuntu系统导致密码忘记,就想着应该有什么办法可以强制修改root密码,就上百度找了一下,果然Ubuntu有办法强制修改root密码. 在这里要谢谢 ...

  5. 如何解决分配到Autoconfiguration IPV4 地址

    配置完服务器静态IP后,在CMD窗口中查看ip地址,发现是Autoconfiguration IPV4. 上网搜索了,是关于虚拟服务器的,但是我没有配置虚拟服务器,有点奇怪. 使用下面的教程,可以解决 ...

  6. C++调用Opencv实践中遇到的问题备忘录

    1.编写一个显示图片的项目,但显示的图片全灰色. 原因:需要在imshow()函数前加一个namedWindow()函数.https://blog.csdn.net/mao_hui_fei/artic ...

  7. LeetCode算法题-Poor Pigs(Java实现)

    这是悦乐书的第235次更新,第248篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第102题(顺位题号是455).有1000个水桶,其中只有一个水桶含有毒药,其余的都没毒 ...

  8. SpringIOC和AOP简单概述

    Spring学习:主要学习两大块IOC   AOP 一.IOC   IOC:控制反转(也可以叫做依赖注入)的基本认识:   当某个Java对象(调用者)需要调用另一个Java对象(被依赖对象)的方法时 ...

  9. mmap:速度快+整块操作

    mmap使得可以将设备内存映射到用户空间,从而使得用户程序获得访问硬件的能力,mmap的动作需要由内核中的驱动来实现.在使用mmap映射后,用户程序对给定范围的内存的读写就变成了对设备内存的读写,也就 ...

  10. MySQL参数最大连接数max_connections

    1.查看最大连接数 mysql> show status like 'Threads%'; +-------------------+-------+ | Variable_name | Val ...