SpringCloud微服务项目下的权限校验

1.以前的单体架构权限验证

用户登录操作传入用户名和密码,传到后端,后端到DB里查询,如果查到就返回登录成功并把session信息存到内存中并把session的唯一标识(JessionId)返回给我们的浏览器,浏览器就会把我们的JessionId存到cookie里面,当我们下一次请求的时候,一样会被我们的登录拦截器拦截到,然后通过JessionId获取session判断你有没有登录过,如果有就说明你已经登录了,这是我们最传统的基于session的登录校验和登录,参考下图:

传统项目的问题: 

1.保存信息到内存,会话保持(session会存储在内存里,如果用户量比较大呢?内存就会被沾满)

 2.JessionId存到浏览器cookie里面,如果cookie被拦截就有可能发生CSRF攻击(跨站攻击)

2.单体架构演变分布式架构权限验证

session就不能存在一台主机上了,就会存在第三方存储工具(redis/mongodb/db)

这种架构的缺点: 

JessionId和用户信息是绑定的,拿到JessionId就能拿到用户信息,一旦JessionId泄露了,别人就有可能CSRF跨域攻击你服务器

3.OAuth2.0框架为我们提供了4种授权方式

OAuth 引入了一个授权层,用来分离两种不同的角色:客户端和资源所有者。资源所有者同意以后,资源服务器可以向客户端颁发令牌。客户端通过令牌,去请求数据

这段话的意思就是,OAuth 的核心就是向第三方应用颁发令牌。然后,RFC 6749 接着写道:

(由于互联网有多种场景,)本标准定义了获得令牌的四种授权方式(authorization grant )。

也就是说,OAuth 2.0 规定了四种获得令牌的流程。你可以选择最适合自己的那一种,向第三方应用颁发令牌。下面就是这四种授权方式。

  • 授权码(authorization-code):指的是第三方应用先申请一个授权码,然后再用该码获取令牌。
  • 隐藏式(implicit)有些 Web 应用是纯前端应用,没有后端。这时就不能用上面的方式了,必须将令牌储存在前端。RFC 6749 就规定了第二种方式,允许直接向前端颁发令牌。这种方式没有授权码这个中间步骤,所以称为(授权码)"隐藏式"(implicit)。
  • 密码式(password):如果你高度信任某个应用,RFC 6749 也允许用户把用户名和密码,直接告诉该应用。该应用就使用你的密码,申请令牌,这种方式称为"密码式"(password)。
  • 客户端凭证(client credentials)适用于没有前端的命令行应用,即在命令行下请求令牌。

客户端模式(client credentials): 

是和客户端绑定的,比如说客户端有PC客户端,IOS客户端,安卓客户端,认证服务器就会颁布3个token,当用户请求zuul,zuul路由到服务端时会带上token,服务端拿到token后会去认证服务器进行token验证(只有token在有效期内并且没有被篡改,那么才会允许zuul请求下游接口)

token只是用户权限访问的字符串,与用户信息无关 

个人认为Zuul是没有必要做权限校验的,因为Zuul里是没有接口没有资源信息的,也就是说Zuul里面没有要保护的东西,下游系统必须要做权限校验。

当然也有Zuul做权限校验,下游系统没有做权限校验的系统,那是因为改了网络架构,Zuul是外网,下游系统设置在内网,然后下游系统设置了防火墙白名单(但是有种极端情况,内网网络被别人攻破,比如说同一个机房内的主机,有的主机能连外网,别人攻破了这台主机,就以这台主机为跳板机访问其他主机(因为你下游系统没有权限验证,那么别人就能随意访问了)),所以网络隔离并不可取。

所以综上两点:Zuul只做路由,下游系统设置在内网并且做权限校验和防火墙白名单,保证整个系统的安全性。

3.1 使用

