springboot集成Spring Security oauth2(八)

因爲公司項目須要,進行SpringBoot集成Spring Security oauth2,幾乎搜尋網上全部大神的案例,苦苦不能理解,不能徹底OK。web

如下是借鑑各大神的代碼,終於demo完工,請欣賞spring

 

oauth2 定義了下面四種受權方式:數據庫

  • 受權碼模式(authorization code)
  • 簡化模式(implicit)
  • 密碼模式(resource owner password credentials)
  • 客戶端模式(client credentials)

具體每一個模式的業務邏輯,請找百度君api

如下是參數:服務器

* response_type:表示受權類型,必選項,此處的值固定爲"code"

* client_id:表示客戶端的ID,必選項

* redirect_uri:表示重定向URI,可選項

* scope:表示申請的權限範圍,可選項

* state:表示客戶端的當前狀態,能夠指定任意值,認證服務器會原封不動地返回這個值。

先貼出項目結構:app

直接貼代碼:ide

SpringBoot項目入口,服務啓動spring-boot

package com.mingtong.demo_client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoClientApplication.class, args);
    }
}

控制器Controller,獲取資源,後面能夠改造JDBC獲取數據庫,或者遠程調用ui

@RestController
@RequestMapping("/api")
public class DemoController {
    @RequestMapping("/blog/{id}")
    public String getBlogById(@PathVariable long id) {
        return "this is blog "+id;
    }
}

Oauth2認證服務this

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .realm("oauth2-resources") //code受權添加
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()") //allow check token
                .allowFormAuthenticationForClients();
    }
       
    /**
     * 注入authenticationManager
     * 來支持 password grant type
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
        //容許 GET、POST 請求獲取 token,即訪問端點:oauth/token
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("demoApp")
                .secret("demoAppSecret")
                .redirectUris("http://baidu.com")//code受權添加
                .authorizedGrantTypes("authorization_code","client_credentials", "password", "refresh_token")
                .scopes("all")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000);
    }

}

資源服務器:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
         http.requestMatchers().antMatchers("/api/**")
             .and()      
             .authorizeRequests()
             .antMatchers("/api/**").authenticated();
    }
    }

SpringSecurity配置

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
            http.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**")
                    .and()
                    .authorizeRequests()
                    .antMatchers("/oauth/**").authenticated()
                    .and()
                    .formLogin().permitAll();
        }

        //配置內存模式的用戶
        @Bean
        @Override
        protected UserDetailsService userDetailsService(){
            InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
            manager.createUser(User.withUsername("demoUser1").password("123456").authorities("USER").build());
            manager.createUser(User.withUsername("demoUser2").password("123456").authorities("USER").build());
            return manager;
        }

        /**
         * 須要配置這個支持password模式
         */
        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
}

POM文件

        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
        </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>
【密碼受權模式-client】
密碼模式須要參數:username,password,grant_type,client_id,client_secret
http://localhost:8080/oauth/token?username=demoUser1&password=123456&grant_type=password&client_id=demoApp&client_secret=demoAppSecret

【客戶端受權模式-password】
客戶端模式須要參數:grant_type,client_id,client_secret
http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=demoApp&client_secret=demoAppSecret

【受權碼模式-code】
獲取code
http://localhost:8080/oauth/authorize?response_type=code&client_id=demoApp&redirect_uri=http://baidu.com
經過code換token http://localhost:8080/oauth/token?grant_type=authorization_code&code=Filepd&client_id=demoApp&client_secret=demoAppSecret&redirect_uri=http://baidu.com

祝君好運!

相關文章
相關標籤/搜索