spring cloud系列学习(十、 使用Spring Security实现OAuth2授权认证存储redis)

2023-11-05

1、新增spring boot,导包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</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>
<!-- redis  -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
配置类
package com.springcloud.newapi.oauthconfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    // 该对象用来支持 password 模式
     @Autowired
    AuthenticationManager authenticationManager;
//     // 该对象用来将令牌信息存储到内存中
//     @Autowired(required = false)
//     TokenStore inMemoryTokenStore;// 该对象将为刷新token提供支持
// 该对象用来将令牌信息存储到Redis中
        @Autowired
RedisConnectionFactory redisConnectionFactory;

    @Autowired
    UserDetailsService userDetailsService;
    // 指定密码的加密方式
    @Bean
      PasswordEncoder passwordEncoder() {
     // 使用BCrypt强哈希函数加密方案(密钥迭代次数默认为10)
     return new BCryptPasswordEncoder();
     }
     // 配置 password 授权模式
    @Override
         public void configure(ClientDetailsServiceConfigurer clients)throws Exception {
          clients.inMemory().withClient("password").authorizedGrantTypes("password", "refresh_token") //授权模式为password和refresh_token两种
              .accessTokenValiditySeconds(1800) // 配置access_token的过期时间
              .resourceIds("rid") //配置资源id
              .scopes("all")
              .secret("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq"); //123加密后的密码
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//endpoints.tokenStore(inMemoryTokenStore) //配置令牌的存储(这里存放在内存中)
    endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)) //配置令牌存放在Redis中
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
// 表示支持 client_id 和 client_secret 做登录认证
security.allowFormAuthenticationForClients();
}
}

 

 

