一 认证中心搭建

添加依赖,如果使用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搭建认证中心与资源中心的更多相关文章

  1. spring cloud 专题一 (spring cloud 入门搭建 之 Eureka注册中心搭建)

    一.前言 本文为spring cloud 微服务框架专题的第一篇,主要讲解如何快速搭建spring cloud微服务及Eureka 注册中心 以及常用开发方式等. 本文理论不多,主要是傻瓜式的环境搭建 ...

  2. spring security oauth2 搭建认证中心demo

    oauth2 介绍 ​ oauth2 协议应该是开发者们耳熟能详的协议了,这里就不做过多的介绍了,具体介绍如何在spring security中搭建oauth2的认证服务.Spring-Securit ...

  3. vue+uni-app商城实战 | 第一篇:【有来小店】微信小程序快速开发接入Spring Cloud OAuth2认证中心完成授权登录

    一. 前言 本篇通过实战来讲述如何使用uni-app快速进行商城微信小程序的开发以及小程序如何接入后台Spring Cloud微服务. 有来商城 youlai-mall 项目是一套全栈商城系统,技术栈 ...

  4. SpringCloud实战之初级入门(三)— spring cloud config搭建git配置中心

    目录 1.环境介绍 2.配置中心 2.1 创建工程 2.2 修改配置文件 2.3 在github中加入配置文件 2.3 修改启动文件 3. 访问配置中心 1.环境介绍 上一篇文章中,我们介绍了如何利用 ...

  5. Spring Cloud config之一:分布式配置中心入门介绍

    Spring Cloud Config为服务端和客户端提供了分布式系统的外部化配置支持.配置服务器为各应用的所有环境提供了一个中心化的外部配置.它实现了对服务端和客户端对Spring Environm ...

  6. spring security oauth2搭建resource-server demo及token改造成JWT令牌

    我们在上文讲了如何在spring security的环境中搭建基于oauth2协议的认证中心demo:https://www.cnblogs.com/process-h/p/15688971.html ...

  7. Spring Cloud OAuth2.0 微服务中配置 Jwt Token 签名/验证

    关于 Jwt Token 的签名与安全性前面已经做了几篇介绍,在 IdentityServer4 中定义了 Jwt Token 与 Reference Token 两种验证方式(https://www ...

  8. Spring Cloud(七):配置中心(Git 版与动态刷新)【Finchley 版】

    Spring Cloud(七):配置中心(Git 版与动态刷新)[Finchley 版]  发表于 2018-04-19 |  更新于 2018-04-24 |  Spring Cloud Confi ...

  9. Spring Cloud第十一篇 | 分布式配置中心高可用

    ​ 本文是Spring Cloud专栏的第十一篇文章,了解前十篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Cl ...

随机推荐

  1. 解决css布局时两个div一个宽度固定另一个占满剩余宽度的问题

    /*左侧div*/ .left-div{width: 220px;height: 100%;position: fixed;background: #FFFFFF;} /*右侧div*/ .right ...

  2. Jenkins配置QQ邮箱发送邮件

    1.登陆QQ邮箱 2. 在“帐户”里开启“POP3/SMTP”并获取授权码 3. 发送短信验证验证后得到下面验证码 aeoygabszxfecbdj #验证吗 点击确定之后,服务已经开启 4. Jen ...

  3. C# 字符串与二进制的相互转换

    /// <summary> /// 将字符串转成二进制 /// </summary> /// <param name="s"></para ...

  4. C++简单项目--推箱子

    在处理移动的时候有太多种情况了: 1.有空位 2.在推箱子,推到了空地 3.推箱子推到了目标, 4.推目标位的箱子推到另一个目标 5.推目标位的箱子推到空地 首先记录目标位置,在每次推动之后会再绘画中 ...

  5. bootstrap:导航分页

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name ...

  6. linux下安装cmake方法(2)---直接用命令安装

    1.linux环境下打开网页,输入上网账号密码,确保已经联网 2.打开终端:输入cmake --version,如果出现版本号,表明已经安装,如果显示没有安装cmake,则需要安装 3.在终端里输入: ...

  7. SQL Server2012高可用之事物复制(发布订阅)测试

      (一)测试目的 目前公司使用的SQL SERVER 2012高可用环境为主备模式,其中主库可执行读写操作,备库既不可写也不可读,即采用的高可用技术为"数据库镜像".存在的问题为 ...

  8. ArcGIS Server for JavaScript 3.3 的安装部署

    一.安装包下载 首先从官网下载ArcGIS API for JavaScript 3.3 的API和SDK,地址:http://support.esrichina.com.cn/2011/0223/9 ...

  9. MySQL 物理备份工具-xtrabackup

    安装 wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo yum -y install perl ...

  10. Python判断一个字符串是否包含某个指定的字符串

    成员操作符 in str = "string test string test" find1 = "str" find2 = "test" ...