>  기사  >  Java  >  SpringBoot+SpringSecurity+JWT를 사용하여 시스템 인증 및 권한 부여를 구현하는 방법

SpringBoot+SpringSecurity+JWT를 사용하여 시스템 인증 및 권한 부여를 구현하는 방법

WBOY
WBOY앞으로
2023-05-14 20:16:041750검색

1. Spring Security 소개

Spring Security는 Spring의 핵심 프로젝트이며, 강력하고 사용자 정의가 가능한 인증 및 액세스 제어 프레임워크입니다. 이는 인증 및 권한 부여 기능은 물론 일반적인 공격에 대한 보호 기능을 제공하며 스프링 기반 애플리케이션을 보호하기 위한 사실상의 표준이 되었습니다.

Spring Boot는 스타터 종속성을 도입하여 사용할 수 있는 자동 구성을 제공합니다.
Spring Security 기능 요약:

  • 사용하기 쉽고 Spring Boot 스타터 종속성을 제공하며 Spring Boot 프로젝트와 쉽게 통합됩니다.

  • Professional, CSRF 보호, 클릭재킹 보호, XSS 보호 등을 제공하고 다양한 보안 헤더 통합(X-XSS-Protection, X-Frame-Options 등)을 제공합니다.

  • 비밀번호 암호화 저장소, 다중 암호화 알고리즘 지원

  • 뛰어난 확장성과 사용자 정의 가능

  • OAuth3 JWT 인증 지원

2.

JWT(Json 웹 토큰 )은 네트워크 애플리케이션 환경 간에 청구를 전송하기 위해 구현된 JSON 기반 개방형 표준(RFC 7519)입니다. 토큰은 특히 단일 서버 분산 사이트 클릭(SSO) 시나리오에 적합하도록 설계되었습니다. JWT 클레임은 일반적으로 리소스 서버에서 리소스를 쉽게 얻을 수 있도록 ID 공급자와 서비스 공급자 간에 인증된 사용자 ID 정보를 전달하는 데 사용됩니다. 또한 다른 비즈니스 논리(예: 권한 정보)에 필요한 일부 추가 클레임 정보를 추가할 수도 있습니다. 사용자에게 토큰이 부여되면 사용자는 토큰을 통해 서버의 리소스에 액세스할 수 있습니다.

3. Spring Boot는 Spring Security를 ​​통합합니다

이 문서에서는 다음과 같이 JDK 및 Spring Boot 버전의 사용을 보여줍니다.
Spring Boot: 2.7.2
JDK: 11
Spring Boot 버전마다 구성이 다르지만 원칙은 동일합니다.

Spring Boot 프로젝트의 pom.xml 파일에 다음 종속성을 추가합니다.

<!-- Spring Security的Spring boot starter,引入后将自动启动Spring Security的自动配置 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 下面的依赖包含了OAuth3 JWT认证实现 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth3-resource-server</artifactId>
</dependency>

위의 두 가지 종속성으로 충분합니다.

4. JWT 인증을 사용하도록 Spring Security 구성

참고: Spring Boot 버전마다 구성이 다르지만 이 문서에서는 Spring Boot: 2.7.2를 사용합니다.

주로 HttpSecurity Bean을 구성하여 SecurityFilterBean을 생성합니다. 구성은 다음과 같습니다.

import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth3.jwt.JwtDecoder;
import org.springframework.security.oauth3.jwt.JwtEncoder;
import org.springframework.security.oauth3.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth3.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth3.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth3.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth3.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.oauth3.server.resource.web.access.BearerTokenAccessDeniedHandler;
import org.springframework.security.web.SecurityFilterChain;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * Spring Security 配置
 *
 * @author cloudgyb
 * @since 2022/7/30 18:31
 */
@Configuration(proxyBeanMethods = false)
@EnableMethodSecurity
public class WebSecurityConfigurer {
    //使用RSA对JWT做签名,所以这里需要一对秘钥。
    //秘钥文件的路径在application.yml文件中做了配置(具体配置在下面)。
    @Value("${jwt.public.key}")
    private RSAPublicKey key; 
    @Value("${jwt.private.key}")
    private RSAPrivateKey priv;

