springboot2+springcloud+security-oauth2+redis实现单点登录

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;

/**

  • @ClassName OAuthServerConfig

  • @Description TODO Oauth2认证服务器

  • @Author Zeus

  • @Date 2019/3/27 10:42

  • @Version 1.0
    /
    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private RedisConnectionFactory connectionFactory;
    @Autowired
    private MyUserDetailService userDetailService;
    /

    • @Description 使用TokenStore操作Token
      /
      @Bean
      public TokenStore tokenStore() {
      return new RedisTokenStore(connectionFactory);
      }
      /

      *用来配置令牌端点(Token Endpoint)的安全约束.
      /
      @Override
      public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
      security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();;
      }
      /
    • 配置客户端详情服务
    • 可以把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
      /
      @Override
      public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      /
      clients.inMemory() // 使用in-memory存储
      .withClient("root") // client_id android
      .scopes("read")
      .secret("123@.com") // client_secret android
      .authorizedGrantTypes("password", "authorization_code", "refresh_token") // 该client允许的授权类型
      .and()
      .withClient("webapp") // client_id
      .scopes("read")
      //.secret("webapp") // client_secret
      .authorizedGrantTypes("implicit")// 该client允许的授权类型
      .and()
      .withClient("browser")
      .authorizedGrantTypes("refresh_token", "password")
      .scopes("read");
      /
      // //客户端信息通过Redis去取得验证
      // final RedisClientDetailsServiceBuilder builder = new RedisClientDetailsServiceBuilder();
      // clients.setBuilder(builder);
      //通过JDBC去查询数据库oauth_client_details表验证clientId信息
      clients.jdbc(this.dataSource).clients(this.clientDetails());
      // clients.withClientDetails(clientDetails());
      }
      @Bean
      public ClientDetailsService clientDetails() {
      return new JdbcClientDetailsService(dataSource);
      }
      @Bean
      public WebResponseExceptionTranslator webResponseExceptionTranslator(){
      return new MssWebResponseExceptionTranslator();
      }

    /**

    • 用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)。
      **/
      @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints.tokenStore(tokenStore())
      .userDetailsService(userDetailService)
      .authenticationManager(authenticationManager);
      endpoints.tokenServices(defaultTokenServices());
      //认证异常翻译
      // endpoints.exceptionTranslator(webResponseExceptionTranslator());
      }

    /**

    • <p>注意,自定义TokenServices的时候,需要设置@Primary,否则报错,</p>
    • 自定义的token
    • 认证的token是存到redis里的
    • @return
      /
      @Primary
      @Bean
      public DefaultTokenServices defaultTokenServices(){
      DefaultTokenServices tokenServices = new DefaultTokenServices();
      tokenServices.setTokenStore(tokenStore());
      tokenServices.setSupportRefreshToken(true);
      //tokenServices.setClientDetailsService(clientDetails());
      // token有效期自定义设置,默认12小时
      tokenServices.setAccessTokenValiditySeconds(60
      60*12);
      // refresh_token默认30天
      tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
      return tokenServices;
      }

    /* //*

    • 密码匹配
      //
      @Bean
      public PasswordEncoder passwordEncoder() {
      return new MyBCryptPasswordEncoder();
      }
      //
    • @Description //TODO
      *//
      @Bean
      public AuthorizationCodeServices authorizationCodeServices() {
      return new JdbcAuthorizationCodeServices(dataSource);
      }

    @Bean
    public ApprovalStore approvalStore() {
    TokenApprovalStore store = new TokenApprovalStore();
    store.setTokenStore(tokenStore());
    return store;
    }*/
    }

五,访问权限设置

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;

/**

  • @ClassName ResourceServerConfig
  • @Description TODO 访问权限配置
  • @Author Zeus
  • @Date 2019/3/27 14:16
  • @Version 1.0
    /
    @Configuration
    @EnableResourceServer
    @Order(3)
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .exceptionHandling()
    .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
    .and()
    .requestMatchers().antMatchers("/api/
    ")
    .and()
    .authorizeRequests()
    .antMatchers("/api/**").authenticated()
    .and()
    .httpBasic();
    }
    }

六,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;

/**

  • 〈security配置〉

  • 配置Spring Security

  • ResourceServerConfig 是比SecurityConfig 的优先级低的

  • @Author Zeus

  • @Date 2019/3/27 18:13

  • @Version 1.0
    **/
    @Configuration
    @EnableWebSecurity
    @Order(2)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailService userDetailService;

    @Bean
    public PasswordEncoder passwordEncoder() {
    return new MyBCryptPasswordEncoder();
    // return new NoEncryptPasswordEncoder();
    }

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

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

    /**

    • 不定义没有password grant_type,密码模式需要AuthenticationManager支持
    • @return
    • @throws Exception
      */
      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
      }
      }

七,重写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;

/**

  • <Description> 重写tokenStore .因为最新版中RedisTokenStore的set已经被弃用了,
  • 所以我就只能自定义一个,代码和RedisTokenStore一样,
  • 只是把所有conn.set(…)都换成conn..stringCommands().set(…),

*/
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;

