フレームワークSpringBoot+Spring Security Oauth 2+PostManを使用

33579 ワード

フレームワークSpringBoot+Spring Security Oauth 2を使用して、主にmysqlデータベースを通じて現在のクライアントテーブル情報を読み取ることができるクライアント認証を完了しました.tokenはデータベースに格納されます.
1.導入依存
oauth 2はspring securityに依存し,spring,mysql,redis,mybatisを導入する必要がある
<dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.security.oauthgroupId>
            <artifactId>spring-security-oauth2artifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.0version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
    dependencies>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2.プロファイル
server:
  port: 8081

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/oauth2?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  redis:
    host: 127.0.0.1
    database: 0

mybatis:
  mapper-locations: mapper/*.xml

security:
  oauth2:
    resource:
      filter-order: 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
3.構成
oauth 2プロトコルに関する内容およびライセンスプロセスについては、別のブログを参照してください.
主に3つのクラスを使用して構成されます
  • AuthorizationServerConfigurationライセンス認証構成AuthorizationServerConfigurerAdapterを継承し、ライセンスに関する情報を構成し、構成のコアはここでクライアントを構成し、tokenストレージ方式などを構成する
  • package oauth.security.client.configauto;
    
    
    import org.apache.tomcat.jdbc.pool.DataSource;
    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.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.TokenStore;
    import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
    import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
    import oauth.security.client.configauto.jdbcdetail.MyJdbcTokenStore;
    
    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    
        private static final String DEMO_RESOURCE_ID = "*";
    
        @Autowired
        AuthenticationManager authenticationManager;
    
        @Autowired
        RedisConnectionFactory redisConnectionFactory;
    
        @Autowired
        private DataSource dataSource;
    
        //    JdbcTokenStore
        @Autowired
        public TokenStore getTokenStore() {
            return new JdbcTokenStore(dataSource);
        }
    
        //         tokenStore
        @Autowired
        public TokenStore getMyTokenStore() {
            return new MyJdbcTokenStore(dataSource);
        }
    
        @Autowired
        private TokenStore getRedisTokenStore() {
            return new RedisTokenStore(redisConnectionFactory);
        }
    
        @Bean   //   ApplyClientDetailService
        public ApplyClientDetailService getClientDetails() {
            return new ApplyClientDetailService();
        }
    
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            //      ,   client  
            clients.withClientDetails(getClientDetails());
    /*          //         
                clients.inMemory().withClient("client_1")
                    .resourceIds(DEMO_RESOURCE_ID)
                    .authorizedGrantTypes("client_credentials", "refresh_token")
                    .scopes("all")
                    .authorities("client")
                    .secret("123456");*/
        }
    
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
             .authenticationManager(authenticationManager);   // redis  token
    /*        endpoints.tokenStore(getTokenStore())   //      token
                    .authenticationManager(authenticationManager);*/
        }
    
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            //      
            oauthServer.allowFormAuthenticationForClients();
        }
    
    }
    

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    クライアントの構成では、ApplyClientDetailServiceクラスを使用しています.Clientを取得するカスタムクラスです.ClientDetailsServiceを継承します.
    Clientへのアクセスは主にJdbcClientDetailsServiceクラスの実装に依存し、公式に与えられたデータベース構造を使用する必要があります.データベース構造をカスタマイズするには、JdbcClientDetailsServiceクラスの実装を必要に応じて書き換えることができます.
    package oauth.security.client.configauto;
    
    import org.apache.tomcat.jdbc.pool.DataSource;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.oauth2.provider.ClientDetails;
    import org.springframework.security.oauth2.provider.ClientDetailsService;
    import org.springframework.security.oauth2.provider.ClientRegistrationException;
    import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
    import oauth.security.client.service.ApplyService;
    
    public class ApplyClientDetailService implements ClientDetailsService {
    
        @Autowired
        private ApplyService applyService;
    
        @Autowired
        private DataSource dataSource;
    
        @Override
        public ClientDetails loadClientByClientId(String applyName) throws ClientRegistrationException {
    
            /*
            //   mybatic  client     ,     sql
            Map clientMap = applyService.findApplyById(applyName);
    
            if(clientMap == null) {
                throw new ClientRegistrationException("  " + applyName + "   !");
            }*/
    
    //        MyJdbcClientDetailsService jdbcClientDetailsService= new MyJdbcClientDetailsService(dataSource, "authentication");
            JdbcClientDetailsService jdbcClientDetailsService= new JdbcClientDetailsService(dataSource);
            ClientDetails clientDetails = jdbcClientDetailsService.loadClientByClientId(applyName);
    
            return clientDetails;
        }
    }
    

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
  • ResourceServerConfigurationリソース構成リソース権限
  • 
    
      package oauth.security.client.configauto;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.http.SessionCreationPolicy;
    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 ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    
        private static final String DEMO_RESOURCE_ID = "*";
    
        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
             resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
             http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .and().requestMatchers().anyRequest()
                    .and().anonymous()
                    .and().authorizeRequests()
    //                    .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')")
                    .antMatchers("/**").authenticated();  //        ,           
        }
    }
    

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
  • SecurityConfigurationセキュリティ構成
  • package oauth.security.client.configauto;
    
    
    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.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.oauth2.provider.ClientDetailsService;
    import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
    import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
    import org.springframework.security.oauth2.provider.token.TokenStore;
    import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
    import org.springframework.security.provisioning.InMemoryUserDetailsManager;
    
    /**
     * Created by fcz on 2017/12/28.
     */
    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private ClientDetailsService clientDetailsService;
    
        @Autowired
        private RedisConnectionFactory redisConnection;
    
        @Bean   //   ApplyClientDetailService
        public ApplyClientDetailService getClientDetails() {
            return new ApplyClientDetailService();
        }
    
        @Bean
        @Override
        protected UserDetailsService userDetailsService(){
            InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
            manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());
            manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());
            return manager;
        }
    
        @Bean
        public TokenStore tokenStore() {
            return new RedisTokenStore(redisConnection);
        }
    
        @Bean
        @Autowired
        public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
            TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
            handler.setTokenStore(tokenStore());
            handler.setRequestFactory(new DefaultOAuth2RequestFactory(getClientDetails()));
            handler.setClientDetailsService(getClientDetails());
            return handler;
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .requestMatchers().anyRequest()
                .and().authorizeRequests().antMatchers("/oauth/*").permitAll();
        }
    }
    

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    インタフェースアクセス
    postManを使用してクライアント要求tokenにアクセスし、POST:http://localhost:8081/oauth/token?grant_type=client_credentials&scope=all&client_id=apply&client_secret=123456
    ユーザ要求token,POST:http://localhost:8081/oauth/token?grant_type=password&username=user_1&password=123456&scope=all&client_id=apply&client_secret=123456
    詳細コードはgithup:SpringSecurityOauth 2