Auth2.0实战案例

简介: 本项目基于Spring Boot与Spring Cloud构建,实现OAuth2四种授权模式。通过父工程统一版本管理,搭建授权服务器与资源服务器,集成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

访问资源服务

相关文章
|
2月前
|
安全 Java 开发工具
SpringSecurity工程搭建与验证
本文介绍如何基于阿里云脚手架快速搭建SpringBoot工程(选用2.7.6版本),并整合Spring Security。内容涵盖项目创建、代码导入、Web依赖引入、接口编写与验证,以及Security依赖添加后的登录认证测试,最终实现安全访问控制。完整代码见GitHub仓库Day01分支。
|
存储 人工智能 运维
阿里云 Tair 基于 3FS 工程化落地 KVCache:企业级部署、高可用运维与性能调优实践
阿里云 Tair KVCache 团队联合硬件团队对 3FS 进行深度优化,通过 RDMA 流量均衡、小 I/O 调优及全用户态落盘引擎,提升 4K 随机读 IOPS 150%;增强 GDR 零拷贝、多租户隔离与云原生运维能力,构建高性能、高可用、易管理的 KVCache 存储底座,助力 AI 大模型推理降本增效。
|
2月前
|
人工智能 安全 前端开发
AgentScope Java v1.0 发布,让 Java 开发者轻松构建企业级 Agentic 应用
AgentScope 重磅发布 Java 版本,拥抱企业开发主流技术栈。
2713 40
|
2月前
|
Java Maven Spring
SpringBoot打包
本项目通过Maven打包为单一可执行JAR,内置配置文件与依赖,使用Spring Boot插件指定主类并repackage。执行`mvn clean package`构建后,通过`java -jar`运行(前台/后台),`kill -9 pid`停止服务。也可将JAR、依赖与配置分离部署,提升灵活性与维护性。(238字)
|
2月前
|
JSON 安全 Java
SpringBoot鉴权
本文介绍基于Spring Security与JWT实现客户端Token认证的完整方案,涵盖登录鉴权、Token生成与验证、角色权限控制等细节。通过自定义过滤器与认证组件,结合Redis或数据库可扩展实现高效安全的无状态认证体系,适用于Spring Boot微服务架构。
|
2月前
|
XML JSON Java
什么是RESTful
RESTful是一种基于资源的API设计规范,通过统一的HTTP方法(GET/POST/PUT/DELETE)对资源进行操作,提升接口的标准化与可维护性。它强调URI代表资源、使用名词而非动词、杜绝行为化路径,确保增删改查逻辑清晰、结构统一,便于理解和扩展,是现代Web API设计的最佳实践之一。
|
2月前
|
Java Shell 测试技术
Jmeter快速入门
JMeter是基于JDK的性能测试工具,需先安装配置JDK。下载解压后,通过双击或命令行启动,注意黑窗不可关闭。可设置中文语言(临时或修改jmeter.properties永久生效)。基本使用包括创建线程组、添加HTTP取样器、配置监听器(如结果树、汇总报告)以查看测试结果。
|
2月前
|
索引 关系型数据库 MySQL
MySQL索引有哪些类型
普通索引无限制;唯一索引列值唯一,可含空值;主键索引是唯一的非空索引,每表仅一个;组合索引由多列组成,提升联合查询效率;全文索引对文本分词,支持关键词搜索。
|
2月前
|
存储 运维 Java
微服务概述
本文对比单体与微服务架构,阐述微服务通过业务拆分、独立部署、轻量通信实现高内聚、低耦合,具备技术多元、扩展性强等优点,但也带来运维复杂、分布式事务等挑战。结合SpringCloud等技术可构建高效微服务体系。(238字)
|
2月前
|
SpringCloudAlibaba Java Nacos
SpringCloud概述
Spring Cloud是微服务架构的统一解决方案,弥补了分散技术栈的不足。它具备约定大于配置、组件丰富、开箱即用等特点,支持云原生应用。版本以地铁站命名,避免与子项目冲突。Spring Cloud Alibaba融合阿里系开源组件如Nacos、Sentinel、Seata等,弥补Netflix套件停更短板,提供更完整、经生产验证的微服务生态,成为主流选择。