springboot2+springcloud+security

2020-04-13  本文已影响0人  ShennCl

springboo2+springcloud+security-oauth2+redis实现单点登录
文章目录
springboo2+springcloud+security-oauth2+redis实现单点登录
参考文献
开发环境
认证中心
业务服务
注册中心
网关服务
postman测试
Url是否走认证配置
参考文献
帅气dee海绵宝宝
史上最简单的 Spring Cloud 教程
spring-security-4 (4)spring security 认证和授权原理
Spring Security Oauth2 认证(获取token/刷新token)流程(password模式)
spring-oauth-server 数据库表说明
史上最简单的 Spring Cloud 教程
纯洁的微笑
SPRING SECURITY 4官方文档中文翻译与源码解读

开发环境
Intellij Idea,JDK1.8,Mysql,Redis,Spring Boot 2.1.3,mysql8.0.15,redis2.9
在项目开始阶段网关选用的是springcloud gateway,但是springcloud gateway不能依赖spring-boot-starter-web,它依赖的是spring-boot-starter-webflux,“间接“导致了网关不能继承WebSecurityConfigurerAdapter类,因此无法关闭CSRF(应该是我没有找到正确的方法),不得已把网关从gateway切换到了zuul。
项目结构:注册中心,网关,认证中心,业务服务

认证中心
一,认证中心引入依赖

<?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>
<parent>
<groupId>com.friday</groupId>
<artifactId>education</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>education-producer-oauth2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>education-producer-oauth2</name>
<description>this project for systerm user oauth2 server</description>

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

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</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.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator-autoconfigure</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>com.friday</groupId>
        <artifactId>education-common</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

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

</project>

二,认证中心配置

server.port= 1203
spring.application.name=producerOauth2

---------------------eureka----------------------

eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id={spring.cloud.client.ip-address}:{server.port}

-------------------mysql,druid-------------------------

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/producer_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123@.com
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.druid.initialSize=5
spring.druid.maxActive=20
spring.druid.maxWait=60000
spring.druid.minIdle=5
spring.druid.timeBetweenEvictionRunsMillis=60000
spring.druid.minEvictableIdleTimeMillis=300000
spring.druid.validationQuery=SELECT 1 from DUAL
spring.druid.testWhileIdle=true
spring.druid.testOnBorrow=false
spring.druid.testOnReturn=false
spring.druid.poolPreparedStatements=false
spring.druid.maxPoolPreparedStatementPerConnectionSize=20

配置扩展插件,常用的插件有=>stat:监控统计 log4j:日志 wall:防御sql注入

spring.druid.filters=stat,wall,slf4j

通过connectProperties属性来打开mergeSql功能;慢SQL记录

spring.druid.connectionProperties='druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000'

-------------------redis----------------------

spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=10000
spring.redis.jedis.pool.max-idle=50
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=0

------------------mybatis-------------------------

mybatis.type-aliases-package=com.friday.education.producer.oauth2.entity
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.jdbc-type-for-null=NULL
mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.aggressive-lazy-loading=true
mybatis.configuration.cache-enabled=true
mybatis.configuration.call-setters-on-nulls=true
mybatis.mapper-locations=classpath:mybatis/*.xml

不走认证的url集合

http.authorize.matchers=//css/,//js/,//plugin/,//template/,//img/,//fonts/,//cvr100u/,/css/,/js/,/plugin/,/template/,/img/,/fonts/,/cvr100u/**
http.login.path=/login

三,启动类

package com.friday.education.producer.oauth2;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.friday.education.producer.oauth2.dao")
public class EducationProducerOauth2Application {

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

}

四,OAuth2认证服务器

package com.friday.education.producer.oauth2.config.oauth;

import com.friday.education.producer.oauth2.config.error.MssWebResponseExceptionTranslator;
import com.friday.education.producer.oauth2.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.sql.DataSource;

/**

五,访问权限设置

package com.friday.education.producer.oauth2.config.oauth;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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 javax.servlet.http.HttpServletResponse;

/**

六,security配置

package com.friday.education.producer.oauth2.config.security;

import com.friday.education.producer.oauth2.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.password.PasswordEncoder;

/**

七,重写TokenStore

package com.friday.education.producer.oauth2.config.oauth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
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;

/**

*/
public class RedisTokenStore 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 RedisTokenStore(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 this.connectionFactory.getConnection();
}

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

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

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

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

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

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

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

@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    String key = this.authenticationKeyGenerator.extractKey(authentication);
    byte[] serializedKey = this.serializeKey(AUTH_TO_ACCESS + key);
    byte[] bytes = null;
    RedisConnection conn = this.getConnection();
    try {
        bytes = conn.get(serializedKey);
    } finally {
        conn.close();
    }
    OAuth2AccessToken accessToken = this.deserializeAccessToken(bytes);
    if (accessToken != null) {
        OAuth2Authentication storedAuthentication = this.readAuthentication(accessToken.getValue());
        if (storedAuthentication == null || !key.equals(this.authenticationKeyGenerator.extractKey(storedAuthentication))) {
            this.storeAccessToken(accessToken, authentication);
        }
    }
    return accessToken;
}

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

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

