Spring Cloud Gateway and Security Certification

  1.Spring Cloud Gateway Profile

  Spring Cloud Spring Cloud Gateway is the official launch of the second generation gateway framework to replace the Zuul gateway. As the gateway traffic, in micro-services system has very role of the gateway routing and forwarding features are common, rights verification, current limit control and so on.

  2. Create Project

  In this paper we use the latest version of Spring Cloud "Finchley.SR2", note that the version corresponds Spring Boot is 2x. The official recommendation is: 2.0.6.RELEASE version.

  Project into the parent package as follows:

  org.springframework.boot

  spring-boot-starter-parent

  2.0.8.RELEASE

  pom

  import

  org.springframework.cloud

  spring-cloud-dependencies

  Finchley.SR2

  pom

  import

  org.mybatis.spring.boot

  mybatis-spring-boot-starter

  1.3.0

  com.alibaba

  dubbo

  2.6.6

  com.alibaba.spring

  spring-context-support

  1.0.2

  org.apache.curator

  curator-framework

  4.0.1

  org.apache.zookeeper

  zookeeper

  3.4.6

  org.hibernate

  hibernate-validator

  6.0.9.Final

  gateway gateway service to import the following jar:

  org.springframework.cloud

  spring-cloud-starter-gateway

  org.springframework.boot

  spring-boot-starter-test

  test

  org.springframework.boot

  spring-boot-starter-aop

  com.alibaba

  dubbo

  com.alibaba.spring

  spring-context-support

  org.apache.curator

  curator-framework

  org.apache.zookeeper

  zookeeper

  org.slf4j

  slf4j-log4j12

  Log4j

  Log4j

  com.uaf.credit

  uaf-credit-api

  org.springframework.boot

  spring-boot-starter-web

  Parent Project Management jar unified version of the package, the subproject will not have to add the jar corresponding version number

  yml configure the gateway services are as follows:

  server:

  port: 8817

  spring:

  application:

  name: uaf-credit-gateway

  security:

  user:

  name: wxt

  password: wxt2016

  cloud:

  gateway:

  routes:

  - id: credit-auth-route

  uri: http://10.168.xx.xx:8820/credit-auth/v1

  predicates:

  - Path = / credit-auth / v1 / * # paths, the matching of all paths to a user request / credit-auth request beginning

  logging:

  config: classpath:logback.xml

  3.Spring Cloud Gateway filters

  Spring-Cloud-Gateway in the bag filter has the following three interfaces guitar, GatewayFilter, GlobalFilter, GatewayFilterChain, GlobalGilter global filter GatewayFilter interface gateway interface has filters defined in the same manner. Global filter is a series of special filters, applied to all the route according to the conditions. Gateway filters more granular filter, acting on the specified routes.

  We can configure multiple GlobalFilter filters to configure the execution order of the filter specified by Priority getOrder () method.

  @Component

  public class RequestAuthFilter implements GlobalFilter, Ordered {

  /**

  * Mode request verification filter

  * @param exchange

  * @param chain

  * @return reactor.core.publisher.Mono

  * Author: will

  * Date: 2019/4/4 14:46

  */

  @Override

  public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {

  ServerHttpRequest serverHttpRequest = exchange.getRequest();

  String method = serverHttpRequest.getMethodValue();

  if(!"POST".equals(method)){

  ServerHttpResponse response = exchange.getResponse();

  . String message = new ResponseUtils () CreditRespMsg (CreditException.ERR_100008, "Illegal Request", null);

  byte[] bits = message.getBytes(StandardCharsets.UTF_8);

  DataBuffer buffer = response.bufferFactory().wrap(bits);

  response.setStatusCode(HttpStatus.UNAUTHORIZED);

  // specify the encoding, otherwise Chinese garbled in the browser

  response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");

  return response.writeWith(Mono.just(buffer));

  }

  return chain.filter(exchange);

  }

  /**

  * priority

  * @Return int The higher the number the lower the priority

  * Author: will

  * Date: 2019/4/4 13:36

  */

  @Override

  public int getOrder() {

  return 0;

  }

  }

  4.Spring boot Security Certification

  Spring Security is committed to providing authentication and authorization management for Java applications. It is a powerful, highly customizable authentication and access control framework definition, this sentence includes two key words: Authentication (authentication) and Authorization (authorization, also known as Access Control).

  Require secure authentication services need to import the following Jar:

  org.springframework.boot

  spring-boot-starter-security

  yml configuration:

  server:

  port: 8820

  servlet:

  context-path: /credit-auth

  spring:

  application:

  name: uaf-credit-auth

  security:

  user:

  name: wxt

  password: wxt2016

  roles:

  - USER

  logging:

  config: classpath:logback.xml

  Next, configure the authentication type:

  @Configuration

  @EnableWebSecurity

  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override

  protected void configure(HttpSecurity http) throws Exception {

  Before / ** means that all access must be an authentication process can be carried out properly * /

  http.httpBasic().and().authorizeRequests().anyRequest().fullyAuthenticated();

  / ** All the Rest services must be set to no state, in order to enhance operational performance * /

  http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

  401 occurs when abnormal / ** * POST request to avoid off csrf /

  http.csrf().disable();

  http.authorizeRequests().antMatchers(org.springframework.http.HttpMethod.GET).permitAll();

  }

  }

  There is a problem, if the request for service outside of our service requires Security certification, but our gateway should avoid the need for certification.

  We implemented by way of GlobalFilter filters Gateway:

  @Component

  public class OAuthSignatureFilter implements GlobalFilter, Ordered {

  / ** * authorized to access the username /

  @Value("${spring.security.user.name}")

  private String securityUserName;

  / Password authorized access ** * /

  @Value("${spring.security.user.password}")

  private String securityUserPassword;

  /**

  * OAuth filter

  * @param exchange

  * @param chain

  * @return reactor.core.publisher.Mono

  * Author: will

  * Date: 2019/4/4 13:36

  */

  @Override

  public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {

  / ** oauth authorization * /

  String auth= securityUserName.concat(":").concat(securityUserPassword);

  String encodedAuth = new sun.misc.BASE64Encoder().encode(auth.getBytes(Charset.forName("US-ASCII")));

  // Note that there is a space behind the Basic

  String authHeader= "Basic " +encodedAuth;

  // put the authorization information to the headers in

  ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().header("Authorization",authHeader).build();

  // The request will now become the object change

  ServerWebExchange build =exchange.mutate().request(serverHttpRequest).build();

  return chain.filter(build);

  }

  /**

  * priority

  * @Return int The higher the number the lower the priority

  * Author: will

  * Date: 2019/4/4 13:36

  */

  @Override

  public int getOrder() {

  return 2;

  }

  5. New Custom filter

  gateway which can be customized ordinary filter, you can create a custom GlobalFilter, we implement a custom filter through inheritance AbstractGatewayFilterFactory.

  yml add the following configuration:

  spring:

  application:

  name: uaf-credit-gateway

  security:

  user:

  name: wxt

  password: wxt2016

  cloud:

  gateway:

  routes:

  - id: credit-auth-route

  uri: http://10.168.xx.xx:8820/credit-auth/v1

  predicates:

  - Path = / credit-auth / v1 / * # paths, the matching of all paths to a user request / credit-auth request beginning

  filters: Wuxi flow of the hospital http://xmobile.wxbhnk120.com/

  - CreditFilter # attention consistent with the definition of the filter class name

  CreditFilter.java new class, custom filter lower priority than GlobalFilter

  @Configuration

  public class CreditFilter extends AbstractGatewayFilterFactory {

  public CreditFilter() {

  super(Config.class);

  }

  @Override

  public GatewayFilter apply(Config config) {

  MySlf4j.textInfo ( "Credit into the custom filter");

  return (exchange, chain) -> {

  String jwtToken = exchange.getRequest().getHeaders().getFirst("Authorization");

  // check the legality of jwtToken

  if (jwtToken != null) {

  // legal

  // user id will be passed on as a parameter

  return chain.filter(exchange);

  }

  // illegal (unregistered abnormal response)

  ServerHttpResponse response = exchange.getResponse();

  // set headers

  HttpHeaders httpHeaders = response.getHeaders();

  httpHeaders.add("Content-Type", "application/json; charset=UTF-8");

  httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");

  // set the body

  String warningStr = "is not logged or login timeout";

  DataBuffer bodyDataBuffer = response.bufferFactory().wrap(warningStr.getBytes());

  return response.writeWith(Mono.just(bodyDataBuffer));

  };

  }

  public static class Config {

  }

  @Bean

  public CreditFilter creditFileterFactory() {

  return new CreditFilter();

  }

  }

  So far our Gateway and related authorization and authentication configured.


Guess you like

Origin blog.51cto.com/14335413/2417365