3.1.1 jar包导入

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.micro.security</groupId>
  <artifactId>micro-security</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>micro-security</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <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>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-data</artifactId>
    </dependency>
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <!-- 1.5的版本默认采用的连接池技术是jedis  2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
      <exclusions>
        <exclusion>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
        </exclusion>
        <exclusion>
          <groupId>io.lettuce</groupId>
          <artifactId>lettuce-core</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <!--        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- 把mybatis的启动器引入 -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.0.0</version>
    </dependency>

    <!--        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>-->
  </dependencies>

  <dependencyManagement>
    <dependencies>
      <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>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

3.1.2启动类

package com.micro.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

@SpringBootApplication
@EnableEurekaClient
/*
* EnableResourceServer注解开启资源服务,因为程序需要对外暴露获取token的API和验证token的API所以该程序也是一个资源服务器
* */
@EnableResourceServer
public class MicroSecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(MicroSecurityApplication.class,args);
    }
}

 3.1.3配置文件

spring.application.name=micro-security
server.port=3030
eureka.client.serviceUrl.defaultZone=http://admin:admin@localhost:8763/eureka/

#spring.data.mongodb.uri=mongodb://192.168.67.139:27017/micro_security

#security.oauth2.resource.filter-order=3

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/consult?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=

spring.jpa.hibernate.ddl-auto:update
spring.jpa.show-sql:true

#sql日志
logging.level.com.xiangxue.jack.dao=debug

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

logging.level.org.springframework.security=debug

 3.1.4 config

3.1.4  AuthorizationServerConfig

package com.micro.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisConnectionFactory connectionFactory;

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public TokenStore tokenStore() {
        return new MyRedisTokenStore(connectionFactory);
    }

    /*
    * AuthorizationServerEndpointsConfigurer:用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)。
    * */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)//若无,refresh_token会有UserDetailsService is required错误
                .tokenStore(tokenStore()).
                allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
    }

    /*
    * AuthorizationServerSecurityConfigurer 用来配置令牌端点(Token Endpoint)的安全约束
    * */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security.allowFormAuthenticationForClients().tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    /*

        ClientDetailsServiceConfigurer:用来配置客户端详情服务(ClientDetailsService),客户端详情信息在这里进行初始化,你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
    *   1.授权码模式(authorization code)
        2.简化模式(implicit)
        3.密码模式(resource owner password credentials)
        4.客户端模式(client credentials)
    * */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456");

        clients.
//                jdbc(dataSource).
                inMemory().
                withClient("micro-web")//客户端id
                .resourceIds("micro-web")
                .authorizedGrantTypes("client_credentials", "refresh_token")//鉴权模式
                .scopes("all","read", "write","aa")//匹配字符串
                .authorities("client_credentials")
                .secret(finalSecret)//平台密码
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000)
                .and()
                .withClient("micro-zuul")
                .resourceIds("micro-zuul")
                .authorizedGrantTypes("password", "refresh_token")
                .scopes("server")
                .authorities("password")
                .secret(finalSecret)
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000);
    }
}

 3.1.5  MyRedisTokenStore

package com.micro.security.config;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;

import java.util.*;

public class MyRedisTokenStore implements TokenStore {

    private static final String ACCESS = "access:";
    private static final String AUTH_TO_ACCESS = "auth_to_access:";
    private static final String AUTH = "auth:";
    private static final String REFRESH_AUTH = "refresh_auth:";
    private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
    private static final String REFRESH = "refresh:";
    private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
    private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:";
    private static final String UNAME_TO_ACCESS = "uname_to_access:";

    private final RedisConnectionFactory connectionFactory;
    private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
    private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();

    private String prefix = "";

    public MyRedisTokenStore(RedisConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
        this.authenticationKeyGenerator = authenticationKeyGenerator;
    }

    public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
        this.serializationStrategy = serializationStrategy;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    private RedisConnection getConnection() {
        return connectionFactory.getConnection();
    }

    private byte[] serialize(Object object) {
        return serializationStrategy.serialize(object);
    }

    private byte[] serializeKey(String object) {
        return serialize(prefix + object);
    }

