spring Security4 和 oauth2整合 注解+xml混合使用(授权码篇)

2023-11-12

Spring Security4 和 oauth2整合授权码模式

上两篇介绍了环境配置和用户密码模式,下面介绍授权码模式。

git地址:https://gitee.com/ffch/OauthUmp

spring Security4 和 oauth2整合 注解+xml混合使用(基础运行篇)
spring Security4 和 oauth2整合 注解+xml混合使用(进阶篇)
spring Security4 和 oauth2整合 注解+xml混合使用(授权码篇)
spring Security4 和 oauth2整合 注解+xml混合使用(注意事项篇)
spring Security4 和 oauth2整合 注解+xml混合使用(替换6位的授权码)
spring Security4 和 oauth2整合 注解+xml混合使用(替换用户名密码认证)
spring Security4 和 oauth2整合 注解+xml混合使用(验证码等额外数据验证)

OAuth2SecurityConfiguration

授权码模式需要对OAuth2SecurityConfiguration进行一些配置,对跳转的url做限制。

package com.ump.test.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
	@Autowired
	@Qualifier("myClientDetailsService")
	private ClientDetailsService clientDetailsService;
//	@Autowired
//	@Qualifier("myUserDetailsService")
//	private UserDetailsService userDetailsService;
	@Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
		//auth.userDetailsService(userDetailsService);
		auth.inMemoryAuthentication()
        .withUser("bill").password("abc123").roles("ADMIN").and()
        .withUser("bob").password("abc123").roles("USER");
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
		http
		.csrf().disable()
	  	.authorizeRequests()
	  	.antMatchers("/oauth/token")
	  	.permitAll().and()
	  	.formLogin().loginPage("/authlogin.jsp")
	  	.usernameParameter("userName").passwordParameter("userPwd")
	  	.loginProcessingUrl("/login").failureUrl("/index1.jsp")
	  	.and().logout().logoutUrl("/logout");
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
//
//	@Bean
//	public TokenStore tokenStore() {
//		return new InMemoryTokenStore();
//	}
	@Bean
	@Autowired
	public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
		TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
		handler.setTokenStore(tokenStore);
		handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
		handler.setClientDetailsService(clientDetailsService);
		return handler;
	}
	@Bean
	@Autowired
	public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
		TokenApprovalStore store = new TokenApprovalStore();
		store.setTokenStore(tokenStore);
		return store;
	}
}

authlogin.jsp

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<%@ page language="java" pageEncoding="UTF-8"%> 
<head>
<%
	String baseUrl = request.getContextPath();
%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="<%=baseUrl%>/js/jquery-3.2.1.min.js"></script>
<title>SkyNet</title>
</head>
<script type="text/javascript">
	function ajaxTest() {
		var type = "1";
		$.ajax({
			type : "post",
			url : "<%=baseUrl%>/test/welCome",
			dataType : "json",
			data : {reqType : type} ,
			success : function(data) {
				$("#div1").html(data.uuid + "<br>" + 
						data.welMsg + "<br>"+
						data.dateTime);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert(errorThrown);
			}
		});
	}
</script>
<body>
	这里是htm1 
	<div id="div1"></div>
	<button type="button" onclick="ajaxTest()">Welcome</button>
	<form action="<%=baseUrl%>/login" method="post">
First name:<br>
<input type="text" name="userName">
<br>
Last name:<br>
<input type="text" name="userPwd">
<input type="submit" value="Submit" />
</form>
	<script type="text/javascript">
		$(document).ready(function() {
			$("#div1").html("呵呵");
		});
	</script>
</body>
</html>

加上前面两篇的测试页面,这样授权码模式就可以了。不过还有个问题,就是授权码的client_id必须用baseauth的方式去写,不能直接写在链接里,这就很烦人。想写在链接里,很简单,AuthorizationServerConfiguration加上一句oauthServer.allowFormAuthenticationForClients();即可。

package com.ump.test.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
	private static String REALM = "MY_OAUTH_REALM";
	@Autowired
	private TokenStore tokenStore;
	@Autowired
	@Qualifier("myClientDetailsService") 
	private ClientDetailsService clientDetailsService;
	@Autowired
	private UserApprovalHandler userApprovalHandler;
	@Autowired
	@Qualifier("authenticationManagerBean")
	private AuthenticationManager authenticationManager;
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.withClientDetails(clientDetailsService);
//		clients.inMemory().withClient("my-trusted-client")
//				.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
//				.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT").scopes("read", "write", "trust").secret("secret")
//				.accessTokenValiditySeconds(120)
//				.refreshTokenValiditySeconds(600);
	}
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
				.authenticationManager(authenticationManager);
	}
	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
		oauthServer.allowFormAuthenticationForClients();
		oauthServer.realm(REALM + "/client");
	}
}

