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

本文详细介绍了在SpringSecurity5中配置OAuth2资源服务器,包括添加依赖、设置JWT验证、以及作为客户端的应用配置。还展示了如何结合使用OAuth2和JWT进行安全认证,包括自定义JwtAuthenticationConverter实现权限管理。
摘要由CSDN通过智能技术生成

目录

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客户端配置。

  • 38
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ead_Y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值