1. 程式人生 > 程式設計 >【最簡OAuth 2.0 教程】開發認證中心及資源伺服器接入

【最簡OAuth 2.0 教程】開發認證中心及資源伺服器接入

背景: 網上很多講配置 oauth2 ,配置方法 複雜紛繁對於初學者很不友好,讓人望而卻步

歡迎關注本系列部落格 基於 spring cloud 最新版本 hoxton 完成oauth2 的實踐

  • 基於 Spring Cloud OAuth ,用簡潔的方式搭建oauth的認證中心,
  • 關於oauth2 的授權模式 請直接參考 [阮一峰 OAuth 2.0 的四種方式的詳細介紹
    ](http://www.ruanyifeng.com/blog/2019/04/oauth-grant-types.html)
  • 專案版本核心說明
名稱 版本
Spring Boot 2.2.0.M5
Spring Cloud Hoxton.M2
Spring Cloud OAuth2 2.2.0.M2

開始配置認證伺服器

maven 依賴引入

  • 這裡只需要引入web、 cloud-oauth 即可,暫不引入spring cloud 其他元件
<dependencies>
    <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>
</dependencies>複製程式碼

配置web安全,攔截全部的請求

  • 獲取web 上下文AuthenticationManager 注入到spring中,方便後邊oauth server注入
  • 建立UserDetailsService的記憶體實現,注入一個測試使用者
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    /**
     * 必須注入 AuthenticationManager,不然oauth  無法處理四種授權方式
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 必須注入UserDetailsService ,不然oauth  密碼模式等死迴圈問題
     *
     * @return
     */
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        userDetailsManager.createUser(User.withUsername("lengleng").password("{noop}lengleng").authorities("USER").build());
        return userDetailsManager;
    }
}複製程式碼

配置oauth2 認證伺服器

  • 配置clientId 資訊,及其支援的授權模式,特別注意這裡是五種包含一個重新整理操作
@Configuration
@EnableAuthorizationServer
public class BigAuthServerConfiguration 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);
    }

}複製程式碼

以上完成了認證伺服器的功能

測試密碼模式

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=password&username=lengleng&password=lengleng&scope=all' "http://appid:secret@localhost:8764/oauth/token"複製程式碼

開始配置資源伺服器

maven 依賴引入

  • 這裡只需要引入web、 cloud-oauth 即可,暫不引入spring cloud 其他元件
<dependencies>
    <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>
</dependencies>複製程式碼

配置客戶端資訊

security:
  oauth2:
    client:
      client-id: appid
      client-secret: secret
      scope: all
    resource: # 認證中心的check_token 介面地址
      token-info-uri: http://127.0.0.1:8764/oauth/check_token複製程式碼

應用宣告資源伺服器

  • @EnableResourceServer 即可完成接入
// 接入oauth2 ,宣告為資源伺服器
@EnableResourceServer  
@EnableDiscoveryClient
@SpringBootApplication
public class BigUpmsServerApplication {

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

}複製程式碼

上文配置的認證伺服器暴露check_token

  • 若不處理介面check_token 403
public class BigAuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
    /**
     * checkTokenAccess 許可權設定為isAuthenticated,不然資源伺服器 來請求403
     * @param oauthServer
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()");
    }
}複製程式碼

資源伺服器demo 介面

@RestController
public class DemoController {

    @GetMapping("/info")
    public Authentication authentication(Authentication authentication) {
        return authentication;
    }
}
複製程式碼

通過上文獲取的token 訪問測試介面

  • 獲取token

  • 通過token 請求測試介面獲取當前使用者資訊

總結