自定义授权页面

oauth2的授权页面太丑了,可以考虑改一下,找个最简单的方案即可。我这里页面跟它类似,也很丑,就是copy它的,做个示范。

package com.ump.test.oauth;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
@Controller
@SessionAttributes("authorizationRequest")
public class OAuth2ApprovalController {
	@RequestMapping("/oauth/confirm_access")
	public String getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
		return "/user/oauth_approval.jsp";
	}
}

oauth_approval.jsp

<%@ page language="java" pageEncoding="UTF-8"%> 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>授权</title>
</head>
<body>
	<h1>自定义 Approval</h1>
	<p>这是我自己的,怎么样?</p>
	<form id='confirmationForm' name='confirmationForm'
		action='/oauth/authorize' method='post'>
		<input name='user_oauth_approval' value='true' type='hidden' /><label><input
			name='authorize' value='Authorize' type='submit' /></label>
	</form>
	<form id='denialForm' name='denialForm' action='/oauth/authorize'
		method='post'>
		<input name='user_oauth_approval' value='false' type='hidden' /><label><input
			name='deny' value='Deny' type='submit' /></label>
	</form>
</body>
</html>

可以咯,下一篇写个注意事项。

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

spring Security4 和 oauth2整合 注解+xml混合使用(授权码篇) 的相关文章

  • 21天,胖哥亲自带你玩转OAuth2

    参与Spring Security与OAuth2专栏限定免费学习群 xff0c 请从阅读原文扫描第三个专栏学习群二维码入群 xff01 关于21天学习挑战赛活动细节 xff0c 请点击 阅读原文了解 作者介绍 码农小胖哥 xff0c Spr
  • .net core基于Oauth2+jwt两种方式实现身份认证(附单点登录)

    引用地址 xff1a net core基于Oauth2 43 jwt两种方式实现身份认证 附单点登录 cslx5zx5的博客 CSDN博客 net core oauth2 基于 net core 3 1微服务架构的SSO单点登录实战 本文所
  • oauth2.0+jwt 源码探究之旅

    oauth2 0协议是一种对外开放式协议 xff0c 主要用于第三方登录授权 例如 xff1a 在豆瓣官网点击用qq登录 以及微信的授权都是基于oauth2 0协议做的 oauth2 0的认证流程 xff08 A xff09 用户打开客户端
  • 轻松搭建CAS 5.x系列(6)-在CAS Server上增加OAuth2.0协议

    概述说明 CAS Server默认搭建出来 xff0c 客户端程序只能按照CAS自身的协议接入 CAS的强大在于 xff0c 有官方的插件 xff0c 可以支持其他的协议 本章节就让CAS Server怎么增加OAuth2 0的登录协议 安
  • oauth2 clientid作用_Oauth 2.0 授权机制

    在了解 Oauth 2 0 之前 xff0c 我们先看一下令牌和密码到底有什么关系 xff0c 其实令牌 xff08 token xff09 与密码 xff08 password xff09 的作用是一样的 xff0c 都可以进入系统 xf
  • (七)springcloud Oauth2授权-Spring Cloud Oauth2

    spring security oauth2 客户端四种授权模式 xff1a 授权码模式 xff08 authorization code xff09 xff1a 第三方应用先申请一个授权码 xff0c 然后再用该码获取令牌 简化模式 xf
  • Spring Security OAuth2.0认证授权

    文章目录 1 基本概念1 1 什么是认证1 2 什么是会话1 3什么是授权1 4授权的数据模型1 4 RBAC1 4 1 基于角色的访问控制 2 基于Session的认证方式3 整合案例3 1 SpringMVC 43 Servlet3 0
  • 使用 OAuth2-Server-php 在 Yii 框架上搭建 OAuth2 Server

    http www cnblogs com rereadyou p 3448381 html Yii 有很多 extension 可以使用 xff0c 在查看了 Yii 官网上提供的与 OAuth 相关的扩展后 xff0c 发现了几个 OAu
  • Spring Boot and OAuth2翻译

    Spring Boot and OAuth2 本指南将向您展示如何使用OAuth2和Spring Boot构建一个使用 社交登录 功能做各种事情的应用程序示例 它从一个简单的单一提供者单点登录开始 xff0c 并运行一个带有身份验证提供程序
  • 基于Apache OLTU的OAuth2.0授权解决方案

    Apache OLTU实现了OAuth 2 0的规范 xff0c 是一种可靠的Java授权解决方案 但是 xff0c 官方文档实在是太惨不忍睹了 本文参考了开涛的 OAuth 2 0集成Shiro文章 模拟了OAuth2 0的认证流程 技术
  • Spring Security OAuth2.0认证授权一:框架搭建和认证测试

    一 OAuth2 0介绍 OAuth xff08 开放授权 xff09 是一个开放标准 xff0c 允许用户授权第三方应用访问他们存储在另外的服务提供者上的信息 xff0c 而不 需要将用户名和密码提供给第三方应用或分享他们数据的所有内容
  • Spring Security OAuth2.0认证授权三:使用JWT令牌

    Spring Security OAuth2 0系列文章 xff1a Spring Security OAuth2 0认证授权一 xff1a 框架搭建和认证测试Spring Security OAuth2 0认证授权二 xff1a 搭建资源
  • Spring Security OAuth2.0认证授权学习与使用~(更新中)

    Spring Security OAuth2 0认证授权学习与使用 1 1 什么是认证1 1 1 系统为什么要认证 xff1f 1 1 2 认证 1 2 什么是会话 xff1f 1 2 1 会话1 2 2 基于Session的认证方式如下图
  • springboot整合maven Profile实现properties文件多环境配置

    步骤 首先写几个properties的配置文件 一般这样的文件有三个 而且文件的名称也也可以随意 不论你们的项目是使用的springmvc还是springboot 文件名称都可以随意指定 例如我的几个文件 在文件中写一些测试的属性值 方便测
  • OAUTH之 钉钉第三方授权登录

    文章目录 OAUTH之钉钉第三方授权登录 前期用到的工具 获取access token 请求地址 请求方法 响应 扫码 使用账号密码 获取 临时 code 参数重要说明 直接访问 扫码登录 使用账号密码登录第三方网站 根据 sns 临时授权
  • Spring Security Oauth2 之 理解OAuth 2.0授权流程

    总览 本系列针对Security Oauth2架构的剖析 包括 oauth2 0认证架构详解 架构源码解读 核心结构配置 本篇是对oauth2认证流程的概述 喜欢的多多pick 内容引用书籍 The OAuth 2 0 Authorizat
  • OAuth2 授权码模式为什么不直接返回access_token

    https www cnblogs com erichi101 p 13497971 html OAuth2的实际应用中 最常见的就是 授权码模式 了 微博是这种模式 微信也是这种模式 总结来说 就是简单的二步 1 获取code 2 根据c
  • oauth2.0的配置信息AuthorizationServerConfigurerAdapter

    继承AuthorizationServerConfigurerAdapter方法的配置 Configuration EnableAuthorizationServer public class Oauth2ServerConfig exte
  • Oauth2.0实现token刷新功能

    扣扣技术分享交流群 1125844267 1 Oauth3 0简介 Oauth2 0是一个授权协议 提供了一种解决用户资源共享问题的思路 它不是一种实现 对于java来说 我们可以利用Spring Security OAuth2来实现 Oa
  • spring Security4 和 oauth2整合 注解+xml混合使用(授权码篇)

    Spring Security4 和 oauth2整合授权码模式 上两篇介绍了环境配置和用户密码模式 下面介绍授权码模式 git地址 https gitee com ffch OauthUmp spring Security4 和 oaut

