>  기사  >  Java  >  SpringBoot 보안 관리의 OAuth2 프레임워크를 사용하는 방법

SpringBoot 보안 관리의 OAuth2 프레임워크를 사용하는 방법

WBOY
WBOY앞으로
2023-05-18 08:08:061237검색

OAuth3 소개

OAuth는 사용자가 타사 애플리케이션이 사용자의 개인 리소스(예: 아바타, 사진, 비디오 등)에 액세스할 수 있도록 허용하는 개방형 표준입니다. 비밀번호는 타사 애플리케이션에 제공됩니다.

사용자 이름과 비밀번호 대신 토큰을 사용하여 특정 서비스 제공업체에 저장된 데이터에 액세스하세요. 각 토큰은 특정 웹 사이트가 특정 기간 동안 특정 리소스에 액세스할 수 있도록 승인합니다.

OAuth를 사용하면 사용자는 제3자 웹사이트에 모든 정보가 아닌 다른 리소스 서버에 저장된 특정 정보에 유연하게 액세스할 수 있는 권한을 부여할 수 있습니다. 예를 들어, 사용자가 QQ를 통해 Zhihu에 로그인하려는 경우 Zhihu는 제3자 애플리케이션입니다. Zhihu가 사용자의 일부 기본 정보에 액세스하려면 사용자가 Zhihu에게 QQ 사용자에게 알리는 것이 필요합니다. 이름과 비밀번호가 있으면 Zhihu는 사용자의 모든 데이터에 접근할 수 있으며 사용자만이 비밀번호를 변경하여 권한을 취소할 수 있습니다. 이 인증 방법은 OAuth를 사용하면 이 문제를 잘 해결할 수 있습니다.

토큰을 사용하면 사용자는 제3자 애플리케이션에 대한 권한을 유연하게 승인하거나 철회할 수 있습니다. OAuth 2는 OAuth 프로토콜의 다음 버전이지만 OAuth 1.0과 역호환되지는 않습니다.

OAuth 2는 클라이언트 개발자를 위한 단순성에 중점을 두는 동시에 웹 애플리케이션, 데스크톱 애플리케이션, 모바일 장치 및 거실 장치에 대한 특수 인증 프로세스를 제공합니다. 기존의 웹 개발 로그인 인증은 일반적으로 Session 기반이지만, 프론트엔드와 백엔드가 분리된 아키텍처에서 Session을 계속 사용하게 되면 모바일 단말(Android, IOS, WeChat 애플릿 등)에서 인증을 수행하지 못하기 때문에 많은 불편을 겪게 됩니다. 쿠키(WeChat 애플릿)을 지원하거나 사용이 매우 불편할 경우 OAuth 2 인증을 사용하면 해결할 수 있습니다.

OAuth3 역할

먼저 OAuth 2의 몇 가지 기본 역할을 이해하세요

  • 리소스 소유자: 아바타, 사진, 비디오 및 기타 리소스를 보유한 사용자

  • 클라이언트: 타사 애플리케이션

  • 인증 서버: 사용자가 제공한 정보가 올바른지 확인하고 타사 애플리케이션에 토큰을 반환하는 데 사용됩니다.

  • 리소스 서버: 아바타, 사진, 동영상 등 사용자 리소스를 제공하는 서버 and other resources

일반적으로 말하면 인증 서버와 리소스 서버는 동일한 서버일 수 있습니다.

OAuth3 인증 프로세스

1단계: 클라이언트(타사 애플리케이션)가 사용자에게 인증을 요청합니다.

사용자가 서비스 승인 페이지에서 승인 동의 버튼을 클릭하면 서버는 클라이언트에게 승인 인증서를 반환합니다.

3단계: 클라이언트는 토큰을 신청하기 위해 인증 라이센스를 인증 서버로 가져갑니다.

4단계: 인증 서버는 정보가 올바른지 확인한 후 클라이언트에 토큰을 발급합니다.

5단계: 클라이언트는 리소스에 액세스하기 위해 토큰을 리소스 서버로 가져갑니다.

6단계: 리소스 서버는 토큰이 올바른지 확인한 후 리소스를 엽니다.

인증 모드

