springboot 통합 author2

author2에는 몇 가지 기본 역할이 있습니다.

리소스 소유자 : 사용자
클라이언트 : 그러나 타사 응용 프로그램
권한 부여 서버 : 사용자가 제공 한 정보가 올바른지 확인하고 토큰을 반환하는 데 사용됩니다
. 리소스 서버 : 사용자에게 리소스를 제공하는 서버

인증 모드 :

인증 코드 모드 : 가장 완벽한 기능과 가장 엄격한 프로세스. 클라이언트 서버는 권한 서버와 상호 작용합니다. 이 기능을 사용하면 중국에서 일반적인 타사 플랫폼 로그인이 실현됩니다.
단순 모드 : 클라이언트 서버의 참여없이 브라우저의 인증 서버에서 직접 토큰을 신청합니다. 일반적으로 웹 사이트는 순수한 정적 페이지이며이 방법을 사용할 수 있습니다.
암호 모드 : 클라이언트에게 사용자 이름과 암호를 직접 알리고 클라이언트는이 정보를 사용하여 권한 부여 서버에서 토큰을 신청합니다.
클라이언트 모드 : 클라이언트는 사용자 이름 대신 자체 이름을 사용하여 서버에서 인증을 신청합니다.

다음으로 springboot 통합 author2, github : https://github.com/fengqing11/springboot-oauth2를 시작
하여 다음 종속성을 가진 프로젝트 생성
합니다. springboot의 oauth 프로토콜은 실제로 스프링 보안을 기반으로 완료되었으므로 스프링 보안 종속성을 추가해야합니다.

  • 토큰은 redis 캐시 서버에 저장 됨과 동시에 redis는 만료 기능이있어 토큰 저장에 매우 적합하므로 redis의 종속성도 추가됩니다. 

<? xml version = "1.0"encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"xmlns : xsi = "http : //www.w3 .org / 2001 / XMLSchema-instance "
         xsi : schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">
    <modelVersion> 4.0.0 </ modelVersion>

    <groupId> org.sang </ groupId>
    <artifactId> oauth2 </ artifactId>
    <version> 0.0.1-SNAPSHOT </ version>
    <packaging> jar </ packaging>

    <name> oauth2 </ name>
    <description> Spring Boot 용 데모 프로젝트 </ description>

    <parent>
        <groupId> org.springframework.boot </ groupId>
        <artifactId> spring-boot-starter-parent </ artifactId>
        <version> 2.0.3.RELEASE </ version>
        <relativePath /> <!-lookup 저장소의 상위->
    </ parent>

    <properties>
        <project.build.sourceEncoding> UTF-8 </project.build.sourceEncoding>
        <project.reporting.outputEncoding> UTF-8 </project.reporting.outputEncoding>
        <java.version> 1.8 </java.version >
    </ properties>

    <dependency>
        <dependency>
            <groupId> org.springframework.boot </ groupId>
            <artifactId> spring-boot-starter-security </ artifactId>
        </ dependency>
        <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>
        </ dependency>
        <dependency>
            <groupId> org.springframework.security.oauth </ groupId>
            <artifactId> spring-security-oauth2 </ artifactId>
            <version> 2.3.3.RELEASE </ version>
        </ dependency>
    </ dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId> org.springframework.boot < / groupId>
                <artifactId> spring-boot-maven-plugin </ artifactId>
            </ plugin>
        </ plugins>
    </ build>


</ 프로젝트>
 

 구성 파일 :

spring.redis.database = 0
spring.redis.host = localhost
spring.redis.port = 6379
spring.redis.password =
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
 

권한 서버 구성 :
권한 서버와 자원 서버는 동일한 서버이거나 다른 서버 일 수 있으며 여기에서는 동일한 서버가 사용됩니다.
다른 구성을 통해 권한 서버와 자원 서버를 분리하십시오.
AuthorizationServerConfigurerAdapter를 상속하여 권한 부여 서버의 구성을 완료 한 다음 @EnableAuthorizationServer 주석을 통해 권한 부여 서버를 활성화합니다.
AuthenticationManager 개체는 암호 인증 모드를 지원하는 데 사용됩니다.
RedisConnectionFactory 객체는 redis 캐싱을 완료하는 데 사용됩니다.
UserDetailsService 개체는 토큰 새로 고침을 지원합니다.
authorizedGrantTypes () 메소드는 인증 모드를 password와 refresh_token으로 설정한다. 실제로 표준 oauth에는 refresh_token이 없지만 스프링 보안에서는 하나로 분류되므로 access_token의 새로 고침을 실현하기 위해서는 refresh_token이 필요하다.
accessTokenValiditySeconds () 메서드는 토큰의 만료 시간을 설정합니다.
resourceIds () 메서드는 리소스 ID를 구성합니다.
secret () 메서드는 암호화 된 암호를 구성하며 일반 텍스트는 123입니다.

