中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

springcloud~微(wei)服務里的oauth2集成(cheng)總結

版本聲明

Springboot,springcloud,spring secutity,spring ouath2都需要有(you)明確的(de)(de)(de)版本(ben)聲明,對于不同版本(ben)的(de)(de)(de)類庫,實現上也有(you)很(hen)大的(de)(de)(de)區別,不同版本(ben)的(de)(de)(de)授(shou)權是不能通用的(de)(de)(de)。

項目定義

  1. 網關服務 gateway
  2. 授權服務 oauth,uaa
  3. 用戶服務 system-service
  4. 其它微服務 others-service

授權流轉方式

  1. 用戶調用gateway的登陸接口
  2. gateway里進行參數組織,調用oauth的頒發token接口
  3. 用戶拿到token之后,帶著token去訪問資源服務的接口

版本定義

springboot+springcloud

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/>
</parent>
<properties>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    <spring-cloud-alibaba.version>2.0.2.RELEASE</spring-cloud-alibaba.version>
    <spring-cloud-starter-oauth2.version>2.0.0.RELEASE</spring-cloud-starter-oauth2.version>
    <spring-security-oauth2.version>2.3.3.RELEASE</spring-security-oauth2.version>
    <spring-boot-starter-security.version>2.0.0.RELEASE</spring-boot-starter-security.version>
</properties>
<dependencyManagement>
        <dependencies>
            <!--spring cloud 版本-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

gateway,oauth,system等服務添加引(yin)用

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>${spring-boot-starter-security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>${spring-security-oauth2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
            <version>${spring-cloud-starter-oauth2.version}</version>
        </dependency>

gateway添加bean

@EnableWebFluxSecurity
public class GatewaySecurityConfig {
    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity serverHttpSecurity)
            throws Exception {
        serverHttpSecurity
                .csrf().disable();
        serverHttpSecurity.cors();
        return serverHttpSecurity.build();
    }
}

ouath添加bean

AuthorizationServerConfig繼承AuthorizationServerConfigurerAdapter 用來配置客(ke)戶端(duan)詳(xiang)(xiang)情(qing)服(fu)務(ClientDetailsService),客(ke)戶端(duan)詳(xiang)(xiang)情(qing)信息(xi)在這里進行初始化(hua),你(ni)能夠(gou)把客(ke)戶端(duan)詳(xiang)(xiang)情(qing)信息(xi)寫死在這里或者(zhe)是通過數(shu)據庫來存儲(chu)調取詳(xiang)(xiang)情(qing)信息(xi)。

ResourceServerConfig它上面添加注解@EnableResourceServer幫我們加入了
org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter,該filter幫我們(men)從(cong)request里(li)(li)解析(xi)出access_token并通(tong)過(guo)org.springframework.security.oauth2.provider.token.DefaultTokenServices根據access_token和(he)認證服務(wu)器配置里(li)(li)的TokenStore從(cong)redis或者jwt里(li)(li)解析(xi)出用戶(hu)注(zhu)意認證中心的@EnableResourceServer和(he)別(bie)的微服務(wu)里(li)(li)的@EnableResourceServer有些(xie)不同別(bie)的微服務(wu)是(shi)通(tong)過(guo)org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices來(lai)獲取用戶(hu)的.

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new OAuth2RequestedMatcher()).authorizeRequests()
                .antMatchers(PermitAllUrl.permitAllUrl()).permitAll() // 放開權限的url
                .anyRequest().authenticated();
    }

    /**
     * 判斷來源請求是否包含oauth2授權信息<br>
     * url參數中含有access_token,或者header里有Authorization
     */
    private static class OAuth2RequestedMatcher implements RequestMatcher {
        @Override
        public boolean matches(HttpServletRequest request) {
            // 請求參數中包含access_token參數
            if (request.getParameter(OAuth2AccessToken.ACCESS_TOKEN) != null) {
                return true;
            }

            // 頭部的Authorization值以Bearer開頭
            String auth = request.getHeader("Authorization");
            if (auth != null) {
                return auth.startsWith(OAuth2AccessToken.BEARER_TYPE);
            }

            return false;
        }
    }

}

SecurityConfig,這個bean主要設置用戶獲取接口和加密(mi)規則(ze)

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

    @Autowired
    public UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Value("${pkulaw.token.redis}")
    private Boolean tokenRedis;

    @Value("${pkulaw.tokenExpireTime}")
    private Integer tokenExpireTime;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }


    /**
     * 認證管理
     *
     * @return 認證管理對象
     * @throws Exception 認證異常信息
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    /**
     * http安全配置
     *
     * @param http http安全對象
     * @throws Exception http安全異常信息
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(PermitAllUrl.permitAllUrl()).permitAll() // 放開權限的url
                .anyRequest().authenticated().and()
                .httpBasic().and().csrf().disable();
    }

UserDetailServiceImpl用(yong)來獲(huo)取用(yong)戶信息(xi),通過通過feign獲(huo)取system里的接口

@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private UserClient userClient;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String flagKey = "loginFailFlag:" + username;
        String value = redisTemplate.opsForValue().get(flagKey);
        Long timeRest = redisTemplate.getExpire(flagKey, TimeUnit.MINUTES);
        if (StrUtil.isNotBlank(value)) {
            //超過限制次數
            System.out.println("登錄錯誤次數超過限制,請" + timeRest + "分鐘后再試");
            throw new PkuLawException("登錄錯誤次數超過限制,請" + timeRest + "分鐘后再試");
        }
        User user = userClient.findByUsername(username);
        //持久化到redis
        redisUtil.set(RedisConstant.USER + username, user);
        return new SecurityUserDetails(user);
    }
}

system添加bean

system也是資源(yuan)(yuan)服務(wu)(wu)的(de)一(yi)種(zhong),主要(yao)提(ti)供用戶(hu)服務(wu)(wu),每(mei)個資源(yuan)(yuan)服務(wu)(wu)都有一(yi)個ResourceServerConfig的(de)bean,用來規定你(ni)的(de)資源(yuan)(yuan)開放(fang)策略。

/**
 * 資源服務配置
 */
@EnableResourceServer
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        super.configure(resources);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().exceptionHandling()
                .authenticationEntryPoint(
                        (request, response, authException) -> response.sendError(
                            HttpServletResponse.SC_UNAUTHORIZED))
                .and().authorizeRequests()
                .antMatchers(PermitAllUrl
                    .permitAllUrl("/company/register","/druid/**","/file/view/**","/**/users-anon/**")).permitAll() // 放開權限的url
                .anyRequest().authenticated()
                .and().httpBasic()
                .and().addFilterBefore(new BeforeTokenFilter(), AbstractPreAuthenticatedProcessingFilter.class)
        ;
        http.headers().frameOptions().sameOrigin();
    }



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

資源服務的配置

通過在yml里(li)對oauth2的配置,來獲取當(dang)前oauth里(li)的登錄信息,并把登陸狀態寫到自己服務(wu)的HTTP請求里(li),這個(ge)過程是oauth框架幫我(wo)們(men)實現的。

security:
  oauth2:
    resource:
      user-info-uri: //localhost:6660/pkulaw/oauth/user-me #授權服務的獲取當前用戶接口,它的返回值是Authentication類型,它會把返回值寫到當前服務的請求頭里
      prefer-token-info: false

這篇文(wen)章主要記錄了oauth2搭(da)建(jian)的過(guo)程。

posted @ 2020-07-29 16:41  張占嶺  閱讀(3456)  評論(4)    收藏  舉報