前情回顾

前几节分享了OAuth2的流程与授权码模式和隐式授权模式两种的Demo,我们了解到授权码模式是OAuth2四种模式流程最复杂模式,复杂程度由大至小:授权码模式 > 隐式授权模式 > 密码模式 > 客户端模式

其中密码模式的流程是:让用户填写表单提交到授权服务器,表单中包含用户的用户名、密码、客户端的id和密钥的加密串,授权服务器先解析并校验客户端信息,然后校验用户信息,完全通过返回access_token,否则默认都是401 http状态码,提示未授权无法访问

本文目标

编写与说明密码模式的Spring Security Oauth2的demo实现,让未了解过相关知识的读者对此授权流程有个更直观的概念

以下分成授权服务器与资源服务器分别进行解释,只讲关键部分,详情见Github:https://github.com/hellxz/spring-security-oauth2-learn

搭建密码模式授权服务器

代码结构与之前两个模式相同,这里便不再进行说明

SecurityConfig配置

package com.github.hellxz.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
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.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils; import java.util.ArrayList;
import java.util.Collections; @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
} @Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
} @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("hellxz")
.password(passwordEncoder().encode("xyz"))
.authorities(new ArrayList<>(0));
} @Override
protected void configure(HttpSecurity http) throws Exception {
//所有请求必须认证
http.authorizeRequests().anyRequest().authenticated();
}
}

基本的SpringSecurity的配置,开启Spring Security的Web安全功能,填了一个用户信息,所有资源必须经过授权才可以访问

AuthorizationConfig授权服务器配置

package com.github.hellxz.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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; @Configuration
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter { @Autowired
private AuthenticationManager authenticationManager;//密码模式需要注入认证管理器 @Autowired
public PasswordEncoder passwordEncoder; //配置客户端
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//@formatter:off
clients.inMemory()
.withClient("client-a")
.secret(passwordEncoder.encode("client-a-secret"))
.authorizedGrantTypes("password") //主要是这里,开始了密码模式
.scopes("read_scope");
//@formatter:on
} @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);//密码模式必须添加authenticationManager
} @Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients()
.checkTokenAccess("isAuthenticated()");
}
}

这里开启了授权服务器的功能,与上几篇文章中不同的是注入了AuthenticationManager,以及在configure(AuthorizationServerEndpointsConfigurer endpoints)方法中设置了AuthenticationManager

application.properties配置sever.port=8080

搭建资源服务器

这里的关键就是ResourceConfig,配置比较简单与其它几个模式完全一致,模式的不同主要表现在授权服务器与客户端服务器上,资源服务器只做token的校验与给予资源

package com.github.hellxz.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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.security.oauth2.provider.token.RemoteTokenServices; @Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter { @Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
} @Primary
@Bean
public RemoteTokenServices remoteTokenServices() {
final RemoteTokenServices tokenServices = new RemoteTokenServices();
//设置授权服务器check_token端点完整地址
tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
//设置客户端id与secret,注意:client_secret值不能使用passwordEncoder加密!
tokenServices.setClientId("client-a");
tokenServices.setClientSecret("client-a-secret");
return tokenServices;
} @Override
public void configure(HttpSecurity http) throws Exception {
//设置创建session策略
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
//@formatter:off
//所有请求必须授权
http.authorizeRequests()
.anyRequest().authenticated();
//@formatter:on
} @Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId("resource1").stateless(true);
}
}

ResourceController主要接收一个用户名,返回一个username与email的json串

application.properties设置server.port=8081

准备工作到这里就差不多了,开始测试

测试流程

这里客户端使用postman手动发送请求进行演示

  • 访问/oauth/token端点,获取token

    http://localhost:8080/oauth/token?username=hellxz&password=xyz&scope=read_scope&grant_type=password

    请求头:

    请求体:

  • token返回值

    {
    "access_token": "4a3c351d-770d-42aa-af39-3f54b50152e9",
    "token_type": "bearer",
    "expires_in": 43199,
    "scope": "read_scope"
    }
  • 使用token调用资源,访问http://localhost:8081/user/hellxz001,注意使用token添加Bearer请求头

    相当于在Headers中添加 Authorization:Bearer 4a3c351d-770d-42aa-af39-3f54b50152e9

  • 资源正确返回

尾声

本文仅说明密码模式的精简化配置,某些部分如资源服务再访问授权服务去校验token这部分生产环境可能会换成Jwt、Redis等tokenStore实现,授权服务器中的用户信息与客户端信息生产环境应从数据库中读取,对应Spring Security的UserDetailsService实现类或用户信息的Provider等

最近发现博客写得相对较长,一方面有相当大的重复解释代码的部分,另一方面是代码很多不关键的地方也直接全贴出来了,博客长了代码全了,读者容易失去阅读的兴趣与探索实践的欲望。代码不全会直接贴出源码地址,暂时就这样,把这几篇关于OAuth2授权模式demo的文章赶出来

代码早就写完了,下周可能要开始加班了,先把这些已经完成的部分写出来,后续有什么新的知识点才有时间记