     /**
      * 构建SecurityFilterChain bean
      */
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        //"/login"是系统的登录接口,所以需要匿名可访问
        http.authorizeRequests().antMatchers("/login").anonymous();
        //其他请求都需认证后才能访问
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                
                //采用JWT认证无需session保持,所以禁用掉session管理器
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                //login接口可能来自其他站点,所以对login不做csrf防护
                .csrf((csrf) -> csrf.ignoringAntMatchers("/login"))
                //配置认证方式为JWT,并且配置了一个JWT认证装换器,用于去掉解析权限时的SCOOP_前缀
                .oauth3ResourceServer().jwt().jwtAuthenticationConverter(
                        JwtAuthenticationConverter()
                );
        //配置认证失败或者无权限时的处理器
        http.exceptionHandling((exceptions) -> exceptions
                .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
                .accessDeniedHandler(new BearerTokenAccessDeniedHandler())
        );
         //根据配置生成SecurityFilterChain对象
        return http.build();
    }


    /**
     * JWT解码器,用于认证时的JWT解码 
     */
    @Bean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withPublicKey(this.key).build();
    }
    /**
     * JWT编码器,生成JWT
     */
    @Bean
    JwtEncoder jwtEncoder() {
        JWK jwk = new RSAKey.Builder(this.key).privateKey(this.priv).build();
        JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new NimbusJwtEncoder(jwks);
    }
    
    /**
     * JWT认证解码时,去掉Spring Security对权限附带的默认前缀SCOOP_
     */
    @Bean
    JwtAuthenticationConverter JwtAuthenticationConverter() {
        final JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
        final JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return jwtAuthenticationConverter;
    }
}

application.yml

jwt:
  private.key: classpath:app.key
  public.key: classpath:app.pub

위 구성에서는 Spring Boot 프로젝트의 Resource 디렉터리에 RSA 키 쌍을 생성해야 합니다.
다음 웹사이트를 사용하여 생성할 수 있습니다: http://tools.jb51.net/password/rsa_encode/, 참고: 키 형식은 PKCS#8을 사용하며 개인 키 비밀번호는 비어 있습니다.

한 가지 더 주목할 점은 코드에서 Spring Boot의 값 주입을 사용했다는 것입니다.

@Value("${jwt.public.key}")
 private RSAPublicKey key; 
@Value("${jwt.private.key}")
private RSAPrivateKey priv;

Spring Boot가 yaml 파일의 문자열에 해당하는 파일을 어떻게 RSAPublicKey 및 RSAPrivateKey로 변환하는지 궁금하십니까?
실제로 Spring Security는 우리를 위해 처리를 수행했으며 이는 Spring Security에서 ResourceKeyConverterAdapter 변환기를 구현하는 데 도움이 되었습니다. 더 깊은 이해를 위해 관련 소스 코드를 읽을 수 있습니다.

우리 프로젝트는 이제 JWT 인증을 지원합니다.
그러나 사용자는 인증을 통과한 다음 서버 리소스에 액세스하려면 요청 헤더 Authorization에 합법적인 JWT를 가지고 있어야 합니다. 그러면 사용자에게 합법적인 JWT를 발급하는 방법은 무엇입니까?
매우 간단합니다. 로그인 인터페이스를 제공하고, 사용자가 사용자 이름과 비밀번호를 입력하고, 매칭에 성공한 후 토큰을 발행할 수 있습니다.

사실 꼭 그렇게 할 필요는 없습니다. 제3자 인터페이스를 호출하는 등의 방법이 있습니다. 우리의 일반적인 접근 방식은 신청서가 승인된 후 먼저 제3자에게 신청하는 것입니다. 토큰. 이 과정은 위에서 로그인을 통과한 후 토큰을 발급받는 것과 동일합니다. 둘 다 합법적인 수단을 통해 토큰을 얻습니다!

5. 로그인 인터페이스 구현

로그인 인터페이스의 목적은 단 하나, 합법적인 사용자에게 토큰을 발행하는 것입니다!
로그인 API 인터페이스:

@RestController
public class SysLoginController {
    private final SysLoginService sysLoginService;

    public SysLoginController(SysLoginService sysLoginService) {
        this.sysLoginService = sysLoginService;
    }

