Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1
0. 前言
之前帐号认证用过自己写的进行匹配,现在要学会使用标准了。准备了解和使用这个OAuth2.0协议。
1. 配置
1.1 配置pom.xml
有些可能会用不到,我把我项目中用到的所有包都贴出来。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
1.2 配置application.properties
#server
server.port=8080
server.servlet.session.timeout=2520000
#redis
spring.redis.database=0
spring.redis.host=172.16.23.203
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=60
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=10000
1.3 资源服务器配置
/**
* OAuth 资源服务器配置
* @author
* @date 2018-05-29
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { private static final String DEMO_RESOURCE_ID = "order"; @Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
} @Override
public void configure(HttpSecurity http) throws Exception {
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().anyRequest()
.and()
.anonymous()
.and()
.authorizeRequests()
.antMatchers("/order/**").authenticated();//配置order访问控制,必须认证过后才可以访问
}
}
1.4 授权服务器配置
/**
* OAuth 授权服务器配置
* @author
* @date 2018-05-29
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { private static final String DEMO_RESOURCE_ID = "order"; @Autowired
AuthenticationManager authenticationManager;
@Autowired
RedisConnectionFactory redisConnectionFactory; @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String finalSecret = "{bcrypt}"+new BCryptPasswordEncoder().encode("123456");
//配置两个客户端,一个用于password认证一个用于client认证
clients.inMemory()
.withClient("client_1")
.resourceIds(DEMO_RESOURCE_ID)
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("select")
.authorities("oauth2")
.secret(finalSecret)
.and()
.withClient("client_2")
.resourceIds(DEMO_RESOURCE_ID)
.authorizedGrantTypes("password", "refresh_token")
.scopes("select")
.authorities("oauth2")
.secret(finalSecret);
} @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(new RedisTokenStore(redisConnectionFactory))
.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
} @Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
//允许表单认证
oauthServer.allowFormAuthenticationForClients();
}
}
1.5 Spring Security配置
/**
* Spring-Security 配置<br>
* 具体参考: https://github.com/lexburner/oauth2-demo
* @author
* @date 2018-05-28
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean
@Override
protected UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("123456");
manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build());
finalPassword = "{noop}123456";
manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("USER").build());
return manager;
} @Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().anyRequest()
.and()
.authorizeRequests()
.antMatchers("/oauth/*").permitAll();
} /**
* Spring Boot 2 配置,这里要bean 注入
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
AuthenticationManager manager = super.authenticationManagerBean();
return manager;
} @Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
1.6 定义一个资源点
@RestController
@RequestMapping(value="/")
public class TestController { @RequestMapping(value="order/demo")
public YYModel getDemo() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println(auth);
YYModel yy = new YYModel();
yy.setYy("中文");
yy.setZz(3);
return yy;
} @GetMapping("/test")
public String getTest() {
YYModel yy = new YYModel();
yy.setYy("中文");
yy.setZz(3);
return yy.toJSONString();
}
}
2. 工具测试


参考: http://blog.didispace.com/spring-security-oauth2-xjf-1/
Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1的更多相关文章
- Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式2
0.前言 经过前面一小节已经基本配置好了基于SpringBoot+SpringSecurity+OAuth2.0的环境.这一小节主要对一些写固定InMemory的User和Client进行扩展.实现动 ...
- Spring Boot 2(一):Spring Boot 2.0新特性
Spring Boot 2(一):Spring Boot 2.0新特性 Spring Boot依赖于Spring,而Spring Cloud又依赖于Spring Boot,因此Spring Boot2 ...
- Spring Boot 多站点利用 Redis 实现 Session 共享
如何在不同站点(web服务进程)之间共享会话 Session 呢,原理很简单,就是把这个 Session 独立存储在一个地方,所有的站点都从这个地方读取 Session. 通常我们使用 Redis 来 ...
- spring boot 是如何利用jackson进行序列化的?
接上一篇:spring boot 是如何利用jackson进行反序列化的? @RestController public class HelloController { @RequestMapping ...
- spring boot rest 接口集成 spring security(2) - JWT配置
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot rest 接口集成 spring security(1) - 最简配置
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- Spring Boot配置篇(基于Spring Boot 2.0系列)
1:概述 SpringBoot支持外部化配置,配置文件格式如下所示: properties files yaml files environment variables command-line ar ...
- (转)Spring Boot 2 (八):Spring Boot 集成 Memcached
http://www.ityouknow.com/springboot/2018/09/01/spring-boot-memcached.html Memcached 介绍 Memcached 是一个 ...
- Spring Boot 2 (八):Spring Boot 集成 Memcached
Spring Boot 2 (八):Spring Boot 集成 Memcached 一.Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数 ...
随机推荐
- excel文件批量重命名
1.创建bat文件 2.在文件内输入以下格式的内容并保存,注意期间有空格 ren 1.txt 0011.txt ren 2.txt 0021.txt ren 3.txt 0031.tx ...
- PHP 反射 初步测试
<?php //php反射机制 /* //用途 1 该扩展分析php程序,导出或提取出关于类,方法,属性,参数等详细信息,包括注释 //Reflection可以说是对php库函数: /class ...
- 分布式 并行软件平台 Dryad Hadoop HPCC
1.为了 能够方便记忆, 总结一下. 2. 并行软件平台,不是 一个. (1)这个特别熟悉的 以 hadoop 为平台的 生态系统 (2)还有以 微软的 并行软件平台 生态系统 (3) 还有Lexi ...
- [转载][Groovy] Groovy与Java的区别(一)
原文地址:[Groovy] Groovy与Java的区别(一)作者:langyizhao 因为Groovy可以用Java的所有功能(虽然JVM不同的时候可能会比较麻烦,比如在Android上),所以G ...
- 接口测试-Http状态码-postman上传文件
转自:https://www.cnblogs.com/jiadan/articles/8546015.html 一. 接口 接口:什么是接口呢?接口一般来说有两种,一种是程序内部的接口,一种是系统 ...
- centos中执行apt-get命令提示apt-get command not found
先说结论: 在centos下用yum install xxx yum和apt-get的区别: 一般来说著名的linux系统基本上分两大类: RedHat系列:Redhat.Centos.Fedora ...
- jenkins+maven+git+ 邮件自动转发 持续化集成 图文教程
1.所需要的插件,安装plugin ,进入mangae Jenkins→ manage Plugins, 切换到Available tab, 选择如下plugin 安装 Gitplugin, GitH ...
- iphone3g 蜂窝数据有效设置
iphone3g 蜂窝数据有效设置 蜂窝数据 APN cmnet/空 用户名 空 A密码 空彩信(默认为空,需要控制的话,可以设置) APN cmwap/空 用 ...
- 为什么现在很多年轻人愿意来北上广深打拼,即使过得异常艰苦,远离亲人,仍然义无反顾? 谈谈程序员返回家乡的创业问题 利基市场就是那些不大不小的缝隙中的市场 马斯洛的需求无层次不适合中国。国人的需求分三个层次——生存、稳定、装逼。对应的,国内的产品也分三个层次——便宜、好用、装B。人们愿意为这些掏钱
信念.思考.行动-谈谈程序员返回家乡的创业问题 昨天晚上在微博上看了篇 <为什么现在很多年轻人愿意来北上广深打拼,即使过得异常艰苦,远离亲人,仍然义无反顾?>,有些话想说. 感觉很多人的担 ...
- c运行库、c标准库、windows API的区别和联系
C运行时库函数C运行时库函数是指C语言本身支持的一些基本函数,通常是汇编直接实现的. API函数API函数是操作系统为方便用户设计应用程序而提供的实现特定功能的函数,API函数也是C语言的函数实现的 ...