当前位置: 首页 > news >正文

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

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. 创建授权服务器配置

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. 创建资源服务器配置

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();}
}

六、定义用户服务

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

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接口,只有通过认证的用户才能访问:

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:

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微服务。

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

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • (~_~)
  • 若依关闭验证码功能
  • Error running appInvalid argument : Argument invalidIport)
  • 前后端完全分离实现登录和退出
  • CTFHUB-文件上传-无验证
  • EAK水冷电阻60kW负载制动电阻器
  • PHP健身微信小程序系统源码
  • 更换收银系统时如何迁移会员数据
  • 简明中医辨证施治小程序
  • 常用传感器讲解十五--触摸传感器(KY-036)
  • 从编程小白到大神的华丽蜕变:大学新生的编程成长秘籍!
  • 数据库魔法:SQL Server中自定义分区函数的奥秘
  • 郑州办理建筑设计农林开发乙级资质
  • 顶刊TPAMI 2024!无需全标注,仅用少量涂鸦标注即可获得确定和一致的语义分割预测结果...
  • [渗透测试学习] PermX-HackTheBox
  • 【从零开始安装kubernetes-1.7.3】2.flannel、docker以及Harbor的配置以及作用
  • Android Volley源码解析
  • Docker入门(二) - Dockerfile
  • es6要点
  • express.js的介绍及使用
  • Fundebug计费标准解释:事件数是如何定义的?
  • Git同步原始仓库到Fork仓库中
  • Iterator 和 for...of 循环
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • webpack4 一点通
  • Webpack入门之遇到的那些坑,系列示例Demo
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 从PHP迁移至Golang - 基础篇
  • 道格拉斯-普克 抽稀算法 附javascript实现
  • 浮动相关
  • 每天10道Java面试题,跟我走,offer有!
  • 你不可错过的前端面试题(一)
  • 前端每日实战:61# 视频演示如何用纯 CSS 创作一只咖啡壶
  • 强力优化Rancher k8s中国区的使用体验
  • 双管齐下,VMware的容器新战略
  • 正则学习笔记
  • const的用法,特别是用在函数前面与后面的区别
  • ​决定德拉瓦州地区版图的关键历史事件
  • # Redis 入门到精通(八)-- 服务器配置-redis.conf配置与高级数据类型
  • #Spring-boot高级
  • (1)常见O(n^2)排序算法解析
  • (3)选择元素——(17)练习(Exercises)
  • (8)STL算法之替换
  • (C#)一个最简单的链表类
  • (八十八)VFL语言初步 - 实现布局
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (顶刊)一个基于分类代理模型的超多目标优化算法
  • (三)c52学习之旅-点亮LED灯
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • (转)scrum常见工具列表
  • (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案一
  • (转)利用ant在Mac 下自动化打包签名Android程序
  • (转)重识new
  • ****** 二 ******、软设笔记【数据结构】-KMP算法、树、二叉树
  • .bat批处理(二):%0 %1——给批处理脚本传递参数