Spring Cloud微服務安全實戰_4-5_搭建OAuth2資源服務器


上一篇搭建了一個OAuth2認證服務器,可以生成token,這篇來改造下之前的訂單微服務,使其能夠認這個token令牌。

本篇針對訂單服務要做三件事:

1,要讓他知道自己是資源服務器,他知道這件事后,才會在前邊加一個過濾器去驗令牌(配置@EnableResourceServer 配置類

2,要讓他知道自己是什么資源服務器(配置資源服務器ID)

 

3,配置去哪里驗令牌,怎么驗令牌,要帶什么信息去驗 (配置@EnableWebSecurity 配置TokenServices,配置AuthenticationManager

 

搭建資源服務器

 

 

++++++++++++++++++資源服務器現有的各個類++++++++++++++++++++++++++++

 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.nb.security</groupId>
    <artifactId>nb-order-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.1.6.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>

    </dependencyManagement>

    <dependencies>

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

        <!--OAuth2-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <!--指定JDK編譯版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- 打包跳過測試 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>


            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

application.yml:

server:
  port: 9060
View Code

OrderInfo.java :

package com.nb.security.order;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class OrderInfo {

    private Long productId;

}
View Code

OrderController:

package com.nb.security.order;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@Slf4j
@RestController
@RequestMapping("/orders")
public class OrderController {

    private RestTemplate restTemplate = new RestTemplate();



    @PostMapping
    public OrderInfo create(@RequestBody OrderInfo info){
        //查詢價格
//        PriceInfo price = restTemplate.getForObject("http://localhost:9080/prices/"+info.getProductId(),PriceInfo.class);
//        log.info("price is "+price.getPrice());
        return info;
    }


    @GetMapping
    public OrderInfo getInfo(@PathVariable Long id){
        log.info("getInfo: id is "+id);
        return new OrderInfo(id);
    }

}
View Code

啟動類:

package com.nb.security;

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

@SpringBootApplication
public class NbOrderApiApplication {

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

}
View Code

PriceInfo.java (暫時先不用):

package com.nb.security.order;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class PriceInfo {

    private Long id;

    private BigDecimal price;
}
View Code

++++++++++++++++++資源服務器現有的各個類結束++++++++++++++++++++++++++++

1,在資源服務器pom哩加上 oauth2的依賴:

        <!--OAuth2-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>

2,新建資源服務器配置類,繼承   ResourceServerConfigurerAdapter

package com.nb.security.resource.server;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * 資源服務器
 * 配置了@EnableResourceServer ,所有發往nb-order-api的請求,都會去請求頭里找token,找不到不讓你過
 */
@Configuration
@EnableResourceServer//告訴nb-order-api,你就是資源服務器
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //配置資源服務器的id,“現在我就是資源服務器order-server!!!”
        resources.resourceId("order-server");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        /**
         * 進入nb-order-api的所有請求,哪些要攔截,哪些要放過,在這里配置
         */
        http.authorizeRequests()
                .antMatchers("/hello")
                .permitAll() //放過/haha不攔截
                .anyRequest().authenticated();//其余所有請求都攔截
    }
}

 

ResourceServerConfigurerAdapter 有兩個方法:

 開篇說的1、2、3中的1和2已經完成了,下面做第3件事,怎么驗令牌:

新建配置類:

 

 

package com.nb.security.resource.server;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * 怎么驗發往本服務的請求頭的令牌
 * 1,自定義tokenServices ,說明去哪里去驗token
 * 2,重寫authenticationManagerBean()方法,將AuthenticationManager暴露為一個Bean
 *    要認證跟用戶相關的信息,一般用 AuthenticationManager
 *
 * 這樣配置了后,所有發往nb-order-api的請求,
 * 需要驗token的時候就會發請求去http://localhost:9090/oauth/check_token驗token,獲取到token對應的用戶信息
 */
@Configuration
@EnableWebSecurity
public class OAuth2WebSecurityConfig extends WebSecurityConfigurerAdapter{


    /**
     * 通過這個Bean,去遠程調用認證服務器,驗token
     * @return
     */
    @Bean
    public ResourceServerTokenServices tokenServices(){
        RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setClientId("orderService");//在認證服務器配置的,訂單服務的clientId
        tokenServices.setClientSecret("123456");//在認證服務器配置的,訂單服務的ClientSecret
        tokenServices.setCheckTokenEndpointUrl("http://localhost:9090/oauth/check_token");
        return tokenServices;
    }


    /**
     * 要認證跟用戶相關的信息,一般用 AuthenticationManager
     * 覆蓋這個方法,可以將AuthenticationManager暴露為一個Bean
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager();
        authenticationManager.setTokenServices(tokenServices());//設置為自定義的TokenServices,去校驗令牌
        return authenticationManager;
    }
}

 認證服務器關於訂單服務的配置:

 

 

 啟動認證服務器,

啟動訂單 資源服務器,

訪問認證服務器獲取token  : localhost:9090/oauth/token   

 

 

 

 

 

 拿着 token 去資源服務器創建訂單,注意,選擇bearer類型的token,生成的請求頭是這樣的(注:Authorization的value值,postman生成的是以Bearer開頭的,但是我看谷歌瀏覽器restclient插件生成的是bearer的B是小寫):

 

 

 在資源服務器里,可以通過該注解獲取用戶名:

錯誤的情況: 

如果把資源服務器配置的resourceId改成了order-server222,請求創建訂單,會受到如下的錯誤

 如果資源服務器檢驗token的cilentID獲取clientSecret寫錯了,后台會報錯:

 

 

 ++++++++++++++++++++++分割線++++++++++++++++++++++

小結:

接上篇的認證服務器,本篇實現了資源服務器,以及與認證服務器的交互,怎么去驗令牌。

遺留疑問:

認證服務器里面,配置資源服務器secret的時候,用passwordEncoder對123456進行了加密,而在資源服務器里,clientSecret確實明文的123456,這兩者不需要一致么?

認證服務器里對資源服務器ClientId、 ClientSecret配置:

 

 

 

資源服務器驗令牌攜帶的ClientId、 ClientSecret:

 

 

代碼github :https://github.com/lhy1234/springcloud-security/tree/chapt-4-5-resource-server

  

歡迎關注個人公眾號一起交流學習:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM