当前位置: 首页 > news >正文

spring oauth2 配置流程

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

package com.icecloud.cloud.test.oauthTest_1;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.ManagementServerProperties;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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.config.http.SessionCreationPolicy;
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.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableAuthorizationServer
@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
public class App extends WebSecurityConfigurerAdapter {
	
	/**
	 * 需要权限的action
	 */
	@RequestMapping({ "/test" })
	public Map<String, String> test() {
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("nametest", "12222");
		return map;
	}
	
	/**
	 * 需要权限并且提供token才能访问的action
	 */
	@RequestMapping({ "/se" })
	public Map<String, String> se() {
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("se", "3333");
		return map;
	}
	
        /**
	 * 不需要权限的action
	 */
	@RequestMapping({ "/","" })
	public String index() {
		return "index";
	}
	
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		 http
         .authorizeRequests()
             .antMatchers("/").permitAll()
             .anyRequest().authenticated()
             .and()
			.formLogin()
			.and()
			.httpBasic();
	}
	
	@Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
    }
	
	
	/**
	 * 资源服务器
	 * @author penghaozhong
	 *
	 */
	@Configuration
	@EnableResourceServer
	protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
		
		
		@Override
		public void configure(ResourceServerSecurityConfigurer resources) {
			resources.resourceId("app").stateless(false);
		}

		@Override
		public void configure(HttpSecurity http) throws Exception {
			http
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
				.and()
				.requestMatchers().antMatchers("/se")
				.and()
				.authorizeRequests()
				.antMatchers("/se").access("#oauth2.hasScope('read')");
		}

	}
	
	/**
	 * oauth2 服务端
	 * @author penghaozhong
	 *
	 */
	@Configuration
	@EnableAuthorizationServer
	protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

		@Override
		public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
			clients.inMemory().withClient("tonr").secret("secret").authorizedGrantTypes("authorization_code")
					.scopes("read");
		}
	}
}

一个完成的oauth2 例子 。服务端和资源服务器同为一个。下面进行代码拆分理解。

本例子中有三个重要的组件:security  ResourceServer AuthorizationServer

一.  继承 WebSecurityConfigurerAdapter 就完成了security的组装工作。

public class App extends WebSecurityConfigurerAdapter

WebSecurityConfigurerAdapter 默认是要求进行账号密码登录操作的,即使你没有编写.formLogin(),因为系统用上了默认配置。

WebSecurityConfigurerAdapter 类中:有这段代码

protected void configure(HttpSecurity http) throws Exception {
		logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");

		http
			.authorizeRequests()
				.anyRequest().authenticated()
				.and()
			.formLogin().and()
			.httpBasic();
	}

security账号密码配置方式,记住这里的账号密码是用户登录时用的。配置有2种形式:

1. 编写代码

@Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
    }

2:编写配置文件

233956_2yeZ_124056.png

 

二. 配置oauth2 AuthorizationServer 继承AuthorizationServerConfigurerAdapter。填入客户端id和密码,授权模式,权限范围。这里简单实现保存到缓存中。

@Override
		public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
			clients.inMemory().withClient("tonr").secret("secret").authorizedGrantTypes("authorization_code")
					.scopes("read");
		}

三. 配置资源服务器 ResourceServer 哪些资源需要通过oauth2提供的服务的,需要编写代码限制。比如/se 这个请求地址就是需要进行oauth2 授权后才能访问的信息。

@Override
		public void configure(HttpSecurity http) throws Exception {
			http
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
				.and()
				.requestMatchers().antMatchers("/se")
				.and()
				.authorizeRequests()
				.antMatchers("/se").access("#oauth2.hasScope('read')");
		}

代码编写已经理解完成。下面进行实际测试工作吧。

四. 请求授权

235810_Yhl3_124056.png

这里我用的postman进行调试的。用到authorization的oauth2.0功能 ,很方便进行调试工作。各个参数按照要求填入即可。点击请求后在后台日志中会得到code。

000055_ubZ2_124056.png

四. 获取token

这里需要用上一把的code值去换取token,获取token时就用post方式获取。填入需要参数后,你会发现这里有个坑。这里卖个关子,如果你没有遇到没有解决又没太多时间去解决的话,留言即可。

000246_vgTX_124056.png

五. 获取资源数据

001229_ApM3_124056.png

大工搞成,希望这篇文章能帮到需要的朋友们。半夜睡不着可以起来调程序,很有乐趣!

转载于:https://my.oschina.net/penghaozhong/blog/777061

相关文章:

  • [转发]项目修复-把有麻烦的项目带向成功
  • 苹果应用的上线步骤
  • 源天软件Velcro解决方案
  • 【转载】ANSYS 动力分析 (9) - 瞬态动力分析 (1)
  • [WCF]重载
  • [python] 之 函数简介
  • [转]SharePoint升级后错误,解决方案
  • RMQ算法模板
  • 自己复制粘贴出来的第一个java小程序
  • 深入浅出JVM
  • C#3.0介绍
  • CSS菜单横竖布局要点
  • XmlReader 读取器读取内存流 MemoryStream 的注意事项
  • Oracle推导参数Derived Parameter介绍
  • [转]如何进行软件需求分析
  • JavaScript工作原理(五):深入了解WebSockets,HTTP/2和SSE,以及如何选择
  • Javascript基础之Array数组API
  • JAVA之继承和多态
  • js ES6 求数组的交集,并集,还有差集
  • leetcode388. Longest Absolute File Path
  • node 版本过低
  • React组件设计模式(一)
  • vue-cli在webpack的配置文件探究
  • 对JS继承的一点思考
  • 经典排序算法及其 Java 实现
  • 如何在 Tornado 中实现 Middleware
  • 深度解析利用ES6进行Promise封装总结
  • 提升用户体验的利器——使用Vue-Occupy实现占位效果
  • 微服务入门【系列视频课程】
  • 我建了一个叫Hello World的项目
  • 一起来学SpringBoot | 第三篇:SpringBoot日志配置
  • 用Visual Studio开发以太坊智能合约
  • elasticsearch-head插件安装
  • 基于django的视频点播网站开发-step3-注册登录功能 ...
  • 微龛半导体获数千万Pre-A轮融资,投资方为国中创投 ...
  • ​LeetCode解法汇总1276. 不浪费原料的汉堡制作方案
  • # 睡眠3秒_床上这样睡觉的人,睡眠质量多半不好
  • (JS基础)String 类型
  • (MATLAB)第五章-矩阵运算
  • (独孤九剑)--文件系统
  • (附源码)spring boot基于小程序酒店疫情系统 毕业设计 091931
  • (三) diretfbrc详解
  • (学习日记)2024.04.10:UCOSIII第三十八节:事件实验
  • (转)【Hibernate总结系列】使用举例
  • (转)EOS中账户、钱包和密钥的关系
  • (转)fock函数详解
  • (转载)从 Java 代码到 Java 堆
  • (轉貼) 蒼井そら挑戰筋肉擂台 (Misc)
  • ***详解账号泄露:全球约1亿用户已泄露
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net
  • .NET Core 和 .NET Framework 中的 MEF2
  • .net 提取注释生成API文档 帮助文档
  • .NET国产化改造探索(三)、银河麒麟安装.NET 8环境
  • .so文件(linux系统)
  • /bin、/sbin、/usr/bin、/usr/sbin