    private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
    }

    private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
    }

    private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
    }

    private byte[] serialize(String string) {
        return serializationStrategy.serialize(string);
    }

    private String deserializeString(byte[] bytes) {
        return serializationStrategy.deserializeString(bytes);
    }

    @Override
    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
        String key = authenticationKeyGenerator.extractKey(authentication);
        byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(serializedKey);
        } finally {
            conn.close();
        }
        OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
        if (accessToken != null) {
            OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
            if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
                // Keep the stores consistent (maybe the same user is
                // represented by this authentication but the details have
                // changed)
                storeAccessToken(accessToken, authentication);
            }

        }
        return accessToken;
    }

    @Override
    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
        return readAuthentication(token.getValue());
    }

    @Override
    public OAuth2Authentication readAuthentication(String token) {
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(serializeKey(AUTH + token));
        } finally {
            conn.close();
        }
        OAuth2Authentication auth = deserializeAuthentication(bytes);
        return auth;
    }

    @Override
    public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
        return readAuthenticationForRefreshToken(token.getValue());
    }

    public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
        RedisConnection conn = getConnection();
        try {
            byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token));
            OAuth2Authentication auth = deserializeAuthentication(bytes);
            return auth;
        } finally {
            conn.close();
        }
    }

    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        byte[] serializedAccessToken = serialize(token);
        byte[] serializedAuth = serialize(authentication);
        byte[] accessKey = serializeKey(ACCESS + token.getValue());
        byte[] authKey = serializeKey(AUTH + token.getValue());
        byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
        byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
        byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());

        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.stringCommands().set(accessKey, serializedAccessToken);
            conn.set(authKey, serializedAuth);
            conn.set(authToAccessKey, serializedAccessToken);
            if (!authentication.isClientOnly()) {
                conn.rPush(approvalKey, serializedAccessToken);
            }
            conn.rPush(clientId, serializedAccessToken);
            if (token.getExpiration() != null) {
                int seconds = token.getExpiresIn();
                conn.expire(accessKey, seconds);
                conn.expire(authKey, seconds);
                conn.expire(authToAccessKey, seconds);
                conn.expire(clientId, seconds);
                conn.expire(approvalKey, seconds);
            }
            OAuth2RefreshToken refreshToken = token.getRefreshToken();
            if (refreshToken != null && refreshToken.getValue() != null) {
                byte[] refresh = serialize(token.getRefreshToken().getValue());
                byte[] auth = serialize(token.getValue());
                byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
                conn.set(refreshToAccessKey, auth);
                byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
                conn.set(accessToRefreshKey, refresh);
                if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
                    ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
                    Date expiration = expiringRefreshToken.getExpiration();
                    if (expiration != null) {
                        int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
                                .intValue();
                        conn.expire(refreshToAccessKey, seconds);
                        conn.expire(accessToRefreshKey, seconds);
                    }
                }
            }
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }

    private static String getApprovalKey(OAuth2Authentication authentication) {
        String userName = authentication.getUserAuthentication() == null ? ""
                : authentication.getUserAuthentication().getName();
        return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
    }

    private static String getApprovalKey(String clientId, String userName) {
        return clientId + (userName == null ? "" : ":" + userName);
    }

    @Override
    public void removeAccessToken(OAuth2AccessToken accessToken) {
        removeAccessToken(accessToken.getValue());
    }

    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        byte[] key = serializeKey(ACCESS + tokenValue);
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(key);
        } finally {
            conn.close();
        }
        OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
        return accessToken;
    }

    public void removeAccessToken(String tokenValue) {
        byte[] accessKey = serializeKey(ACCESS + tokenValue);
        byte[] authKey = serializeKey(AUTH + tokenValue);
        byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.get(accessKey);
            conn.get(authKey);
            conn.del(accessKey);
            conn.del(accessToRefreshKey);
            // Don't remove the refresh token - it's up to the caller to do that
            conn.del(authKey);
            List<Object> results = conn.closePipeline();
            byte[] access = (byte[]) results.get(0);
            byte[] auth = (byte[]) results.get(1);

            OAuth2Authentication authentication = deserializeAuthentication(auth);
            if (authentication != null) {
                String key = authenticationKeyGenerator.extractKey(authentication);
                byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
                byte[] unameKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
                byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
                conn.openPipeline();
                conn.del(authToAccessKey);
                conn.lRem(unameKey, 1, access);
                conn.lRem(clientId, 1, access);
                conn.del(serialize(ACCESS + key));
                conn.closePipeline();
            }
        } finally {
            conn.close();
        }
    }

    @Override
    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
        byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
        byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
        byte[] serializedRefreshToken = serialize(refreshToken);
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.set(refreshKey, serializedRefreshToken);
            conn.set(refreshAuthKey, serialize(authentication));
            if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
                ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
                Date expiration = expiringRefreshToken.getExpiration();
                if (expiration != null) {
                    int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
                            .intValue();
                    conn.expire(refreshKey, seconds);
                    conn.expire(refreshAuthKey, seconds);
                }
            }
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }

    @Override
    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
        byte[] key = serializeKey(REFRESH + tokenValue);
        byte[] bytes = null;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(key);
        } finally {
            conn.close();
        }
        OAuth2RefreshToken refreshToken = deserializeRefreshToken(bytes);
        return refreshToken;
    }

    @Override
    public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
        removeRefreshToken(refreshToken.getValue());
    }

    public void removeRefreshToken(String tokenValue) {
        byte[] refreshKey = serializeKey(REFRESH + tokenValue);
        byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue);
        byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue);
        byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.del(refreshKey);
            conn.del(refreshAuthKey);
            conn.del(refresh2AccessKey);
            conn.del(access2RefreshKey);
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }

    @Override
    public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
        removeAccessTokenUsingRefreshToken(refreshToken.getValue());
    }

    private void removeAccessTokenUsingRefreshToken(String refreshToken) {
        byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
        List<Object> results = null;
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            conn.get(key);
            conn.del(key);
            results = conn.closePipeline();
        } finally {
            conn.close();
        }
        if (results == null) {
            return;
        }
        byte[] bytes = (byte[]) results.get(0);
        String accessToken = deserializeString(bytes);
        if (accessToken != null) {
            removeAccessToken(accessToken);
        }
    }

    @Override
    public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
        byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(clientId, userName));
        List<byte[]> byteList = null;
        RedisConnection conn = getConnection();
        try {
            byteList = conn.lRange(approvalKey, 0, -1);
        } finally {
            conn.close();
        }
        if (byteList == null || byteList.size() == 0) {
            return Collections.<OAuth2AccessToken> emptySet();
        }
        List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(byteList.size());
        for (byte[] bytes : byteList) {
            OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
            accessTokens.add(accessToken);
        }
        return Collections.<OAuth2AccessToken> unmodifiableCollection(accessTokens);
    }

    @Override
    public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
        byte[] key = serializeKey(CLIENT_ID_TO_ACCESS + clientId);
        List<byte[]> byteList = null;
        RedisConnection conn = getConnection();
        try {
            byteList = conn.lRange(key, 0, -1);
        } finally {
            conn.close();
        }
        if (byteList == null || byteList.size() == 0) {
            return Collections.<OAuth2AccessToken> emptySet();
        }
        List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(byteList.size());
        for (byte[] bytes : byteList) {
            OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
            accessTokens.add(accessToken);
        }
        return Collections.<OAuth2AccessToken> unmodifiableCollection(accessTokens);
    }

}

 3.1.6  SecurityConfiguration