OAuth 프로토콜의 인증 모드는 다음과 같이 4가지로 구분됩니다.

  • 인증 코드 인증 모드는 인증 방법 중 가장 완전하고 엄격하며, 인증 코드(인증 코드)는 다음과 같습니다. 열쇠. 이 모드의 특징은 클라이언트 서버가 인증 서버와 상호 작용한다는 것입니다. 국내 일반적인 타사 플랫폼 로그인 기능은 기본적으로 이 방법을 채택합니다

  • 간소 모드: 단순화 모드에서는 클라이언트 서버가 직접 참여할 필요가 없습니다. 브라우저 인증 서버에서 토큰을 신청합니다. 일반적으로 순수 정적 페이지인 경우 이 방법을 사용할 수 있습니다

  • 비밀번호 모드에서는 사용자가 자신의 사용자 이름과 비밀번호를 클라이언트에 직접 제공하고 클라이언트는 이를 사용합니다. 인증 서버에 요청하기 위한 정보입니다. 액세스 토큰을 요청합니다. 사용자는 클라이언트 애플리케이션과 서비스 제공자가 동일한 회사인지 여부 등 클라이언트에 대한 상위 수준의 정보를 알아야 합니다.

  • 클라이언트 모드에서는 특정 사용자가 아닌 서비스 제공자가 클라이언트를 인증합니다. 엄밀히 말하면 클라이언트 모드는 OAuth 프로토콜이 해결하는 문제에 대한 해결책이라고 볼 수 없습니다. 그러나 개발자의 경우 일부 프런트엔드 및 백엔드 분리 응용 프로그램이나 제공되는 인증 및 권한 부여 서버에서 이 방법을 사용하는 것이 유용합니다. 모바일 단말기의 경우 이 모드는 여전히 매우 편리합니다

4가지 모드는 각각 고유한 장점이 있으며 다양한 개발 시나리오에 적합합니다. 프론트 엔드와 백엔드 애플리케이션(또는 모바일의 경우 WeChat 애플릿에서 제공하는 인증 서버에서 OAuth 서비스를 구축하는 방법 등)이므로 비밀번호 모드를 주로 소개합니다.

1. 프로젝트 생성 및 종속성 추가

Spring Boot 웹 프로젝트 생성 및 다음 종속성 추가

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <exclusions>
    <exclusion>
      <groupId>io.lettuce</groupId>
      <artifactId>lettuce-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security.oauth</groupId>
  <artifactId>spring-security-oauth3</artifactId>
  <version>2.3.3.RELEASE</version>
</dependency>

Spring Boot의 OAuth 프로토콜은 Spring Security를 ​​기반으로 하므로 먼저 Spring Security 종속성을 추가해야 합니다. 2이므로 OAuth 2 관련 종속성을 추가합니다. 동시에 Redis에는 만료와 같은 기능이 있어 토큰 저장에 매우 적합하므로 Redis 종속성도 추가됩니다.

application.properties 구성

spring.redis.database=0
spring.redis.host=ip地址
spring.redis.port=6379
spring.redis.password=root
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0

2. 配置授权服务器

授权服务器和资源服务器可以是同一台服务器,也可以是不同服务器,此处假设是同一台服务器,通过不同的配置分别开启授权服务器和资源服务器,首先是授权服务器:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    @Autowired
    UserDetailsService userDetailsService;
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("password")
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(1800)
                .resourceIds("rid")
                .scopes("all")
                .secret("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }
}

代码解释:

  • 自定义类继承自 AuthorizationServerConfigurerAdapter ,完成对授权服务器的配置,然后通过 @EnableAuthorizationServer 注解开启授权服务器

  • 注入 AuthenticationManager 用来支持 password 模式

  • 注入 RedisConnectionFactory 用来完成 Redis 缓存,将令牌信息储存到 Redis 缓存中

  • 注入 UserDetailsService 该对象为刷新 token 提供支持

  • 在 configure(ClientDetailsServiceConfigurer clients) 方法中配置 password 授权模式,authorizedGrantTypes 表示 OAuth 2 中的授权模式为 password 和 refresh_token 两种,在标准的 OAuth 2 协议中,授权模式并不包括 refresh_token ,但是在 Spring Security 的实现中将其归为一种,因此如果要实现 access_token 的刷新,就需要添加这样一种授权模式;accessTokenValiditySeconds 方法配置了 access_token 的过期时间;resourceIds 配置了资源 id;secret 方法配置了加密后的密码,明文是 123

  • configure(AuthorizationServerEndpointsConfigurer endpoints) 方法配置了令牌的存储,AuthenticationManager 和 UserDetailsService 主要用于支持 password 模式以及令牌的刷新

  • configure(AuthorizationServerSecurityConfigurer security) 方法配置表示支持 client_id 和 client_secret 做登录认证

