OAuth2.0实战案例

本文涉及的产品
PolarSearch,搜索节点 4核8GB
PolarDB Agent Express,2核4GB
PolarDB Agent Flow,2核4GB
简介: 本项目基于Spring Boot与Spring Cloud构建,实现OAuth2四种授权模式。通过父工程统一版本管理,分别搭建授权服务器(9001端口)与资源服务器(9002端口),集成Spring Security、MyBatis及MySQL,完成认证授权流程。支持授权码、简化、密码及客户端四种模式,实现安全的分布式权限控制。

1.创建父工程

com.itheima

springboot_security_oauth
1.0-SNAPSHOT


org.springframework.boot
spring-boot-starter-parent
2.1.3.RELEASE




Greenwich.RELEASE




org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import






spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot

true



spring-milestones
Spring Milestones
https://repo.spring.io/milestone

false



2.创建资源模块
2.1 创建工程并导入依赖

springboot_security_oauth
com.itheima
1.0-SNAPSHOT

4.0.0
oauth_source



org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-security


org.springframework.cloud
spring-cloud-starter-oauth2


mysql
mysql-connector-java
5.1.47


org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.0


2.2 创建配置文件
server:
port: 9002
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: root
main:
allow-bean-definition-overriding: true
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
2.3 创建启动类
@SpringBootApplication
@MapperScan("com.itheima.mapper")
public class OAuthSourceApplication {
public static void main(String[] args) {
SpringApplication.run(OAuthSourceApplication.class, args);
}
}
2.4 创建处理器
@RestController
@RequestMapping("/product")
public class ProductController {
@GetMapping
public String findAll(){
return "查询产品列表成功!";
}
}
3.创建授权模块
3.1 创建工程并导入依赖


springboot_security_oauth
com.itheima
1.0-SNAPSHOT

4.0.0

oauth_server



org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-security


org.springframework.cloud
spring-cloud-starter-oauth2


mysql
mysql-connector-java
5.1.47


org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.0


3.2 创建配置文件
server:
port: 9001
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: root
main:
allow-bean-definition-overriding: true # 这个表示允许我们覆盖OAuth2放在容器中的bean对象,一定要配置
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
3.3 创建启动类
@SpringBootApplication
@MapperScan("com.itheima.mapper")
public class OauthServerApplication {
public static void main(String[] args) {
SpringApplication.run(OauthServerApplication.class, args);
}
}
3.4 创建配置类
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService myCustomUserService;
@Bean
public BCryptPasswordEncoder myPasswordEncoder(){
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    //所有资源必须授权后访问
    .anyRequest().authenticated()
    .and()
    .formLogin()
    .loginProcessingUrl("/login")
    .permitAll()//指定认证页面可以匿名访问
    //关闭跨站请求防护
    .and().csrf().disable();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    //UserDetailsService类
    auth.userDetailsService(myCustomUserService)
    //加密策略
    .passwordEncoder(myPasswordEncoder());
}

//AuthenticationManager对象在OAuth2认证服务中要使用,提取放入IOC容器中
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

}
3.5 创建OAuth2授权配置类
@Configuration
@EnableAuthorizationServer
public class OauthServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private DataSource dataSource;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;

//从数据库中查询出客户端信息
@Bean
public JdbcClientDetailsService clientDetailsService() {
    return new JdbcClientDetailsService(dataSource);
}

//token保存策略
@Bean
public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource);
}

//授权信息保存策略
@Bean
public ApprovalStore approvalStore() {
    return new JdbcApprovalStore(dataSource);
}

//授权码模式专用对象
@Bean
public AuthorizationCodeServices authorizationCodeServices() {
    return new JdbcAuthorizationCodeServices(dataSource);
}

//指定客户端登录信息来源
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(clientDetailsService());
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.allowFormAuthenticationForClients();
    oauthServer.checkTokenAccess("isAuthenticated()");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints
    .approvalStore(approvalStore())
    .authenticationManager(authenticationManager)
    .authorizationCodeServices(authorizationCodeServices())
    .tokenStore(tokenStore());
}

}
4.测试
4.1 授权码模式测试
在地址栏访问地址
http://localhost:9001/oauth/authorize?response_type=code&client_id=heima_one
跳转到SpringSecurity默认认证页面,提示用户登录个人账户【这里是sys_user表中的数据】