package com.micro.security.config;

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.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        String finalPassword = "{bcrypt}" + bCryptPasswordEncoder.encode("123456");
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("jack").password(finalPassword).authorities("USER").build());
        manager.createUser(User.withUsername("admin").password(finalPassword).authorities("USER").build());

        return manager;
    }

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

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
//        http.requestMatchers().anyRequest()
//                .and()
//                .authorizeRequests()
//                .antMatchers("/oauth/**").permitAll();

        http.authorizeRequests()
                .antMatchers("/oauth/**","/actuator/**").permitAll()
                .and()
                .httpBasic().disable();
    }
}

3.1.7 我们可以看到客户端模式申请 token,只要带上有平台资质的客户端 id、客户端密码、然后 带上授权类型是客户端授权模式,带上 scope 就可以了。这里要注意的是客户端必须是具有 资质的。

POST请求

http://localhost:3030/oauth/token
grant_type:client_credentials
client_id:micro-web
client_secret:123456
scope:all

 3.1.8 客户端信息配置 参考3.1.4

  3.1.9 配置 token 存储方式 参考3.1.4

 Oauth2.0 权限校验认证服务器代码配置和客户端代码配置基本上是固定写法,这里知道如何 使用即可,关键是理解认证授权过程,oauth2.0 授权流程基本上是行业认证授权的标准了。