package com.springcloud.newapi.oauthconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {

        return super.userDetailsService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq") //123
                .roles("admin")
                .and()
                .withUser("sang")
                .password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq") //123
                .roles("user");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/oauth/**").authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .and().csrf().disable();
    }
}

 

微服务配置

package com.springcloud.newapi.oauthconfig;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {

        resources.resourceId("rid") // 配置资源id,这里的资源id和授权服务器中的资源id一致
                .stateless(true); // 设置这些资源仅基于令牌认证
    }

    // 配置 URL 访问权限
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated();
    }
}
package com.springcloud.newapi.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/admin/hello")
    public String admin() {
        return "hello admin";
    }

    @GetMapping("/user/hello")
    public String user() {
        return "hello user";
    }

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

spring cloud系列学习(十、 使用Spring Security实现OAuth2授权认证存储redis) 的相关文章

  • JavaScript高级

    文章目录 今日内容 一 DOM简单学习 为了满足案例要求 1 功能 二 事件简单学习 三 BOM 1 概念 Browser Object Model 浏览器对象模型 2 组成 3 Window 窗口对象 案例2 轮播图 4 Location

随机推荐

  • c# - A study on the NativeWindow - encapsulate window handle and procedure

    NativeWindow gives you a way to way to intercept the window messages are you familiar with the Windows Message Pump Aslo
  • 【yolov7系列三】实战从0构建训练自己的数据集

    大家好 我是张大刀 上文中提到了yolov7的正负样本匹配策略 这里主要从0开始训练自己的数据集 如果大家需文中ppt使用 请关注公众号后台添加微信 领取 备注 ppt 首先大刀是在windows电脑端完成数据集的标注 linux ubun
  • 在 FPGA 上如何实现双线性插值的计算?

    作者 殷庆瑜 责编 胡巍巍 目录 一 概述 二 What 什么是双线性插值 二 Why 为什么需要双线性插值 三 How 怎么实现双线性插值 关键点1 像素点选择 关键点2 权重计算 升级1 通过查表减少计算量 升级2 通过数据锁存减少取数
  • cnpm下载、cnpm不存在处理、yarn安装

    1 cnpm全局安装 npm install g cnpm registry https registry npm taobao org 2 运行cnpm v 报错 不是内部环境 3 解决办法 在环境变量里添加路径 cmd中输入以下命令获取
  • 万用表怎么测量电池容量_家电维修必知:万用表测量及使用方法

    万用表怎么用 这是很多新手或是业余爱好者的一个小难题 有了万用表却不会使用 万用表是电工电器行业不可缺少的测量仪表 一般以测量电压 电流和电阻为主要目的 万用表按显示方式分为指针万用表和数字万用表 是一种多功能 多量程的测量仪表 也称三用表
  • c语言打开大于2G的文件,C语言操作大于2G的文件

    最近在做视频编解码时遇到使用fseek无法定位到一个大于2G的文件尾 由于自己功底不扎实 百思不得其解 请教大神后得知在VC平台下使用 fseeki64可以解决问题 然而自己傻乎乎的在获取文件指针位置的地方依旧使用的ftell 中途调试N久
  • (Java)leetcode-42 Trapping Rain Water(接雨水)

    题目描述 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图 计算按此排列的柱子 下雨之后能接多少雨水 上面是由数组 0 1 0 2 1 0 1 3 2 1 2 1 表示的高度图 在这种情况下 可以接 6 个单位的雨水 蓝色部分表示雨水
  • Servlet重要的API

    重要的API 重要的API config response响应 响应头的相关操作 响应输出流的操作 其它操作 request请求 请求头数据 Request乱码问题的解决方法 Java反射基础 重要的API config init 和ini
  • 【软件测试简答题】

    软件测试简答题 1 根据G Mayers的观点 软件测试的目的是什么 软件测试是 1 为了发现错误而执行程序的过程 2 一个好的用例能够发现至今尚未发现的错误的测试 3 一个成功的测试是发现至今尚未发现的错误的测试 2 简述软件测试的任务
  • java试题 算法训练 大小写转换

    试题 算法训练 大小写转换 资源限制 时间限制 1 0s 内存限制 256 0MB 问题描述 输入一个字符串 将大写字符变成小写 小写变成大写 然后输出 输入格式 acbAB 输出格式 ACBab 样例输入 一个满足题目要求的输入范例 例
  • 浅析Python爬虫ip程序延迟和吞吐量影响因素

    作为一名资深的爬虫程序员 今天我们很有必要来聊聊Python爬虫ip程序的延迟和吞吐量 这是影响我们爬取效率的重要因素 这里我们会提供一些实用的解决方案 让你的爬虫程序飞起来 网络延迟 首先 让我们来看看网络延迟对爬虫ip程序性能的影响 网
  • 【2022】小米秋招前端笔试(卷1+卷2单选题)

    文章目录 小米秋招前端笔试卷1 1 Git 暂存操作的API是什么 2 的valueOf和toString的结果是什么 3 排序算法中哪一种算法的时间复杂度是O nlogn 4 通常情况下 一个URL的格式是 5 以下哪个项目不是可以在HT
  • 【Educoder作业】问题求解——for 循环

    E d u c o d e r Educoder Educoder作
  • VUE全局过滤器

    对于反复使用或多个组件使用的过滤器相同时应该考虑全局过滤器 1 最基本的使用方法 在main js中注册 Vue filter MyFilter function value 返回处理后的值 return value 在组件直接使用即可 2
  • THINKPHP5.1在windows系统下,安装workerman

    一 首先你要在项目里安装composer 按照步骤下载 php r copy https install phpcomposer com installer composer setup php php composer setup php
  • Linux(云计算)期末复习资料

    1 linux概述 Linux是一种自由 开放源代码的操作系统 它最初由芬兰的Linus Torvalds在1991年开发 目前已经成为世界上最流行的操作系统之一 Linux操作系统的特点是免费 稳定 安全 可定制 可移植性强 支持多任务
  • mysql索引 文件坏了_MySQL索引失效的几种情况

    1 索引无法存储null值 a 单列索引无法储null值 复合索引无法储全为null的值 b 查询时 采用is null条件时 不能利用到索引 只能全表扫描 为什么索引列无法存储Null值 a 索引是有序的 NULL值进入索引时 无法确定其
  • ASTM 协议

    ASTM 协议为标准组织美国材料实验室协会 ASTM 制定的在医疗临床实验室仪器和计算机系统间传输信息的一个标准 此标准有多个版本 本文中提到的版本为 E1394 97 下文中提到的 ASTM 均为 ASTM 的 E1394 97 是在 1
  • Kettle系列(一)下载安装与基础配置

    Kettle系列 一 下载安装与基础配置 说明 一 下载 二 目录结构 三 基础配置 1 环境变量 2 kettle配置 四 连接mysql8 五 连接其他数据库 六 总结 说明 更新时间 2023 08 13 17 47 本文记录了win
  • spring cloud系列学习(十、 使用Spring Security实现OAuth2授权认证存储redis)

    1 新增spring boot 导包