패키지 org.sang.oauth2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableAuthorizationServer
공개 클래스 AuthorizationServerConfig는
        AuthorizationServerConfigurerAdapter {     @Autowired     AuthenticationManager authenticationManager를 확장 합니다.     @Autowired     RedisConnectionFactory redisConnectionFactory;     @Autowired     UserDetailsService userDetailsService;     @Bean     PasswordEncoder passwordEncoder () {         새로운 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 $ RMuFXGQ5AtH4wOvkUqsyvuecpWqYiqz50dceRga.WqYeoxZYqilXzbz");
    }
    @Override
    public void configure (AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {         endpoints.tokenStore (new RedisTokenStore (redisConnectionFactory))                 .authenticationManager (authenticationManager)                 .userDetailsService (userDetailsService);






            예외 발생 {         security.allowFormAuthenticationForClients ();     } }



 

 리소스 서버 구성 :
ResourceServerConfigurerAdapter를 상속하고 @EnableResourceServer 주석을 사용하여 리소스 서버 구성을 활성화합니다.
resourceId ()를 사용하여 리소스 ID를 구성합니다. 여기서 ID는 권한 부여 서버의 리소스 ID와 동일해야합니다.
stateless () 메서드는 토큰 확인을 기반으로 만 이러한 리소스를 설정합니다.

패키지 org.sang.oauth2;

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 {     @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 ( "사용자")                 .anyRequest (). authenticated ();     } }













 

구성 보안 :
이전 것과 차이가 없습니다. 유일한 차이점은 @bean 주석이 두 개 더 있다는 것입니다.이 두 Bean은 사용을 위해 권한 부여 서버에 주입됩니다.
여기서 HttpSecurity 구성은 주로 / oauth / **의 URL을 구성하며 이러한 유형의 요청은 직접 해제됩니다. 리소스 서버 구성에도 HttpSecurity가 있으며, 여기서 HttpSecurity는 리소스 서버의 HttpSecurity보다 우선합니다.

패키지 org.sang.oauth2;

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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

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





 

서버 시작 후 POST 액세스 : http://127.0.0.1:8080/oauth/token?username=sang&password=123&grant_type=password&client_id=password&scope=all&client_secret=123
매개 변수가 URL에 기록되어 편리하지만 게시 요청이기도합니다.

여기에 사진 설명 삽입
요청 매개 변수 :

사용자 이름 : 사용자 이름
암호 : 마스크
grant_type : 권한 부여 모드
client_id : 자원 서버 ID
범위 : 자원 서버 범위
client_secret : 자원 서버 암호

반환 내용 :

access_token :은 토큰입니다.
token_type :
refresh_token : 토큰을 새로 고치는 데 사용할 수 있습니다. 토큰이 만료되지 않은 경우 토큰을 새로 고치는 데 사용할 수 있습니다
. expires_in : 토큰의 만료 시간, 구현이 1800이 아닌 것을 확인하기 위해 다시 새로 고치면
범위가 줄어 듭니다 .

토큰 액세스 새로 고침 : http://127.0.0.1:8080/oauth/token?grant_type=refresh_token&refresh_token=6bef362e-a96c-48af-a310-b9623d7c69a4&client_id=password&client_secret=123

여기에 사진 설명 삽입

리소스에 액세스하려면 http : // localhost : 8080 / user / hello? access_token = cf4d8b09-3fe1-4671-91f3-4703d6e75c91을 방문하십시오.


여기에 사진 설명 삽입

이 시점에서 암호 모드 oauth 인증 시스템이 구축되었습니다.
-종료-
 

추천

출처blog.csdn.net/xulong5000/article/details/107155321