客户端请求

密码模式获取 token

密码模式获取 token,也就是说在获取 token 过程中必须带上用户的用户名和密码,获取到 的 token 是跟用户绑定的。

密码模式获取 token:

客户端 id 和客户端密码必须要经过 base64 算法加密,并且放到 header 中,加密模式为 Base64(clientId:clientPassword),如下:

其他参数:

 获取到的 token

1、密码模式认证服务器代码配置

加上注解,说明是认证服务器 

 

1、客户端配置,客户端是存储在表中的 

对应的客户端表为:oauth_client_details

表中数据: 把客户端信息加入到 oauth2.0 框架中 

2、token 的保存方式,token 是也存储在数据库中 

对应的 token 存储表为:oauth_access_token

表中数据: 

可以看到 token 是跟用户绑定的。

设置 token 的属性 

3、认证服务器 token 校验和校验结果返回接口

 2、密码模式下游系统配置

1、properties 配置

指定客户端请求认证服务器接口 

2、声明使用 oauth2.0 框架并说明这是一个客户 

 3、开启权限的方法级别注解和指定拦截路径

认证服务器和下游系统权限校验流程 

1、zuul 携带 token 请求下游系统,被下游系统 filter 拦截

2、下游系统过滤器根据配置中的 user-info-uri 请求到认证服务器

3、请求到认证服务器被 filter 拦截进行 token 校验,把 token 对应的用户、和权限从数据库 查询出来封装到 Principal

4、认证服务器 token 校验通过后过滤器放行执行 security/check 接口,把 principal 对象返回 5、下游系统接收到 principal 对象后就知道该 token 具备的权限了,就可以进行相应用户对 应的 token 的权限执行 

授权码模式获取 token

授权码模式获取 token,在获取 token 之前需要有一个获取 code 的过程。

1、获取 code 的流程如下:

1、用户请求获取 code 的链接 http://localhost:7070/auth/oauth/authorize?client_id=pc&response_type=code&redirect_uri=htt p://localhost:8083/login/callback

2、提示要输入用户名密码

3、用户名秘密成功则会弹出界面 

4、点击 approve 则会回调 redirect_uri 对应的回调地址并且把 code 附带到该回调地址里面

2、根据获取到的 code 获取 token

这里必须带上 redirect_uri 和 code,其他就跟前面的类似 

 其他配置跟密码模式的是一样的,拿到 token 后就可以访问了。

1、客户端模式 一般用在无需用户登录的系统做接口的安全校验,因为 token 只需要跟客户端绑定,控制粒 度不够细

2、密码模式 密码模式,token 是跟用户绑定的,可以根据不同用户的角色和权限来控制不同用户的访问 权限,相对来说控制粒度更细

3、授权码模式 授权码模式更安全,因为前面的密码模式可能会存在密码泄露后,别人拿到密码也可以照样 的申请到 token 来进行接口访问,而授权码模式用户提供用户名和密码获取后,还需要有一 个回调过程,这个回调你可以想象成是用户的手机或者邮箱的回调,只有用户本人能收到这 个 code,即使用户名密码被盗也不会影响整个系统的安全。

JWT 模式

JWT:json web token 是一种无状态的权限认证方式,一般用于前后端分离,时效性比较端 的权限校验,jwt 模式获取 token 跟前面的,客户端,密码,授权码模式是一样的,只是需 要配置秘钥:

1、生成秘钥文件

