首页 > 其他分享 >基于security-oauth2-autoconfigure实现的OAuth2迁移到更现代的解决方案,Spring Security 5中使用OAuth2配合JWT实现安全认证

基于security-oauth2-autoconfigure实现的OAuth2迁移到更现代的解决方案,Spring Security 5中使用OAuth2配合JWT实现安全认证

时间:2024-03-22 09:59:34浏览次数:24  
标签:OAuth2 JWT springframework oauth2 服务器 客户端

目录

OAuth2 资源服务器配置

步骤 1:添加依赖

步骤 2:配置资源服务器

OAuth2 客户端配置(可选)

/**其他应用作为OAuth2客户端

步骤 1:添加依赖

步骤 2:配置OAuth 2.0客户端

/**应用同时作为OAuth2客户端

步骤 1:配置OAuth 2.0客户端

控制器示例

结合使用OAuth2与JWT


        在Spring Security 5中使用OAuth2配合JWT实现安全认证,可以通过资源服务器和客户端的方式来配置。这里,我将分别说明如何配置OAuth2资源服务器和客户端,以及如何结合JWT使用。

OAuth2 资源服务器配置

步骤 1:添加依赖

        首先,确保你的项目中加入了Spring Security和OAuth2资源服务器的依赖。以下是pom.xml文件中的示例配置:

<!-- Spring Boot Starter Security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- OAuth2 Resource Server -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<!-- OAuth2 Client -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

        确保你使用的是Spring Boot 2.1.x及以上版本,以获取完整的OAuth 2.0和JWT支持。

步骤 2:配置资源服务器

        然后,在application.yml(或application.properties)配置文件中,设置资源服务器应该如何验证传入的令牌。这通常需要指定JWT令牌的发行者和用于解码JWT的公钥或JWK端点。

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://your-auth-server.com # JWT发行者的URL
          # 或者,如果你有JWK端点,可以这么配置:
          # jwk-set-uri: https://your-auth-server.com/.well-known/jwks.json

        配置资源服务器的安全约束,可以通过继承WebSecurityConfigurerAdapter并重写configure(HttpSecurity http)方法来完成:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authz -> authz
                .antMatchers("/public/**").permitAll() // 允许访问公共路径
                .anyRequest().authenticated()) // 其他所有路径都需要认证
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
    }

    JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        // 在这里配置JWT转换器,例如根据JWT中的claims设置权限
        return converter;
    }
}

OAuth2 客户端配置(可选)

/**其他应用作为OAuth2客户端

步骤 1:添加依赖

        对于客户端,如果你需要通过OAuth2服务器获取JWT令牌以访问受保护的资源,你需要添加OAuth2客户端的依赖并进行相应配置。

        在pom.xml中添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

步骤 2:配置OAuth 2.0客户端

        在application.yml中配置客户端详情,例如:

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: your-client-id
            client-secret: your-client-secret
            scope: openid, profile, email
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/okta"
        provider:
          okta:
            issuer-uri: https://your-auth-server.com

        这将配置一个OAuth2客户端,用于通过Okta(或其他OAuth2兼容的授权服务器)执行OpenID Connect登录流程。

/**应用同时作为OAuth2客户端

步骤 1:配置OAuth 2.0客户端

        如果你的应用程序需要作为OAuth 2.0客户端,例如,需要使用第三方服务的用户信息,你可以在application.yml中配置客户端详情:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-client-id
            client-secret: your-client-secret
            scope: openid, profile, email
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://openidconnect.googleapis.com/v1/userinfo
            user-name-attribute: sub

控制器示例

        假设你已经配置了资源服务器和客户端(如果需要),你可以创建一个简单的REST控制器,展示如何利用安全上下文获取用户信息:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;

@RestController
public class UserController {

    @GetMapping("/user")
    public Map<String, Object> getUser(@AuthenticationPrincipal Jwt jwt) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", jwt.getClaimAsString("preferred_username"));
        userInfo.put("roles", jwt.getClaimAsStringList("roles"));
        return userInfo;
    }
}

结合使用OAuth2与JWT

        在Spring Security 5中,资源服务器和客户端配置使得与OAuth2和JWT结合使用变得更加简洁。资源服务器部分负责验证JWT令牌的有效性(例如,签名和发行者),而客户端部分则负责通过OAuth2流程从授权服务器获取JWT令牌。

        关于JWT的处理和转换,你可以通过自定义JwtAuthenticationConverter来实现,比如根据JWT中的claims来设置用户权限。此外,使用新的OAuth2登录和资源服务器支持,Spring Security提供了更加灵活的方式来处理安全性需求,包括更细粒度的安全规则和OAuth2客户端配置。

标签:OAuth2,JWT,springframework,oauth2,服务器,客户端
From: https://blog.csdn.net/Ead_Y/article/details/136837051

相关文章

  • 【SpringSecurity】十七、OAuth2授权服务器 + 资源服务器Demo
    文章目录0、库表准备:1、项目结构2、基于数据库的认证3、授权服务器配置4、授权服务器效果测试5、资源服务器配置相关......
  • JWT
    1、JWT定义JWT(JsonWebToken)是一种用于双方之间传递安全信息的简洁的、URL安全的表述性声明规范。JWT作为一个开放的标准( RFC7519 ),定义了一种简洁的,自包含的方法用于通信双方之间以Json对象的形式安全的传递信息。因为数字签名的存在,这些信息是可信的,JWT可以使用HMAC算法或......
  • JWT(JSON WEB TOKEN)是玩具吗
    JWT当然不是玩具,理解其设计意图,和适用场景自然会发现存在的就是有价值的JWT:JSONWebToken起源和定义JWT(JSONWebToken)是由IETF(InternetEngineeringTaskForce)基于RFC7519规范定义的。它是一种用于在网络应用间传递信息的标准方法。JWT最初由无状态的分布式应用场......
  • JWTBearer
    JWTBearer框架是.NET中一种基于JSONWebToken(JWT)实现的身份验证和授权框架。JWT是一种开放标准,用于在不同系统之间安全地传输信息。它使用JSON对象来表示声明,声明包含关于实体(通常是用户)的信息以及与该实体相关的元数据。这些声明可以被签名和/或加密,以确保只有授权用户可......
  • SSM整合Jwt
    #导入jwt依赖创键Util123#4.测试......
  • JWT令牌-登录认证
    1.JWT令牌组成Header(头),记录令牌类型和签名算法等PayLoad(载荷),携带自定义的信息Signature(签名),对头部和载荷进行加密计算得来用于登录认证承载业务数据,减少后续请求查询数据库的次数防篡改,保证信息的合法性和有效性2.使用引入java-jwt坐标调用API生成或验证......
  • JWT登录认证-项目BotBattle
    目录session授权认证原理密码存储与加密jwt(JSONWebToken)验证JWT的无状态认证机制实践与调试实现目标:在没有判断登录认证的情况下,访问任意界面,直接跳转到登录界面。添加SpringSecurity依赖来实现登录认证session授权认证原理实现config.SecurityConfig类SessionID相当......
  • Asp.net core使用Authentication使用jwt简单登录认证
    研究了两天,简单使用就这些,如果需要token续期或者刷新或者自定义校验处理需要重写比较麻烦。在controller中单独获取请求头可使用 HttpContext.Request.Headers["Authorization"]使用流程是:先认证登录->再校验权限Authentication->Authorization 安装依赖,.net8版......
  • jwt
    [jsonwebtoken挖坑]token令牌,注册时生成,登陆验证通过后下发//installnpminstalljsonwebtoken//生成consttoken='Bearer'+jwt.sign({userid:1},secret)//secret生成令牌加密用到的字符串,尽可能复杂一点//解析constdecode=jwt.ver......
  • 使用JWT进行授权认证
    .Net6WebAPI中1、安装组件(Nuget)Microsoft.AspNetCore.Authentication.JwtBearer2、Program.cs配置//授权认证(使用JWT)builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o=>{//私钥varsecretByte=Encoding.UTF8.GetBytes......