登录成功后询问用户是否给予操作资源的权限,具体给什么权限。Approve是授权,Deny是拒绝。
这里我们选择read和write都给予Approve。

点击Authorize后跳转到回调地址并获取授权码

使用授权码到服务器申请通行令牌token

重启资源服务器,然后携带通行令牌再次去访问资源服务器,大功告成!

4.2 简化模式测试
在地址栏访问地址
http://localhost:9001/oauth/authorize?response_type=token&client_id=heima_one
由于上面用户已经登录过了,所以无需再次登录,其实和上面是有登录步骤的,这时,浏览器直接返回了token

直接访问资源服务器

4.3 密码模式测试
申请token

访问资源服务器

4.4 客户端模式测试
申请token

访问资源服务

相关文章
|
机器学习/深度学习 人工智能 自然语言处理
Informer:用于长序列时间序列预测的新型Transformer
Informer:用于长序列时间序列预测的新型Transformer
2758 0
Informer:用于长序列时间序列预测的新型Transformer
|
存储 安全 数据安全/隐私保护
OAuth 2.0 的授权机制
【10月更文挑战第5天】
1340 2
|
安全 Linux 网络安全
Docker部署ssh连接工具webssh2
【8月更文挑战第2天】Docker部署ssh连接工具webssh2
2097 6
Docker部署ssh连接工具webssh2
|
运维 安全 网络安全
"革新远程访问体验:Docker化部署webssh2,一键启动Web SSH客户端,让远程管理如虎添翼!"
【8月更文挑战第2天】Docker作为软件开发与运维的关键工具,以其轻量级、可移植及强隔离特性简化了应用部署。结合webssh2这一开源Web SSH客户端,可通过浏览器安全便捷地访问SSH服务器,无需额外软件。首先确保已安装Docker,接着拉取webssh2镜像并运行容器,映射端口以便外部访问。配置好SSH服务器后,通过浏览器访问指定URL即可开始SSH会话。此方案不仅提升了用户体验,还加强了访问控制与系统安全。
1560 7
|
前端开发 JavaScript C#
C#开发者的新天地:Blazor如何颠覆传统Web开发,打造下一代交互式UI?
【8月更文挑战第28天】Blazor 是 .NET 生态中的革命性框架,允许使用 C# 和 .NET 构建交互式 Web UI,替代传统 JavaScript。本文通过问答形式深入探讨 Blazor 的基本概念、优势及应用场景,并指导如何开始使用 Blazor。Blazor 支持代码共享、强类型检查和丰富的生态系统,简化 Web 开发流程。通过简单的命令即可创建 Blazor 应用,并利用其组件化和数据绑定特性快速搭建界面。无论对于 .NET 还是 Web 开发者,Blazor 都是一个值得尝试的新选择。
1196 1
|
负载均衡 安全 Ubuntu
docker部署keepalived(搭建keepalived)
将HTML或其他格式的内容转化为图片是Web开发中的一个较为常见需求。在某些特殊场景下,比如生成用户看不到的信息图片或进行内容的快速截图,该功能变得尤为重要。部署Keepalived至Docker容器提供了一种便捷方式来保证服务的高可用性。通过上述步骤,你可以轻松地在自己的项目中实现这一点,从而确保业务的连续性和稳定性。
1021 4
|
Kubernetes 网络安全 API
在K8S中,集群内有个节点not ready,如何排查?
在K8S中,集群内有个节点not ready,如何排查?
小狼毫Rime输入法简单配置指南
小狼毫Rime输入法简单配置指南
5197 4
|
Java 测试技术
【Java】已解决java.lang.UnsupportedOperationException异常
【Java】已解决java.lang.UnsupportedOperationException异常
3064 0
|
Ubuntu Linux 网络安全
Git on Ubuntu 22.04: 终极安装与配置指南
【4月更文挑战第21天】
5688 0
Git on Ubuntu 22.04: 终极安装与配置指南

热门文章

最新文章