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 ...
随机推荐
- 快速部署 Spring PetClinic 到函数计算平台
简介 首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute):函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传.函数计算准 ...
- DOCKER学习_001:Docker简介
一 Docker简介 1.1 docker由来 Docker的英文翻译是“码头工人”,即搬运工,它搬运的东西就是我们常说的集装箱Container,Container里面装的是任意类型的App.我们的 ...
- 十三、springboot 优雅集成spring-boot-admin 实现程序监控
前言 我们知道项目的监控是尤为重要的,但是我们如果用jdk 自带的jconsole 和jvisualvm 的话会非常繁琐,且界面不是很友好.之前我们使用了spring boot 项目,但是都没有对项目 ...
- $Luogu2680/NOIp2015$ 运输计划
传送门 $Sol$ 最暴力的做法就是枚举最长链上的边,然后再算一次所有的链长,更新$ans$. 这里要求最大的最小,容易想到二分答案.对于二分的值$mid$,扫一遍所有的链,若链长小于等于$mid$, ...
- JDK1.8的HashMap实现原理和源码解析
哈希表(hash table)也叫散列表,是一种非常重要的数据结构.许多缓存技术(比如memcached)的核心其实就是在内存中维护一张大的哈希表,本文会对java集合框架中的对应实现HashMap的 ...
- nodejs-websocket+ssl证书
1.nodejs配置微信小程序本地服务器(二):利用ws模块创建基于ssl证书的WebSocket服务器:https://segmentfault.com/a/1190000013956534 2.n ...
- 现代主流框架路由原理 hash、history的底层原理
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【GeneXus】在WorkWithPlus中如何定义未被包含的页面属性?
在使用GeneXus开发项目的过程中,有很多用户会使用到WorkWithPlus这个模板.通过WorkWithPlus的编辑器,让页面的调整变得极为简单,尤其是响应式页面.在WorkWithPlus的 ...
- 人脸识别系统 —— 基于python的人工智能识别核心
起因 自打用python+django写了一个点菜系统,就一直沉迷python编程.正好前几天公司boss要我研究一下人脸识别,于是我先用python编写了一个人脸识别系统的核心,用于之后的整个系统. ...
- vnpy源码阅读学习(3):学习vnpy的界面的实现
学习vnpy的界面的实现 通过简单的学习了PyQt5的一些代码以后,我们基本上可以理解PyQt的一些用法,下面让我们来先研究下vnpy的UI部分的代码. 首先回到上一节看到的run.py(/vnpy/ ...