/**

  • @ClassName MyUserDetailService
  • @Description TODO 自定义认证逻辑
  • @Author Zeus
  • @Date 2019/3/27 17:34
  • @Version 1.0
    /
    @Service//("userDetailService")
    public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    PUser user = userDao.findByMemberName(userName);
    if (user == null) {
    throw new UsernameNotFoundException(userName);
    }
    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    // 可用性 :true:可用 false:不可用
    boolean enabled = true;
    // 过期性 :true:没过期 false:过期
    boolean accountNonExpired = true;
    // 有效性 :true:凭证有效 false:凭证无效
    boolean credentialsNonExpired = true;
    // 锁定性 :true:未锁定 false:已锁定
    boolean accountNonLocked = true;
    /
    for (Role role : member.getRoles()) {
    //角色必须是ROLE_开头,可以在数据库中设置
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
    grantedAuthorities.add(grantedAuthority);
    //获取权限
    for (Permission permission : role.getPermissions()) {
    GrantedAuthority authority = new SimpleGrantedAuthority(permission.getUri());
    grantedAuthorities.add(authority);
    }
    }
    /
    User us = new User(user.getUserName(), user.getPassword(),
    enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
    return us;
    }
    }

九,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;

/**

  • @ClassName PUser
  • @Description TODO
  • @Author Zeus
  • @Date 2019/3/21 15:00
  • @Version 1.0
    **/
    @Data
    public class PUser extends BaseEntity {
    private String userId;
    private String loginCode;
    private String userName;
    private String password;
    private String email;
    private String mobile;
    private String phone;
    private int status;
    private String createBy;
    private Date createDate;
    private String updateBy;
    private Date updateDate;
    private String remarks;
    }

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;

/**

  • @ClassName LoginController

  • @Description TODO 登陆、退出控制器

  • @Author Zeus

  • @Date 2019/3/21 15:22

  • @Version 1.0
    **/
    @Slf4j
    @RestController
    @RequestMapping("/api")
    public class LoginController extends BaseController {
    @Autowired
    private MyUserDetailService userDetailService;

    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @GetMapping("/user")
    public Principal user(Principal user) {
    //获取当前用户信息
    log.debug("user",user);
    return user;
    }

    @DeleteMapping(value = "/exit")
    public Result revokeToken(String access_token) {
    //注销当前用户
    Result result = new Result();
    if (consumerTokenServices.revokeToken(access_token)) {
    result.setCode(ResultCode.SUCCESS.getCode());
    result.setMessage("注销成功");
    } else {
    result.setCode(ResultCode.FAILED.getCode());
    result.setMessage("注销失败");
    }
    return result;
    }
    }

业务服务
一,引入依赖

<?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;

/**

  • @ClassName ResourceServerConfig
  • @Description TODO
  • @Author Zeus
  • @Date 2019/3/28 14:48
  • @Version 1.0
    /
    @Configuration
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .exceptionHandling()
    .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
    .and()
    .requestMatchers().antMatchers("/api/
    ")
    .and()
    .authorizeRequests()
    .antMatchers("/api/**").authenticated()
    .and()
    .httpBasic();
    }
    }

注册中心
一,引入依赖

<?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;

/**

  • @ClassName SecurityConfig
  • @Description TODO
  • @Author Zeus
  • @Date 2019/3/28 14:45
  • @Version 1.0
    **/
    @Configuration
    @EnableWebSecurity
    @Order(99)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    }
    }

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;

/**

  • @ClassName ResourceServerConfig
  • @Description TODO
  • @Author Zeus
  • @Date 2019/3/28 14:48
  • @Version 1.0
    /
    @Configuration
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .exceptionHandling()
    .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
    .and()
    .requestMatchers().antMatchers("/
    /")
    .and()
    .authorizeRequests()
    .antMatchers("/api/
    ").permitAll()
    .anyRequest().authenticated()
    .and()
    .httpBasic();
    }
    }

在这个子服务中有两个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;

/**

  • @ClassName UserController

  • @Description TODO

  • @Author Zeus

  • @Date 2019/3/28 14:50

  • @Version 1.0
    **/
    @RestController
    @RequestMapping("/api")
    public class ApiController {
    @GetMapping("hello")
    // @PreAuthorize("hasAnyAuthority('hello')")
    public String hello(){
    return "hello";
    }

    @GetMapping("current")
    public Principal user(Principal principal) {
    return principal;
    }

    @GetMapping("query")
    // @PreAuthorize("hasAnyAuthority('query')")
    public String query() {
    return "具有query权限";
    }
    }

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;

/**

  • @ClassName UserController

  • @Description TODO

  • @Author Zeus

  • @Date 2019/3/28 14:50

  • @Version 1.0
    **/
    @RestController
    @RequestMapping("/user")
    public class UserController {
    @GetMapping("hello")
    // @PreAuthorize("hasAnyAuthority('hello')")
    public String hello(){
    return "hello";
    }

    @GetMapping("current")
    public Principal user(Principal principal) {
    return principal;
    }

    @GetMapping("query")
    // @PreAuthorize("hasAnyAuthority('query')")
    public String query() {
    return "具有query权限";
    }
    }

调用接口如下:


在这里插入图片描述
在这里插入图片描述
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,723评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,080评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,604评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,440评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,431评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,499评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,893评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,541评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,751评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,547评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,619评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,320评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,890评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,896评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,137评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,796评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,335评论 2 342

推荐阅读更多精彩内容