Java中的单点登录实现:OAuth2与JWT

ops/2024/9/23 9:31:15/

Java中的单点登录实现:OAuth2与JWT

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天我们来探讨在Java中如何使用OAuth2与JWT实现单点登录(SSO)。

一、单点登录概述

单点登录(Single Sign-On, SSO)是一种认证机制,允许用户在多个应用系统中使用一个账户登录一次,即可访问所有相互信任的应用系统。OAuth2和JWT是实现单点登录的两个重要技术。

二、OAuth2简介

OAuth2(Open Authorization)是一个用于资源授权的开放标准,允许第三方应用以有限的访问权限访问用户的资源,而无需将用户的凭据暴露给第三方。

三、JWT简介

JWT(JSON Web Token)是一种紧凑且自包含的令牌格式,用于在各方之间传递信息。JWT可以通过数字签名验证其真实性,且可以携带用户的认证信息。

四、Spring Boot项目配置

首先,我们需要创建一个Spring Boot项目,并添加必要的依赖。以下是Maven配置:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>

五、OAuth2认证服务器配置

我们使用Spring Security OAuth2来配置认证服务器,生成和验证JWT令牌。

1. 创建授权服务器配置

java">package cn.juwatech.config;import org.springframework.context.annotation.Configuration;
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.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("client-id").secret("{noop}client-secret").authorizedGrantTypes("password", "refresh_token").scopes("read", "write").accessTokenValiditySeconds(3600).refreshTokenValiditySeconds(7200);}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {endpoints.tokenStore(tokenStore()).accessTokenConverter(accessTokenConverter());}public TokenStore tokenStore() {return new JwtTokenStore(accessTokenConverter());}public JwtAccessTokenConverter accessTokenConverter() {JwtAccessTokenConverter converter = new JwtAccessTokenConverter();converter.setSigningKey("secret-key");return converter;}
}

2. 创建资源服务器配置

java">package cn.juwatech.config;import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(ResourceServerSecurityConfigurer resources) {resources.resourceId("resource-id").stateless(true);}@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/api/**").authenticated().antMatchers("/").permitAll();}
}

六、定义用户服务

定义用户服务类,用于处理用户的认证和授权:

java">package cn.juwatech.service;import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import java.util.Collections;@Service
public class CustomUserDetailsService implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {if ("user".equals(username)) {return new User("user", "{noop}password", Collections.emptyList());}throw new UsernameNotFoundException("User not found");}
}

七、实现RESTful接口

实现一个简单的RESTful接口,只有通过认证的用户才能访问:

java">package cn.juwatech.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/api")
public class ApiController {@GetMapping("/hello")public String hello() {return "Hello, authenticated user!";}
}

八、配置安全配置类

配置Spring Security以支持OAuth2和JWT:

java">package cn.juwatech.config;import cn.juwatech.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate CustomUserDetailsService userDetailsService;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/oauth/token").permitAll().anyRequest().authenticated();}@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Beanpublic PasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance();}
}

九、测试单点登录

启动Spring Boot应用,使用Postman测试OAuth2授权和JWT令牌。

  1. 获取令牌:

    • 请求:POST /oauth/token
    • 请求体:grant_type=password&username=user&password=password&client_id=client-id&client_secret=client-secret
    • 响应:返回包含访问令牌的JSON对象。
  2. 访问受保护的资源:

    • 请求:GET /api/hello
    • 头部:Authorization: Bearer {access_token}
    • 响应:Hello, authenticated user!

总结

本文介绍了如何使用Spring Boot构建一个基于OAuth2和JWT的单点登录系统。通过配置授权服务器、资源服务器、用户服务和安全配置,我们实现了一个简单且安全的RESTful微服务。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!


http://www.ppmy.cn/ops/87461.html

相关文章

PyCharm 2024.1最新变化

1、Hugging Face 集成&#xff1a; PyCharm 现在集成了对 Hugging Face 模型和数据集的支持&#xff0c;允许用户直接在 IDE 内预览模型和数据集的文档。当鼠标悬停在模型或数据集名称上时&#xff0c;IDE 将显示一个弹出窗口&#xff0c;其中包含相关的描述信息&#…

【计算机视觉】基本概念和应用

计算机视觉&#xff1a;基本概念和应用 目录 引言计算机视觉的基本概念 图像处理与图像分析特征提取与表示机器学习与深度学习 计算机视觉的关键技术 图像分类目标检测图像分割姿态估计图像生成与风格迁移 计算机视觉的应用 自动驾驶医疗影像智能监控增强现实与虚拟现实 计算…

反序列化靶机serial复现

靶机描述 今天研究一下php反序列化&#xff0c;靶机serial实战。目标为获取root权限。 ------------------------------------- 靶机信息 可以去vulhub上下载此靶机:serial: 1 ~ VulnHub下载好&#xff0c;之后&#xff0c;使用Vmware新建虚拟机打开&#xff1a; 渗透测试过程…

创建了Vue项目,需要导入什么插件以及怎么导入

如果你不知道怎么创建Vue项目,建议可以看一看这篇文章 怎么安装Vue的环境和搭建Vue的项目-CSDN博客 1.在idea中打开目标文件 2.系在一个插件Vue.js 3.下载ELement UI 在Terminal中输入 # 切换到项目根目录 cd vueadmin-vue # 或者直接在idea中执行下面命令 # 安装element-u…

Spring boot 整合influxdb2

一.服务安装 docker search influxdb docker pull influxdb docker run -dit --name influxdb --restart always -p 8086:8086 -v /dp/docker/file/influxdb:/var/lib/influxdb influxdb 访问8086 初始化 账号组织和新建bucket 创建密钥 这些豆记录下来 二.项目配置 引入依赖…

HiveSQL题——炸裂+开窗

一、每个学科的成绩第一名是谁&#xff1f; 0 问题描述 基于学生成绩表输出每个科目的第一名是谁呢&#xff1f; 1 数据准备 with t1 as(selectzs as name,[{"Chinese":80},{"Math":70},{"English"…

QML编程知识——Quick动画类型详解及示例

目录 引言 一、动画的基本概念 常用的动画类型 二、动画的应用示例 1. 属性动画&#xff08;PropertyAnimation&#xff09; 2. 数值动画&#xff08;NumberAnimation&#xff09; 3. 颜色动画&#xff08;ColorAnimation&#xff09; 4. 旋转动画&#xff08;Rotation…

二叉搜索树,Map,Set,LeetCode刷题

二叉搜索树&#xff0c;Map&#xff0c;Set 1. 二叉搜索树2. 二叉搜索树的模拟实现1.1 插入操作1.2 查找操作1.3 删除操作 3. 二叉搜索树时间复杂度分析4. TreeMap和TreeSet5. Map5.1 Map的常用方法5.2 Map.Entry<K,V> 6. Set6.1 Set的常用方法 LeetCode刷题1. 二叉搜索树…