随机推荐

  • 获取outputstream大小_关于inputStream.available()方法获取下载文件的总大小

    如果用inputStream对象的available 方法获取流中可读取的数据大小 通常我们调用这个函数是在下载文件或者对文件进行其他处理时获取文件的总大小 以前在我们初学File和inputStream和outputStream时 有需要
  • C++标准库之中文输出详细介绍【转】

    iostream printf wprintf和中文输出 本文引用出处 http www enjoysoft cn blog post 62 html使用C 标准库的iostream 可以方便地将控制台 文件 字符串以及其它可扩充的外部表示
  • Vue使用v-for遍历map

    功能 遍历数据库中按钮的图片和名字 当页面打开时 触发查询事件 以下图形式显示出来 前端代码 遍历存在数据库中的按钮名称和图片名称 其中按钮的click事件名称和按钮图片名称相同
  • Linux命令 理解

    RPM常用命令参数列表 1 安装一个包 rpm ivh 2 升级一个包 rpm Uvh 注意U一定要大写 i 安装 U 升线安装 h 以 显示安装进度 v 显示附加信息 3 移走一个包 rpm e 4 安装参数 force 即使覆盖属于其它
  • 变透明的黑匣子:UCLA 开发可解释神经网络 SNN 预测山体滑坡

    内容一览 由于涉及到多种时空变化因素 山体滑坡预测一直以来都非常困难 深度神经网络 DNN 可以提高预测准确性 但其本身并不具备可解释性 本文中 UCLA 研究人员引入了 SNN SNN 具有完全可解释性 高准确性 高泛化能力和低模型复杂度
  • 基本的信号——矩阵脉冲信号(门函数)

    门函数的数学表达式为 example1 矩形脉冲信号的matlab代码如下 矩形脉冲信号 clc clear close all t 0 0 001 4 T 1 ft rectpuls t 2 T 2 T plot t ft 运行结果如下
  • Normalize 和 normalized

    首先说明下 normalized的是vector的属性 而Normalize 是vector的方法 normalized和Normalize 都是可读的 读到的值是单位向量的值 只是nomalized不会更改当前vector本身的值 只是返
  • [转载]PropertyChanged 事件

    在 NET平台上 数据绑定是一项令人十分愉快的技术 利用数据绑定能减少代码 简化控制逻辑 通常 可以将某个对象的一个属性绑定到一个可视化的控件上 当属性值改变时 控件上的显示数据也随之发生变化 要实现这一功能 只需要为自定义对象实现 INo
  • Pandas 笔记 (一)

    Pandas 笔记 Pandas 提供高性能 易于使用的数据结构和数据分析工具 Pandas 可以从 CSV JSON SQL MICROSOFTEXCEL 导入数据 Pandas 可以对各种数据进行运算操作 比如归并 再形成 选择 还有数
  • vue3的一些知识点plus--4

    二十六 hooks使用 hooks 复用代码进行封装 钩子函数 和vue2中的mixins相似 将共同部分抽离出来 也有开源的库 vueUse 包含各种hooks 可以在 官网 查看 我们自己怎么编写呢 要知道hook底层就是个函数 返回p
  • 树(Tree)——(六)平衡搜索二叉树理论篇

    目录 平衡 分类 最小不平衡子树 AVL Tree AVL树的失衡调整的四种情况 1 左单旋 RR 关键代码 例 补充 2 右单旋 LL 关键代码 3 右左双旋 RL 4 左右双旋 LR 总结 平衡 影响树的平衡的因素主要有 插入顺序 删除
  • 数据结构---栈与队列

    今天是高木同学哦 栈 栈的基本概念 栈 栈是一种特殊的线性表 其只允许在固定的一端进行插入和删除元素操作 进行数据插入和删除操作的一端称为栈顶 另一端被称为栈底 栈中的数据元素遵守后进先出 LIFO 的原则 压栈 栈的插入操作叫做压栈 出栈
  • 【复变函数与积分变换】02. 解析函数

    Contents 2 解析函数 2 1 复变函数 2 2 解析函数 2 3 解析函数的充分必要条件 2 4 解析函数与调和函数的关系 2 5 初等解析函数 2 解析函数 2 1 复变函数 复变函数的定义 设 D D D 是复平面中的一个点集
  • JDK8,JDK11,JDK17,JDK21及中间版本主要更新特性

    一 版本roadmap图 官方地址 https www oracle com java technologies java se support roadmap html 从上图可以很清晰得可以看出 JDK7 JDK8 JDK11 JDK1
  • CCS8.0和XDS100V3仿真器连接目标板失败的解决办法

    对于新手 要想顺利的连接上目标板不是一个容易的事 所以我这里记录一下我这个新手为了连接目标板的折腾过程 我的开发平台 WIN10系统CCS8 0 目标板芯片 TMS320VC5509A 仿真器 研旭XDS100V3 已确定的前提条件 CCS
  • 华北水利水电大学c语言无暇素数,华北水大C语言实验报告(三)

    华北水大高级语言程序设计 C语言 实验报告 三 2014 2015学年 第二学期 2014级 专业 学号 姓名 一 实验题目 循环结构程序设计 二 实验目的 略 三 实验内容 1 程序验证 略 2 程序设计 1 找出100 900之间的无暇
  • C++中使用UDP Socket发送字节数据

    文章目录 参考 代码 结果展示 参考 这篇文章给的代码也能用 https blog csdn net qq 36437446 article details 106446172 CRC代码来自https blog csdn net huij
  • 自己实现ls-l命令

    include
  • c4d人物模型 - mixamo 网页骨骼绑定

    1 首先拿出建立好的模型 成男 全身 c4d 2 复制一份到新文件 绑定动作 c4d 把轴对齐设置到人物脚中心 然后复位psr 确认没有问题后把模型 C 掉 导出obj文件准备放到网页中进行骨骼绑定 3 登录网址 Mixamo 导入obj文
  • spring Security4 和 oauth2整合 注解+xml混合使用(授权码篇)

    Spring Security4 和 oauth2整合授权码模式 上两篇介绍了环境配置和用户密码模式 下面介绍授权码模式 git地址 https gitee com ffch OauthUmp spring Security4 和 oaut