Spring Security OAuth2 Demo —— 密码模式(Password)的更多相关文章

  1. Spring Security OAuth2 Demo —— 客户端模式(ClientCredentials)

    前情回顾 前几节分享了OAuth2的流程与其它三种授权模式,这几种授权模式复杂程度由大至小:授权码模式 > 隐式授权模式 > 密码模式 > 客户端模式 本文要讲的是最后一种也是最简单 ...

  2. Spring Security OAuth2 Demo —— 隐式授权模式(Implicit)

    本文可以转载,但请注明出处https://www.cnblogs.com/hellxz/p/oauth2_impilit_pattern.html 写在前面 在文章OAuth 2.0 概念及授权流程梳 ...

  3. Spring Security OAuth2 Demo

    Spring Security OAuth2 Demo 项目使用的是MySql存储, 需要先创建以下表结构: CREATE SCHEMA IF NOT EXISTS `alan-oauth` DEFA ...

  4. Spring Security OAuth2 Demo —— 授权码模式

    本文可以转载,但请注明出处https://www.cnblogs.com/hellxz/p/oauth2_oauthcode_pattern.html 写在前边 在文章OAuth 2.0 概念及授权流 ...

  5. 使用Spring Security Oauth2完成RESTful服务password认证的过程

            摘要:Spring Security与Oauth2整合步骤中详细描述了使用过程,但它对于入门者有些重量级,比如将用户信息.ClientDetails.token存入数据库而非内存.配置 ...

  6. Spring Security OAuth2 Demo -- good

    1. 添加依赖授权服务是基于Spring Security的,因此需要在项目中引入两个依赖: <dependency> <groupId>org.springframework ...

  7. Spring Security OAuth2 授权码模式

     背景: 由于业务实现中涉及到接入第三方系统(app接入有赞商城等),所以涉及到第三方系统需要获取用户信息(用户手机号.姓名等),为了保证用户信息的安全和接入方式的统一, 采用Oauth2四种模式之一 ...

  8. Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战

    一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...

  9. Spring Security 解析(五) —— Spring Security Oauth2 开发

    Spring Security 解析(五) -- Spring Security Oauth2 开发   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决 ...

随机推荐

  1. 阿里云开源 image-syncer 工具,容器镜像迁移同步的终极利器

    为什么要做这个工具? 由于阿里云上的容器服务 ACK 在使用成本.运维成本.方便性.长期稳定性上大大超过公司自建自维护 Kubernets 集群,有不少公司纷纷想把之前自己维护 Kubernetes ...

  2. B2B市场新的营销思路

    随着互联网+时代的到来,企业与企业之间的联系已经慢慢从传统的服务模式转变为网上服务,企业与企业之间通过网络,进行数据信息的交换.传递,开展交易活动的商业模式我们称之为B2B B2B使企业大大节约了企业 ...

  3. Windows下搭建远程Linux主机的图形化本地开发环境

    在实际开发中,项目的类生产.生产环境一般都是选择Linux为服务器进行部署. 相应的,我们的开发最好也在Linux环境下进行,否则容易引发其他的问题,比如不同环境下功能不一致.库依赖差异等. 但是Li ...

  4. 【ABP】 动态菜单修改过程asp.netcore+vue

    无论用什么框架,第一件事情就是实现动态菜单,从数据库中读取菜单配置项输出前台,网上翻了一大堆翻译文档,也看了官方英文文档,关键点在于如何实现NavigationProvider和在前端调用abp.na ...

  5. 精通awk系列(8):awk划分字段的3种方式

    回到: Linux系列文章 Shell系列文章 Awk系列文章 详细分析awk字段分割 awk读取每一条记录之后,会将其赋值给$0,同时还会对这条记录按照预定义变量FS划分字段,将划分好的各个字段分别 ...

  6. centos7 设置连接无线wifi

    安装系统后,首先要联网. 1.首先使用网线连接,之后尝试ping www.baidu.com我的是自动通的 2.需要查看网卡型号,先安装工具 yum -y install pciutils* 3.查看 ...

  7. HTTP基础及telnet基本用法

    HTTP概况 ​ 20世纪90年代初期,一个主要的新兴应用即万维网(World Wide Web)登上了舞台.Web是一个引起公众注意的因特网应用.Web的应用层协议是超文本传输协议(HTTP),它是 ...

  8. 20191121-7 Scrum立会报告+燃尽图 03

    此作业的要求参见https://edu.cnblogs.com/campus/nenu/2019fall/homework/10067一.小组情况 队名:扛把子 组长:孙晓宇 组员:宋晓丽 梁梦瑶 韩 ...

  9. 胜利点组——“萌猿填词”微信小程序评价

    此作业要求参见https://edu.cnblogs.com/campus/nenu/2019fall/homework/9860 1.根据(不限于)NABCD评论作品的选题; (1).你的创意解决了 ...

  10. odoo12 修行基础篇之 添加字段 (一)

    本人刚刚接触odoo12,大概有2个多月的时间,这两天有点时间,就集中写下博客. 本来是打算整理成笔记,想到这段时间的开发经历,着实感觉网上有关odoo的资料太少,学习资料也不多,既然与odoo有缘, ...