    @PostMapping("/login")
    public String login(@RequestBody LoginInfo loginInfo) {
        return sysLoginService.login(loginInfo);
    }
}

로그인 로직 구현:

@Service
public class SysLoginService {
    private final JwtEncoder jwtEncoder;
    private final SpringSecurityUserDetailsService springSecurityUserDetailsService;

    public SysLoginService(JwtEncoder jwtEncoder, SpringSecurityUserDetailsService springSecurityUserDetailsService) {
        this.jwtEncoder = jwtEncoder;
        this.springSecurityUserDetailsService = springSecurityUserDetailsService;
    }

    public String login(LoginInfo loginInfo) {
        //从用户信息存储库中获取用户信息
        final UserDetails userDetails = springSecurityUserDetailsService.loadUserByUsername(loginInfo.getUsername());
        final String password = userDetails.getPassword();
        //匹配密码,匹配成功生成JWT令牌
        if (password.equals(loginInfo.getPassword())) {
            return generateToken(userDetails);
        }
        //密码不匹配,抛出异常,Spring Security发现抛出该异常后会将http响应状态码设置为401 unauthorized
        throw new BadCredentialsException("密码错误!");
    }

    private String generateToken(UserDetails userDetails) {
        Instant now = Instant.now();
        //JWT过期时间为36000秒,也就是600分钟,10小时
        long expiry = 36000L;
        String scope = userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(" "));
         //将用户权限信息使用空格分割拼为字符串,放到JWT的payload的scope字段中,注意不要改变scope这个属性,这是Spring Security OAuth3 JWT默认处理方式,在JWT解码时需要读取该字段,转为用户的权限信息!
        JwtClaimsSet claims = JwtClaimsSet.builder()
                .issuer("self")
                .issuedAt(now)
                .expiresAt(now.plusSeconds(expiry))
                .subject(userDetails.getUsername())
                .claim("scope", scope)
                .build();
        return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
    }
}

다른 비핵심 코드는 여기에 게시되지 않습니다. 자세한 내용은 https://github.com/cloudgyb/에 게시합니다. 봄 -보안 연구-jwt.

6. 테스트

postman을 사용하여 테스트하세요.
잘못된 비밀번호를 사용하면 인증이 실패했음을 나타내는 401 Unauthorized 상태 코드가 반환됩니다.

SpringBoot+SpringSecurity+JWT를 사용하여 시스템 인증 및 권한 부여를 구현하는 방법

올바른 사용자 이름과 비밀번호를 사용하세요.

SpringBoot+SpringSecurity+JWT를 사용하여 시스템 인증 및 권한 부여를 구현하는 방법

JWT 반환 토큰.

이 시점에서 클라이언트는 합법적인 토큰을 얻었으며 서버에서 액세스할 수 있는 리소스에 액세스할 수 있습니다.
테스트 인터페이스를 작성했습니다:

@RestController
public class HelloController {

    @GetMapping("/")
    @PreAuthorize("hasAuthority(&#39;test&#39;)")
    public String hello(Authentication authentication) {
        return "Hello, " + authentication.getName() + "!";
    }
}

이 인터페이스는 사용자에게 "테스트" 권한이 필요하지만 로그인한 사용자에게는 이 권한이 없습니다(단 하나의 앱 권한만 있음). 이때 인터페이스를 호출하세요.
먼저 , 이전 단계에서 로그인하세요. 토큰을 토큰에 붙여넣으세요.

SpringBoot+SpringSecurity+JWT를 사용하여 시스템 인증 및 권한 부여를 구현하는 방법

我们发送请求得到了403 Forbidden的响应,意思就是我们没有访问权限,此时我们将接口权限改为“app”:

@RestController
public class HelloController {

    @GetMapping("/")
    @PreAuthorize("hasAuthority(&#39;app&#39;)")
    public String hello(Authentication authentication) {
        return "Hello, " + authentication.getName() + "!";
    }
}

重启项目。再次发起请求:

SpringBoot+SpringSecurity+JWT를 사용하여 시스템 인증 및 권한 부여를 구현하는 방법

위 내용은 SpringBoot+SpringSecurity+JWT를 사용하여 시스템 인증 및 권한 부여를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제