SpringBoot 快速嘗試 OAuth2 密碼和授權碼模式

微服務火熱,前後端分離,oauth2 是我們接口調用認證的首選。springboot 天然集成 oauth2,使用非常方便,簡單記錄下,嚐嚐鮮。

一、新建boot項目

idea 新建 springboot項目,maven 引入pom依賴,推薦使用spring-cloud-starter-oauth2和spring-cloud-starter-security。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>

項目結構目錄如下,

二、oauth2核心config配置

這一步是成功的關鍵,主要三個config:認證服務配置、資源服務配置和web安全配置。

1、AuthServerConfig,繼承 AuthorizationServerConfigurerAdapter

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("appid")
                .secret("{noop}secret")
                .authorizedGrantTypes("password", "authorization_code", "client_credentials", "implicit", "refresh_token")
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }

}

2、ResourceServerConfig,繼承 ResourceServerConfigurerAdapter (這裏簡單起見,我們都做默認實現)

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

}

3、WebSecurityConfig,繼承 WebSecurityConfigurerAdapter 

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 必須注入 AuthenticationManager,不然oauth無法處理四種授權方式
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    /**
     * 注入UserDetailsService
     * @return
     */
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        userDetailsManager.createUser(User.withUsername("zhangsan").password("{noop}123").authorities("USER").build());
        return userDetailsManager;
    }

三、測試類編寫

一切從簡,前面三個配置類寫好後,我們寫個簡單的測試controller。

@RestController
public class HelloController {

    @GetMapping("/sayHi")
    public String sayHi() {
        return "你好,哈哈哈";
    }

}

另,application-dev.yml 裏沒做其他配置,就是指定一個端口號。

server:
  port: 7000

四、postman測試

上面都做完了 我們就開始測試啦。

1、直接請求controller地址,返回沒有授權

2、獲取token

請求地址:http://appid:secret@localhost:7000/oauth/token?grant_type=password&username=zhangsan&password=123&scop=all

3、帶token參數訪問接口地址,訪問成功。

這樣的話,一個簡單的oauth2授權碼模式就ok了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章