springboot集成Spring Security oauth2(八)
由于公司项目需要,进行SpringBoot集成Spring Security oauth2,几乎搜寻网上所有大神的案例,苦苦不能理解,不能完全OK。
以下是借鉴各大神的代码,终于demo完工,请欣赏
oauth2 定义了下面四种授权方式:
- 授权码模式(authorization code)
- 简化模式(implicit)
- 密码模式(resource owner password credentials)
- 客户端模式(client credentials)
具体每个模式的业务逻辑,请找百度君
以下是参数:
* response_type:表示授权类型,必选项,此处的值固定为"code"* client_id:表示客户端的ID,必选项* redirect_uri:表示重定向URI,可选项* scope:表示申请的权限范围,可选项* state:表示客户端的当前状态,可以指定任意值,认证服务器会原封不动地返回这个值。
先贴出项目结构:
直接贴代码:
SpringBoot项目入口,服务启动
package com.mingtong.demo_client;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class DemoClientApplication {public static void main(String[] args) {SpringApplication.run(DemoClientApplication.class, args);} }
控制器Controller,获取资源,后面可以改造JDBC获取数据库,或者远程调用
@RestController @RequestMapping("/api") public class DemoController {@RequestMapping("/blog/{id}")public String getBlogById(@PathVariable long id) {return "this is blog "+id;} }
Oauth2认证服务
@Configuration @EnableAuthorizationServer public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.realm("oauth2-resources") //code授权添加.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()") //allow check token .allowFormAuthenticationForClients();}/*** 注入authenticationManager* 来支持 password grant type*/@Autowiredprivate AuthenticationManager authenticationManager;@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager(authenticationManager)//允许 GET、POST 请求获取 token,即访问端点:oauth/token .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("demoApp").secret("demoAppSecret").redirectUris("http://baidu.com")//code授权添加.authorizedGrantTypes("authorization_code","client_credentials", "password", "refresh_token").scopes("all").resourceIds("oauth2-resource").accessTokenValiditySeconds(1200).refreshTokenValiditySeconds(50000);}}
资源服务器:
@Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers("/api/**").and() .authorizeRequests().antMatchers("/api/**").authenticated();}}
SpringSecurity配置
@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.csrf().disable();http.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**").and().authorizeRequests().antMatchers("/oauth/**").authenticated().and().formLogin().permitAll();}//配置内存模式的用户 @Bean@Overrideprotected UserDetailsService userDetailsService(){InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();manager.createUser(User.withUsername("demoUser1").password("123456").authorities("USER").build());manager.createUser(User.withUsername("demoUser2").password("123456").authorities("USER").build());return manager;}/*** 需要配置这个支持password模式*/@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();} }
POM文件
<dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
【密码授权模式-client】 密码模式需要参数:username,password,grant_type,client_id,client_secret http://localhost:8080/oauth/token?username=demoUser1&password=123456&grant_type=password&client_id=demoApp&client_secret=demoAppSecret【客户端授权模式-password】 客户端模式需要参数:grant_type,client_id,client_secret http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=demoApp&client_secret=demoAppSecret【授权码模式-code】 获取code http://localhost:8080/oauth/authorize?response_type=code&client_id=demoApp&redirect_uri=http://baidu.com 通过code换token http://localhost:8080/oauth/token?grant_type=authorization_code&code=Filepd&client_id=demoApp&client_secret=demoAppSecret&redirect_uri=http://baidu.com
祝君好运!
转载于:https://www.cnblogs.com/wookong/p/9244132.html
springboot集成Spring Security oauth2(八)相关推荐
- SpringBoot集成Spring Security —— 第二章自动登录
文章目录 一.修改login.html 二.两种实现方式 2.1 Cookie 存储 2.2 数据库存储 2.2.1 基本原理 2.2.2 代码实现 三.运行程序 在上一章:SpringBoot集成S ...
- SpringBoot集成Spring Security(二)注册 、密码加密、修改密码
SpringBoot集成Spring Security(一)登录注销 写在前面 上一节创建了项目并且利用Spring Security完成了登录注销功能,这里继续说一下注册.密码加密和找回密码,代码注 ...
- SpringBoot集成Spring Security(一)登录注销
同个人网站 https://www.serendipper-x.cn/,欢迎访问 ! SpringBoot集成Spring Security(二)注册 .密码加密.修改密码 写在前面 Spring S ...
- SpringBoot集成Spring Security(2)——自动登录
在上一章:SpringBoot集成Spring Security(1)--入门程序中,我们实现了入门程序,本篇为该程序加上自动登录的功能. 文章目录 一.修改login.html 二.两种实现方式 2 ...
- SpringBoot 集成 Spring Security
Spring Security Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架.它实际上是保护基于spring的应用程序的标准. Spring Security是一个 ...
- SpringBoot集成Spring Security(1)——入门程序
因为项目需要,第一次接触 Spring Security,早就听闻 Spring Security 功能强大但上手困难,学习了几天出入门道,特整理这篇文章希望能让后来者少踩一点坑(本文附带实例程序,请 ...
- springboot集成spring security实现登录和注销
文章目录 一.导入坐标 二.Users实体类及其数据库表的创建 三.controller,service,mapper层的实现 四.核心–编写配置文件 五.页面的实现 运行结果 一.导入坐标 < ...
- springboot集成spring security安全框架入门篇
一. :spring security的简介 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下 ...
- SpringBoot集成Spring Security(3)——异常处理
源码地址:https://github.com/jitwxs/blog_sample 文章目录 一.常见异常 二.源码分析 三.处理异常 不知道你有没有注意到,当我们登陆失败时候,Spring sec ...
最新文章
- 搭建Modelsim SE仿真环境-使用do文件仿真
- C++点操作符和箭头操作符
- 怎么去大蒜味(一定要看拉) - 生活至上,美容至尚!
- (一)Git学习记录(不断更新)
- ACMMM2021|在多模态训练中融入“知识+图谱”:方法及电商应用实践
- HTML标签的书写和嵌套规范
- activiti 功能概述_子串功能概述
- 技术人的年货福利:百宝黑皮书在手,2020年技术栈变革一次看透 | 免费下载
- 将python程序打包成exe
- jQuery中,$.extend,$obj.extend和$.fn.extend三者的区别
- VCS学习(2)debug simulation mismatches
- asp使用Jmail发送含任意内嵌附件和附件的Email函数
- dreamweaver序列号免费_dreamweaver8【dreamweaver8序列号】dreamweaver8注册码序列号简体中文版...
- iOS开发系列--音频播放、录音、视频播放、拍照、视频录制 (转)
- 嵌入式中的 C 语言
- uniapp调起打印机(调起第三方打印软件)适用app,将页面生成图片打印的两种方式
- X1000之LCD部分的翻译
- python画多层次五角星
- php根据键值排序,数组根据某个键值排序
- DVE 查看覆盖率方法