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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 使用spring oauth2框架获取当前登录用户信息的实现代码

    使用spring oauth2框架做授权鉴定.想获取当前用户信息怎么办? 我们知道spring oauth2是基于spring security的实现的. spring security可以通过SecurityContextHolder.getContext().getAuthentication().getPrincipal()获取到当前用户信息. 而spring oauth2通过SecurityContextHolder.getContext().getAuthentication().ge

  • Spring Cloud OAuth2 实现用户认证及单点登录的示例代码

    OAuth 2 有四种授权模式,分别是授权码模式(authorization code).简化模式(implicit).密码模式(resource owner password credentials).客户端模式(client credentials),具体 OAuth2 是什么,可以参考这篇文章.(http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html) 本文我们将使用授权码模式和密码模式两种方式来实现用户认证和授权管理. OAuth2 其

  • Spring Security OAuth过期的解决方法

    最近一段时间,大家在用 Spring Security OAuth2 时可能发现有很多类过期了. 大家在选择 OAuth2 依赖的时候,可能也会困惑,有好几个地方都可以选: 那么到底选择哪一个依赖合适呢?这不同的依赖又有什么区别?今天松哥就来和大家聊一聊 Spring Security 中关于 OAuth2 的恩怨. 前言 先来大致介绍一下 OAuth2 在 Spring 框架中的发展历程. 大约十年前,Spring 引入了一个社区驱动的开源项目 Spring Security OAuth,并将

  • Spring Security整合Oauth2实现流程详解

    一.创建项目并导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <art

  • spring cloud oauth2 实现用户认证登录的示例代码

    需求 在微服务架构中,我们有很多业务模块,每个模块都需要有用户认证,权限校验.有时候也会接入来自第三方厂商的应用.要求是只登录一次,即可在各个服务的授权范围内进行操作.看到这个需求,立马就想到了这不就是单点登录吗?于是基于这样的需求,作者使用spring-cloud-oauth2去简单的实现了下用户认证和单点登录. 相关介绍 OAuth2 OAuth2是一个关于授权的网络标准,他定制了设计思路和执行流程.OAuth2一共有四种授权模式:授权码模式(authorization code).简化模式

  • Spring Cloud下基于OAUTH2认证授权的实现示例

    在Spring Cloud需要使用OAUTH2来实现多个微服务的统一认证授权,通过向OAUTH服务发送某个类型的grant type进行集中认证和授权,从而获得access_token,而这个token是受其他微服务信任的,我们在后续的访问可以通过access_token来进行,从而实现了微服务的统一认证授权. 本示例提供了四大部分: discovery-service:服务注册和发现的基本模块 auth-server:OAUTH2认证授权中心 order-service:普通微服务,用来验证认

  • Spring Security OAuth2 授权码模式的实现

    写在前边 在文章OAuth 2.0 概念及授权流程梳理 中我们谈到OAuth 2.0的概念与流程,这里我准备分别记一记这几种授权模式的demo,一方面为自己的最近的学习做个总结,另一方面做下知识输出,如果文中有错误的地方,请评论指正,在此不胜感激 受众前提 阅读本文,默认读者已经过Spring Security有一定的了解,对OAuth2流程有一定了解 本文目标 带领读者对Spring Security OAuth2框架的授权码模式有一个比较直观的概念,能使用框架搭建授权码模式授权服务器与资源服

  • Spring Cloud下OAUTH2注销的实现示例

    接上文Spring Cloud下基于OAUTH2认证授权的实现,我们将基于Spring Cloud实现OAUTH2的注销功能. 1 增加自定义注销Endpoint 所谓注销只需将access_token和refresh_token失效即可,我们模仿org.springframework.security.oauth2.provider.endpoint.TokenEndpoint写一个使access_token和refresh_token失效的Endpoint: @FrameworkEndpoi

  • Spring cloud oauth2如何搭建认证资源中心

    一 认证中心搭建 添加依赖,如果使用spring cloud的话,不管哪个服务都只需要这一个封装好的依赖即可 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> 配置spring security /** * security配置类 */

  • Spring Cloud oauth2 认证服务搭建过程示例

    目录 安装httpie 导入数据库脚本 sts中导入项目 修改 POM文件 修改配置文件 修改主类文件 编译,运行 测试 查看Redis缓存 安装httpie 安装httpie 需要 python 环境 pip install --upgrade httpie 进入D:\Project目录,在此目录下打开CMD,调用httpie,创建 oauth2 项目 http -d https://start.spring.io/starter.zip javaVersion==17 groupId==co

  • spring cloud oauth2 feign 遇到的坑及解决

    目录 springcloudoauth2feign遇到的坑 客户端模式 基于springsecurity springcloud微服务增加oauth2权限后feign调用报null 一般是这样实现的 spring cloud oauth2 feign 遇到的坑 关于oauth2相关的内容这里不重复描述,在spring cloud中在管理内部api时鉴权相信有很多人会有疑问,这里描述两种比较low的用法,由于公司内部使用的是阿里云edas这里仅仅是记录一下,如果有更好的用法在请赐教,不喜勿喷! 客

  • Spring Cloud OAuth2中/oauth/token的返回内容格式

    目录 背景 实现原理 代码实现 相关类 关键切面拦截器 背景 在前后端分离的项目中,一般后端返回给前端的格式是一个固定的json格式.在这个前提下,Spring Cloud OAuth2 生成access token的请求/oauth/token的返回内容就需要自定义. 访问/oauth/token示例如下: 原始返回值的格式如下: 我们希望使用我们自己固定的json格式,如下: 实现原理 原理就是通过切面编程实现对/oauth/token端点请求的结果进行拦截封装处理,由于/oauth/tok

  • Spring Cloud Alibaba使用Nacos作为注册中心和配置中心

    目录 前言 Nacos简介 使用Nacos作为注册中心 安装并运行Nacos 创建应用注册到Nacos 负载均衡功能 使用Nacos作为配置中心 创建nacos-config-client模块 在Nacos中添加配置 Nacos的动态刷新配置 使用到的模块 前言 Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案,Nacos 作为其核心组件之一,可以作为注册中心和配置中心使用,本文将对其用法进行详细介绍. Nacos简介 Nacos 致力于帮助您发现.配置和管理微服务

  • Spring Cloud OAuth2实现自定义token返回格式

    目录 问题描述 解决方案 总结 最近读者朋友针对Spring Security OAuth2.0 想要陈某补充一些知识,如下: 今天这篇文章就来回答其中一个问题:如何自定义token的返回格式? 问题描述 Spring Security OAuth的token返回格式都是默认的,但是往往这个格式是不适配系统,/oauth/token返回的格式如下: { "access_token": token "token_type": "bearer", &

  • Spring Cloud 整合 nacos实现动态配置中心的详细步骤

    目录 前提条件 整合步骤 1. 添加依赖 2. 新建 nacos 配置 3. bootstrap.properties 配置 4. 配置dataId 4.1 自动配置 dataId 4.2 手动设置 dataId 5.获取数据 总结 源码 参考文献 上一篇文章讲解了Spring Cloud 整合 nacos 实现服务注册与发现,nacos除了有服务注册与发现的功能,还有提供动态配置服务的功能.本文主要讲解Spring Cloud 整合nacos实现动态配置服务.主要参考官方部署手册点我. 前提条

  • Spring Cloud之配置中心的搭建

    Spring Cloud是现在流行的分布式服务框架,它提供了很多有用的组件.比如:配置中心.Eureka服务发现.消息总线.熔断机制等. 配置中心在Spring Cloud的众多组件中是比较基础的,它提供了配置文件的统一管理,可以很轻松的切换不通的环境. 它的具体结构如下: 存储配置文件的文件系统(通常使用git) 配置中心服务端(从文件系统获取最新的配置文件,为客户端提供配置信息) 配置客户端(从配置中心获取配置信息) Spring Cloud是建立在Spring Boot基础上的,Sprin

随机推荐