@Override
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
    return this.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.stringCommands().set(authKey, serializedAuth);
        conn.stringCommands().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.stringCommands().set(refreshToAccessKey, auth);
            byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
            conn.stringCommands().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) {
    this.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.stringCommands().set(refreshKey, serializedRefreshToken);
        conn.stringCommands().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) {
    this.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) {
    this.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);
    }
}

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);
}

}

八,MyUserDetailService实现UserDetailsService接口

package com.friday.education.producer.oauth2.service;

import com.friday.education.producer.oauth2.dao.UserDao;
import com.friday.education.producer.oauth2.entity.PUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**

九,dao,entity,controller

package com.friday.education.producer.oauth2.dao;

import com.friday.education.producer.oauth2.entity.PUser;

public interface UserDao {
PUser findByMemberName(String userName);
}

package com.friday.education.producer.oauth2.entity;

import com.friday.education.common.baseentity.BaseEntity;
import lombok.Data;

import java.util.Date;

/**

package com.friday.education.producer.oauth2.controller;

import com.friday.education.common.basecontroller.BaseController;
import com.friday.education.common.baseentity.Result;
import com.friday.education.common.baseentity.ResultCode;
import com.friday.education.producer.oauth2.service.MyUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**

业务服务
一,引入依赖

<?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>
<parent>
<groupId>com.friday</groupId>
<artifactId>education</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>education-pnr</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>education-pnr</name>
<description>this project for publish education resources (pnr)</description>

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

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</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.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.friday</groupId>
        <artifactId>education-common</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

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

</project>

二,配置文件

server.port= 8002
spring.application.name=pnr

-------------------------eureka-------------------------

eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id={spring.cloud.client.ip-address}:{server.port}

-------------------oauth2---------------------

security.oauth2.resource.id=pnr
security.oauth2.client.access-token-uri=http://localhost:1202/producerOauth2/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:1202/producerOauth2/oauth/authorize
security.oauth2.resource.user-info-uri=http://localhost:1202/producerOauth2/api/user
security.oauth2.resource.prefer-token-info=false

三,启动类

package com.friday.education.pnr;

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

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class EducationPnrApplication {
public static void main(String[] args) {
SpringApplication.run(EducationPnrApplication.class, args);
}
}

四,继承ResourceServerConfigurerAdapter类

package com.friday.education.pnr.config;

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 javax.servlet.http.HttpServletResponse;

/**

注册中心
一,引入依赖

<?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>
<parent>
<groupId>com.friday</groupId>
<artifactId>education</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>education-eureka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>education-eureka</name>
<description>this project for eureka</description>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</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>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

二,配置

spring.application.name=education-eureka
server.port=7001
eureka.instance.hostname=127.0.0.1
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://127.0.0.1:7001/education-eureka/

eureka.server.enable-self-preservation = false

网关服务
一,引入依赖

<?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>
<parent>
<groupId>com.friday</groupId>
<artifactId>education</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>education-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>education-gateway</name>
<description>this project for gateway server</description>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>-->
    <!--<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</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>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

二,配置服务
zuul:

server.port=1202
spring.application.name=gateway

---------------------eureka---------------------

eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id={spring.cloud.client.ip-address}:{server.port}

-----------------------zuul----------------------

zuul.routes.producerOauth2-api.path=/producerOauth2/**
zuul.routes.producerOauth2-api.service-id=producerOauth2
zuul.routes.producerOauth2-api.sensitiveHeaders=*
zuul.routes.pnr-api.path=/pnr/**
zuul.routes.pnr-api.service-id=pnr
zuul.routes.pnr-api.sensitiveHeaders=*
zuul.retryable=false
zuul.ignored-services=*
zuul.ribbon.eager-load.enabled=true
zuul.host.connect-timeout-millis=3000
zuul.host.socket-timeout-millis=3000
zuul.add-proxy-headers=true

ribbon.eager-load.enabled=true
logging.level.org.springframework.http.server.reactive=debug
logging.level.org.springframework.web.reactive=debug
logging.level.reactor.ipc.netty=debug

---------------------OAuth2---------------------

security.oauth2.client.client-id=gateway
security.oauth2.client.access-token-uri=http://localhost:{server.port}/producerOauth2/oauth/token security.oauth2.client.user-authorization-uri=http://localhost:{server.port}/producerOauth2/oauth/authorize
security.oauth2.resource.user-info-uri=http://localhost:${server.port}/producerOauth2/api/user

指定access token失效时长

security.oauth2.client.access-token-validity-seconds=30
security.oauth2.resource.prefer-token-info=false

gateway:

server.port=1202
spring.application.name=gateway

---------------------eureka---------------------

eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id={spring.cloud.client.ip-address}:{server.port}

-----------------------gateway----------------------

spring.cloud.gateway.default-filters[0]=PrefixPath=/httpbin
spring.cloud.gateway.default-filters[1]=AddResponseHeader=X-Response-Default-Foo, Default-Bar

开启服务注册和发现,如果此处设置为true,就不需要配置routes

spring.cloud.gateway.discovery.locator.enabled=true

将请求路径上的服务名配置为小写

spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true
spring.cloud.gateway.routes[0].id=pnr

pnr服务的负载均衡地址

spring.cloud.gateway.routes[0].uri=lb://pnr

以/pnr/开头的请求都会转发到uri为lb://PNR的地址上

spring.cloud.gateway.routes[0].predicates[0]=Path=/pnr/**

转发之前将/pnr去掉

spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1

spring.cloud.gateway.routes[1].id=producerOauth2
spring.cloud.gateway.routes[1].uri=lb://PRODUCEROAUTH2
spring.cloud.gateway.routes[1].predicates[0]=Path=/producerOauth2/**
spring.cloud.gateway.routes[1].filters[0]=StripPrefix=1
spring.cloud.gateway.routes[2].id=163
spring.cloud.gateway.routes[2].uri=http://www.163.com/
spring.cloud.gateway.routes[2].predicates[0]=Path=/163/**
spring.cloud.gateway.routes[2].filters[0]=StripPrefix=1

ribbon.eager-load.enabled=true
logging.level.org.springframework.cloud.gateway=trace
logging.level.org.springframework.http.server.reactive=debug
logging.level.org.springframework.web.reactive=debug
logging.level.reactor.ipc.netty=debug

---------------------OAuth2---------------------

security.oauth2.client.access-token-uri=http://localhost:{server.port}/producerOauth2/oauth/token security.oauth2.client.user-authorization-uri=http://localhost:{server.port}/producerOauth2/oauth/authorize
security.oauth2.client.client-id=web
security.oauth2.resource.user-info-uri=http://localhost:${server.port}/producerOauth2/api/user

指定access token失效时长

security.oauth2.client.access-token-validity-seconds=30
security.oauth2.resource.prefer-token-info=false

三,继承WebSecurityConfigurerAdapter类

package com.friday.education.gateway.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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;

/**

postman测试
1,获取认证:
http://192.168.29.6:1202/producerOauth2/oauth/token?grant_type=password&username=root&password=123@.com

获取认证

2.获得用户
http://192.168.29.6:1202/producerOauth2/api/user?access_token=c76bdb56-afc1-4a51-b159-223e259df0b2

获得用户

3,访问业务接口
http://192.168.29.6:1202/pnr/api/current?access_token=c76bdb56-afc1-4a51-b159-223e259df0b2

访问业务接口

4.token刷新
http://192.168.29.6:1202/producerOauth2/oauth/token?grant_type=refresh_token&refresh_token=1e555199-c8dd-4504-b484-53d3185df2db

token刷新

5,注销
http://192.168.29.6:1202/producerOauth2/api/exit?access_token=c76bdb56-afc1-4a51-b159-223e259df0b2

注销

Url是否走认证配置
像传统配置方式一样,把不走认证的代码放到了网关中之后,不管怎么配置,调用子服务中需要走认证的接口都报403
代码如下:

@Value("${http.authorize.matchers}")
private String[] httpAuthorizeMatchers;

private String[] getHttpAuthorizeMatchers() {
    List<String> matchers = new ArrayList<String>();
    matchers.add(uaaServerServicePath);
    matchers.add(securityOauth2SsoLoginPath);
    if (httpAuthorizeMatchers != null) {
        for (String httpAuthorizeMatcher : httpAuthorizeMatchers) {
            matchers.add(httpAuthorizeMatcher);
        }
    }
    return matchers.toArray(new String[matchers.size()]);
}
@Override
public void configure(HttpSecurity http) throws Exception {
    // 不需要认证的路径
    http.authorizeRequests().antMatchers(getHttpAuthorizeMatchers())
            .permitAll().anyRequest().authenticated();
    // 禁用csrf,csrf校验功能全部放到子系统
    http.csrf().disable();
}

按照上面这种方式,代码始终没有调通,不得已,把不走认证的代码放到了子服务中,代码立马就正常了

package com.friday.wf.basicdata.config;

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 javax.servlet.http.HttpServletResponse;

/**

在这个子服务中有两个controller,user和api,api不需要走认证,user需要,代码如下:

package com.friday.wf.customer.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**

package com.friday.wf.customer.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**

调用接口如下:


在这里插入图片描述 在这里插入图片描述
上一篇 下一篇

猜你喜欢

热点阅读