3. 配置资源服务器

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("rid").stateless(true);
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated();
    }
}

代码解释:

  • 自定义类继承自 ResourceServerConfigurerAdapter ,并添加 @EnableResourceServer 注解开启资源服务器配置

  • resources.resourceId(“rid”).stateless(true); 配置资源 id,这里的资源 id 和授权服务器中的资源 id 一直,然后设置这些资源仅基于令牌认证

  • configure(HttpSecurity http) 方法配置 HttpSecurity

4. 配置 Security

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return super.userDetailsService();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq")
                .roles("admin")
                .and()
                .withUser("sang")
                .password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq")
                .roles("user");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/oauth/**").authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .and().csrf().disable();
    }
}

这里两个 Bean 将注入授权服务器配置类中使用,另外,这里的 HttpSecurity 配置主要是配置 /oauth/** 模式的 URL ,这一类的请求直接放行。在 Spring Security 配置和资源服务器配置中,一共涉及两个 HttpSecurity ,其中 Spring Security 中的配置优先级高于资源服务器中的配置,即请求地址先经过 Spring Security 的 HttpSecurity ,再经过资源服务器的 HttpSecurity。

5. 验证测试

首先创建三个简单的请求地址

@RestController
public class HelloController {
    @GetMapping("/admin/hello")
    public String admin() {
        return "Hello admin!";
    }
    @GetMapping("/user/hello")
    public String user() {
        return "Hello user!";
    }
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

根据前文的配置,要请求这三个地址,分别需要 admin 角色、user 角色以及登录后访问。

所有都配置完成后,启动 Redis 服务器,再启动 Spring Boot 项目,首先发送一个 POST 请求获取 token,请求地址如下(注意这里是一个 POST 请求,为了显示方便,将参数写在地址栏中):http://localhost:8080/oauth/token?username=sang&password=123&grant_type=password&client_id=password&scope=all&client_secret=123

请求地址中包含的参数有用户名、密码、授权模式、客户端 id 、scope 以及客户端密码,基本就是授权服务器中所配置的数据,请求结果如图

SpringBoot 보안 관리의 OAuth2 프레임워크를 사용하는 방법

其中 access_token 是获取其它资源时要用的令牌,refresh_token 用来刷新令牌,expires_in 表示 access_token 过期时间,当 access_token 过期后,使用 refresh_token 重新获取新的 access_token (前提是 refresh_token 未过期),请求地址(注意也是POST请求):http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=693b0e36-4515-442a-8c5d-90bade3c74d2&client_id=password&client_secret=123

获取新的 access_token 时需要携带上 refresh_token ,同事授权模式设置为 refresh_token ,在获取的结果中 access_token 会变化,同时 access_token 有效期也会变化,如图

SpringBoot 보안 관리의 OAuth2 프레임워크를 사용하는 방법

接下来访问所有资源,携带上 access_token 参数即可,例如 /user/hello 接口:http://localhost:8080/user/hello?access_token=0497e4bc-df37-460e-8755-b813b9dbf36a,访问结果如图

SpringBoot 보안 관리의 OAuth2 프레임워크를 사용하는 방법

sang 사용자가 /admin/hello 인터페이스에 접속하는 등 불법적으로 리소스에 접속하면 결과는 그림과 같습니다.

SpringBoot 보안 관리의 OAuth2 프레임워크를 사용하는 방법

이때 비밀번호 모드 OAuth 인증 시스템은 성공적으로 설립되었습니다.

OAuth에는 4가지 인증 모드가 있습니다. 개발자는 실제 개발 상황에 따라 그 중 하나를 선택해야 합니다. 프런트엔드 및 백엔드 분리 애플리케이션에서 일반적으로 사용되는 비밀번호 모드도 여기에 소개되어 있습니다. 사용할 장면이 있습니다.

일반적으로 Spring Security OAuth 2의 사용은 여전히 ​​상대적으로 복잡하고 구성도 상대적으로 번거롭습니다. 개발자의 애플리케이션 시나리오가 상대적으로 간단하다면 여기에 소개된 인증 프로세스에 따라 자체 OAuth 2 인증 시스템을 구축할 수 있습니다. .

위 내용은 SpringBoot 보안 관리의 OAuth2 프레임워크를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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