spring cloud oauth2搭建认证中心与资源中心
一 认证中心搭建
添加依赖,如果使用spring cloud的话,不管哪个服务都只需要这一个封装好的依赖即可
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
配置spring security
/**
* security配置类
*/
@Configuration
@EnableWebSecurity //开启web保护
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法注解权限配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Qualifier("userDetailsServiceImpl")
@Autowired
private UserDetailsService userDetailsService; //配置用户签名服务,赋予用户权限等
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)//指定userDetailsService实现类去对应方法认
.passwordEncoder(passwordEncoder()); //指定密码加密器
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//配置拦截保护请求,什么请求放行,什么请求需要验证
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//配置所有请求开启认证
.anyRequest().permitAll()
.and().httpBasic(); //启用http基础验证
} // 配置token验证管理的Bean
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
配置OAuth2认证中心
/**
* OAuth2授权服务器
*/
@EnableAuthorizationServer //声明OAuth2认证中心
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private DataSource dataSource;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 这个方法主要是用于校验注册的第三方客户端的信息,可以存储在数据库中,默认方式是存储在内存中,如下所示,注释掉的代码即为内存中存储的方式
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
clients.inMemory()
.withClient("hou") // 客户端id,必须有
.secret(passwordEncoder.encode("123456")) // 客户端密码
.scopes("server")
.authorizedGrantTypes("authorization_code", "password", "refresh_token") //验证类型
.redirectUris("http://www.baidu.com");
/*redirectUris 关于这个配置项,是在 OAuth2协议中,认证成功后的回调地址,此值同样可以配置多个*/
//数据库配置,需要建表
// clients.withClientDetails(clientDetailsService());
// clients.jdbc(dataSource);
}
// 声明 ClientDetails实现
private ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
} /**
* 控制token端点信息
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.userDetailsService(userDetailsService);
}
//获取token存储类型
@Bean
public TokenStore tokenStore() {
//return new JdbcTokenStore(dataSource); //存储mysql中
return new InMemoryTokenStore(); //存储内存中
//new RedisTokenStore(connectionFactory); //存储redis中
} //配置获取token策略和检查策略
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()") //获取token请求不进行拦截
.checkTokenAccess("isAuthenticated()") //验证通过返回token信息
.allowFormAuthenticationForClients(); // 允许 客户端使用client_id和client_secret获取token
}
}
二 测试获取Token
默认获取token接口图中2所示,这里要说明一点,参数key千万不能有空格,尤其是client_这两个

三 需要保护的资源服务配置
yml配置客户端信息以及认中心地址
security:
oauth2:
resource:
tokenInfoUri: http://localhost:9099/oauth/check_token
preferTokenInfo: true
client:
client-id: hou
client-secret: 123456
grant-type: password
scope: server
access-token-uri: http://localhost:9099/oauth/token
配置认证中心地址即可
/**
* 资源中心配置
*/
@Configuration
@EnableResourceServer // 声明资源服务,即可开启token验证保护
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法权限注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//配置所有请求不需要认证,在方法用注解定制权限
.anyRequest().permitAll();
}
}
编写权限控制
@RestController
@RequestMapping("test")
public class TestController {
//不需要权限
@GetMapping("/hou")
public String test01(){
return "返回测试数据hou";
}
@PreAuthorize("hasAnyAuthority('ROLE_USER')") //需要权限
@GetMapping("/zheng")
public String test02(){
return "返回测试数据zheng";
}
}
四 测试权限
不使用token

使用token