cd 到 jdk 的 bin 目录执行该指令,会在 bin 目录下生成 micro-jwt.jks 文件,把该文件放到认 证服务工程里面的 resources 目录下:

keytool -genkeypair -alias micro-jwt

-validity 3650

-keyalg RSA

-dname "CN=jwt,OU=jtw,O=jwt,L=zurich,S=zurich, C=CH"

-keypass 123456

-keystore micro-jwt.jks

-storepass 123456

2、生成公钥

keytool -list -rfc --keystore micro-jwt.jks | openssl x509 -inform pem -pubkey

把生成的公钥内容放到 public.cert 文件中,内容如下:

把公钥文件放到客户端的 resources 目录下。

密码模式获取 jwt token:

 

 eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODQ5ODc0ODMsInVzZXJfbmFtZSI6ImphbWVzIiwiYXV0aG9yaXRpZXMiOl siUk9MRV9BRE1JTiJdLCJqdGkiOiIxNTAwNDcwOC1kZjVlLTQ1NzMtODExZi0xOWExMDA2ZjI3NmMiLCJjbGllbnRfaWQiOiJwYyIsInNjb 3BlIjpbImFsbCJdfQ.HoUFEnGVG2FLCOvtIK02RmZGovpWUvcsH0TO-jyes1rj1ZqT_GeQ5uU0LMHIddZ0nYOBXCYJgR5vQkC-OOT64LpP0 ypLbp9mPbEtYrzl3iT91cqpb_gcBFDZR7Wzi5eW9_B7BtfF9BvgEp51KicnpYgsN7yb4t5OXcn1Ves4uYSeNG96N9Yt0bgiA34-r8cZfA8_ UePMY1sZRS3jgmBt--TcjXqJy-GRcL6_ilGgbwQyt-znOqxOxUg7glm9Zixbf27FmPkB0mqJ2qsNqqLz3Cc_RMTi24myRMVW6vSlx789s6t Eh74lIwdEAzO73q_HPAvmOJO0RQNow9LhXFve6g

 Jwt 的 token 信息分成三个部分,用“.”号分割的

第一步部分:头信息,通过 base64 加密生成

第二部分:有效载荷,通过 base64 加密生成

第三部分:签名,根据头信息中的加密算法通过,RSA(base64(头信息) + “.” + base64(有效载 荷))生成的第三部分内容

可以到 jwt 的官网看看这三部分信息的具体内容:jwt 官网 jwt.io

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Cloud微服务架构中,由于涉及到多个微服务之间的调用,确保数据一致性是一个重要的问题。以下是保证数据一致性的一些方法: 1. 分布式事务:使用分布式事务来确保多个微服务之间的数据操作具有原子性、一致性、隔离性和持久性。可以通过使用消息队列、两阶段提交或TCC(Try-Confirm-Cancel)等机制来实现分布式事务。这样可以确保对多个服务的操作要么全部成功,要么全部回滚,保持数据的一致性。 2. 异步处理:可以将不必要立即执行的操作异步处理,在需要时再进行处理。例如,将数据提交到消息队列中,然后由后台任务进行处理,以免阻塞或延迟请求的返回。这样可以确保即使某个服务不可用,数据也可以在之后被处理,并最终保持一致。 3. 冗余校验:对于特别重要的数据操作,可以在多个服务中进行冗余校验,以确保数据的一致性。例如,在进行关键操作之前,可以先查询相关微服务的数据,然后进行比较和校验,以确保数据一致。 4. 重试机制:在微服务之间的调用过程中,可能会出现网络故障、服务不可用等问题,为了确保数据的一致性,可以在发生错误时进行重试。通过设置合理的重试机制,可以确保在一定次数的重试后,数据操作成功并保持一致。 5. 数据同步:对于需要在多个服务之间共享的数据,可以采用定期同步的方式,确保数据在各个服务中是一致的。例如,可以通过定时任务或订阅发布模式来实现数据的同步。 综上所述,通过采用分布式事务、异步处理、冗余校验、重试机制和数据同步等方式,可以在Spring Cloud微服务架构中保证数据的一致性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值