基於Spring Cloud 幾行配置完成單點登入開發

冷冷gg發表於2018-01-29

單點登入概念

單點登入(Single Sign On),簡稱為 SSO,是目前比較流行的企業業務整合的解決方案之一。SSO的定義是在多個應用系統中,使用者只需要登入一次就可以訪問所有相互信任的應用系統。登入邏輯如上圖

基於Spring 全家桶的實現

技術選型:

Spring Boot
Spring Cloud 
Spring Security oAuth2
複製程式碼

客戶端:

maven依賴

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
</dependency>
複製程式碼

EnableOAuth2Sso 註解

入口類配置@@EnableOAuth2Sso


@SpringBootApplication
public class PigSsoClientDemoApplication {

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

}
複製程式碼

配置檔案

security:
  oauth2:
    client:
      client-id: pig
      client-secret: pig
      user-authorization-uri: http://localhost:3000/oauth/authorize
      access-token-uri: http://localhost:3000/oauth/token
      scope: server
    resource:
      jwt:
        key-uri: http://localhost:3000/oauth/token_key
  sessions: never
複製程式碼

SSO認證伺服器

認證伺服器配置

@Configuration
@Order(Integer.MIN_VALUE)
@EnableAuthorizationServer
public class PigAuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(authServerConfig.getClientId())
                .secret(authServerConfig.getClientSecret())
                .authorizedGrantTypes(SecurityConstants.REFRESH_TOKEN, SecurityConstants.PASSWORD,SecurityConstants.AUTHORIZATION_CODE)
                .scopes(authServerConfig.getScope());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .tokenStore(new RedisTokenStore(redisConnectionFactory))
                .accessTokenConverter(jwtAccessTokenConverter())
                .authenticationManager(authenticationManager)
                .exceptionTranslator(pigWebResponseExceptionTranslator)
                .reuseRefreshTokens(false)
                .userDetailsService(userDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .allowFormAuthenticationForClients()
                .tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(CommonConstant.SIGN_KEY);
        return jwtAccessTokenConverter;
    }

}
複製程式碼

配置完成體驗

  1. 訪問SSO客戶端的 index.html
  2. 重定向到SSO服務端的 Basic 認證
  3. 輸入賬號密碼又重定向到原請求的 客戶端index資源

總結

  • 客戶端訪問服務端 403問題? 使用者需要擁有ROLE_USER的許可權,具體的可以通過日誌可以檢視到報錯。
  • Possible CSRF detected - state parameter was present but no state could be found 目前是通過設定session: never或者 cotext-path解決
  • 原始碼請參考 gitee.com/log4j/ 基於Spring Cloud、Spring Security Oauth2.0開發企業級認證與授權,提供常見服務監控、鏈路追蹤、日誌分析、快取管理、任務排程等實現

相關文章