spring cloud oauth2搭建认证中心与资源中心的更多相关文章
- spring cloud 专题一 (spring cloud 入门搭建 之 Eureka注册中心搭建)
一.前言 本文为spring cloud 微服务框架专题的第一篇,主要讲解如何快速搭建spring cloud微服务及Eureka 注册中心 以及常用开发方式等. 本文理论不多,主要是傻瓜式的环境搭建 ...
- spring security oauth2 搭建认证中心demo
oauth2 介绍 oauth2 协议应该是开发者们耳熟能详的协议了,这里就不做过多的介绍了,具体介绍如何在spring security中搭建oauth2的认证服务.Spring-Securit ...
- vue+uni-app商城实战 | 第一篇:【有来小店】微信小程序快速开发接入Spring Cloud OAuth2认证中心完成授权登录
一. 前言 本篇通过实战来讲述如何使用uni-app快速进行商城微信小程序的开发以及小程序如何接入后台Spring Cloud微服务. 有来商城 youlai-mall 项目是一套全栈商城系统,技术栈 ...
- SpringCloud实战之初级入门(三)— spring cloud config搭建git配置中心
目录 1.环境介绍 2.配置中心 2.1 创建工程 2.2 修改配置文件 2.3 在github中加入配置文件 2.3 修改启动文件 3. 访问配置中心 1.环境介绍 上一篇文章中,我们介绍了如何利用 ...
- Spring Cloud config之一:分布式配置中心入门介绍
Spring Cloud Config为服务端和客户端提供了分布式系统的外部化配置支持.配置服务器为各应用的所有环境提供了一个中心化的外部配置.它实现了对服务端和客户端对Spring Environm ...
- spring security oauth2搭建resource-server demo及token改造成JWT令牌
我们在上文讲了如何在spring security的环境中搭建基于oauth2协议的认证中心demo:https://www.cnblogs.com/process-h/p/15688971.html ...
- Spring Cloud OAuth2.0 微服务中配置 Jwt Token 签名/验证
关于 Jwt Token 的签名与安全性前面已经做了几篇介绍,在 IdentityServer4 中定义了 Jwt Token 与 Reference Token 两种验证方式(https://www ...
- Spring Cloud(七):配置中心(Git 版与动态刷新)【Finchley 版】
Spring Cloud(七):配置中心(Git 版与动态刷新)[Finchley 版] 发表于 2018-04-19 | 更新于 2018-04-24 | Spring Cloud Confi ...
- Spring Cloud第十一篇 | 分布式配置中心高可用
本文是Spring Cloud专栏的第十一篇文章,了解前十篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Cl ...
随机推荐
- pandas数据分析小知识点(一)
最近工作上,小爬经常需要用python做一些关于excel数据分析的事情,显然,从性能和拓展性的角度出发,使用pandas.numpy是比vba更好的选择.因为pandas能提供诸如SQL的很多查找. ...
- mysql主从之多元复制
实验环境: 192.168.132.121 master1 192.168.132.122 master2 192.168.132.123 slave 使用gtid的方式 两个主分别是19 ...
- $POJ2311\ Cutting\ Game$ 博弈论
正解:博弈论 解题报告: 传送门! 首先看到说,谁先$balabala$,因为$SG$函数是无法解决这类问题的,于是考虑转化成"不能操作者赢/输"的问题,不难想到先剪出$1\cdo ...
- 小小知识点(三十七)OFDM和OFDMA的区别以及OFDMA与SC-FDMA的区别
OFDM和OFDMA的区别 OFDM(orthogonal frequency division multiplexing),which assigns one block (in time ) to ...
- Django之models高级进阶技术详解
目录 一.常用字段 1.AutoField 2.IntegerField 3.CharField 4.自定义及使用char 5.DateField 6.DateTimeField 二.字段合集 三.字 ...
- iOS滤镜系列-滤镜开发概览
概述 滤镜最早的出现应该是应用在相机镜头前实现自然光过滤和调色的镜片,然而在软件开发中更多的指的是软件滤镜,是对镜头滤镜的模拟实现.当然这种方式更加方便快捷,缺点自然就是无法还原拍摄时的真实场景,例如 ...
- jdk1.7扩容时,不论是否有链表,并发都可能出现循环链表
扩容时使用transfertransfer不同于put时的判断hash冲突,直接使用头插法,如果没有冲突,则next为null.如下:e.next = newTable[i];newTable[i] ...
- js以当前时间为基础,便捷获取时间(最近2天,最近1周,最近2周,最近1月,最近2月,最近半年,最近一年,本周,本月,本年)
在开发公司管理后台系统时,遇到了需要根据不同的时间段如"近一年.近半年.近三月.近一月.近一周"来获取并展示不同图表数据的需求,很是繁琐,项目开发周期又非常的短,自己想了一下,虽然 ...
- ST表竞赛模板
void RMQ_init(){//ST表的创建模板 ;i<n;i++) d[i][]=mo[i]; ;(<<j)<=n;j++) ;i+(<<j)-<n;i ...
- 【LC_Overview1_5】---学会总结回顾
刷LeetCode题目一周,主要采用C++和Python编程手段,截至目前做了5道简单的leetcode题目,做下阶段性的小结: 小结主要通过手撕代码,复习加回顾,尽量避免自己眼高手低的情况发生,对于 ...