2020/09/02更新
Github开源脚手架,在网关处统一进行鉴权,授权服务器可单独部署或者走网关,具体见 https://github.com/beifei1/fire-cloud
本文基于Spring Cloud Security OAuth2实现微服务应用的保护,具体概念理解可参考
深入理解Spring Cloud Security OAuth2及JWT
应用版本
Spring Boot: 2.1.1.RELEASE
Spring Cloud:Greenwich.SR2
应用实现
Eureka Server服务
pom.xml
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion> 
  <parent> 
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-parent</artifactId>  
    <version>2.1.1.RELEASE</version>  
    <relativePath/>  
    <!-- lookup parent from repository --> 
  </parent>  
  <groupId>com.wang</groupId>  
  <artifactId>eureka-server</artifactId>  
  <version>0.0.1-SNAPSHOT</version>  
  <name>eureka-server</name>  
  <description>Demo project for Spring Boot</description>  
  <properties> 
    <java.version>1.8</java.version>  
    <spring-cloud.version>Greenwich.SR2</spring-cloud.version> 
  </properties>  
  <dependencies> 
    <dependency> 
      <groupId>org.springframework.cloud</groupId>  
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-web</artifactId> 
    </dependency>  
    <dependency> 
      <groupId>com.netflix.feign</groupId>  
      <artifactId>feign-slf4j</artifactId>  
      <version>8.14.4</version> 
    </dependency>  
    <dependency> 
      <groupId>org.projectlombok</groupId>  
      <artifactId>lombok</artifactId>  
      <optional>true</optional> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-test</artifactId>  
      <scope>test</scope>  
      <exclusions> 
        <exclusion> 
          <groupId>org.junit.vintage</groupId>  
          <artifactId>junit-vintage-engine</artifactId> 
        </exclusion> 
      </exclusions> 
    </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>
定义应用配置application.yml
spring:
  application:
    name: eureka-server #application name
eureka:
  instance:
    hostname: localhost
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/
    register-with-eureka: false #是否向注册自己,该应用为服务治理,不注册自己
    fetch-registry: false #服务治理应用,不拉取注册列表
  server:
    enable-self-preservation: false #禁用自我保护
    eviction-interval-timer-in-ms: 5000 #剔除无用节点的间隔时间
定义启动类
@EnableEurekaServer //开启eureka支持
@SpringBootApplication
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
Auth Server服务
application.yml
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka
server:
  port: 8081
spring:
  application:
    name: auth-service
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/spring-cloud-auth?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&useSSL=false&serverTimezone=GMT
    username: root
    password: root123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
spring security安全配置
@Configuration
@EnableWebSecurity //启用security
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法级权限控制
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request,response,exception) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))  //切入点,可自定义未授权响应体
                .and()
                .authorizeRequests()
                .antMatchers("/**").authenticated() //所有路径均启用安全
                .and().httpBasic();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中创建两个用户便于测试,实际应用可用userdetail
        auth.inMemoryAuthentication()
                .withUser("wangzhichao").password("123456").roles("USER").and()            .withUser("admin").password("123456").roles("ADMIN").and().passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
oauth2配置
@Configuration
@EnableAuthorizationServer //开启授权服务器支持
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;  //注入Security配置中的manager
@Autowired
private JwtTokenEnhancer jwtTokenEnhancer; //自定义JWT内容(jwt增强器)
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    //定义两个client,授权范围为refresh_token,password
    clients.inMemory()
            .withClient("app").secret("123456").scopes("app-service").authorizedGrantTypes("refresh_token","password")
            .and()
            .withClient("system").secret("123456").scopes("system-service").authorizedGrantTypes("refresh_token","password")
            .accessTokenValiditySeconds(3600);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore()).tokenEnhancer(initTokenEnhancerChanin())
            .authenticationManager(authenticationManager);
}
public TokenStore tokenStore() {
    return new JwtTokenStore(jwtAccessTokenConverter());
}
//jwt token 解析器
private JwtAccessTokenConverter jwtAccessTokenConverter() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("study-jwt.jks"),"123456".toCharArray());
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("study-jwt"));
    return converter;
}
public TokenEnhancerChain initTokenEnhancerChanin() {
    //token增强链
    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
    List<TokenEnhancer> list = new ArrayList<>();
    list.add(jwtTokenEnhancer); //注入定义好的自定义token增强
    list.add(jwtAccessTokenConverter());
    tokenEnhancerChain.setTokenEnhancers(list);
    return tokenEnhancerChain;
}
}
定义JWT增强,可自由定义jwt的 拓展信息
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessTokenoAuth2AccessToken,OAuth2Authentication oAuth2Authentication) {
        Map<String,Object> map = new HashMap<>();
        map.put("extension","jwt 拓展信息");
        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(map);
    return oAuth2AccessToken;
    }
}
关于JKS文件及pubkey相关使用可参考Java keytool生成jks证书,并使用openssl查看公钥信息
把生成的jks文件放入到auth文件的classpath中
user consumer(Resource Server)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wang</groupId>
    <artifactId>user-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>user-consumer</name>
    <description>Demo project for Spring Boot</description>
<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencies>
    <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-security</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-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </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>
application.yml
server:
  port: 8082
spring:
  application:
    name: user-consumer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/
启动类
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法级安全配置
public class UserConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserConsumerApplication.class, args);
    }
}
配置jwt解析器
@Configuration
public class JwtConfig {
    @Bean
    @Qualifier("tokenStore")
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //使用命令查看上节中生成的jks中的pubkey内容,并复制到public.pub文件中,粘贴到resource server的classpath中
        Resource resource = new ClassPathResource("public.pub");
        String pubkey = null;
        try {
            pubkey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        converter.setVerifierKey(pubkey);
        //不设置会出现 cant convert jwt to JSON 错误
        converter.setVerifier(new RsaVerifier(pubkey));
        return converter;
    }
}
resource server配置
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    private TokenStore tokenStore;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/**").authenticated();  //所有路径均需要授权
    }
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore);
    }
}
测试controller
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/info")
    @PreAuthorize("hasRole('ADMIN')")  //需要授权并且必须拥有ADMIN角色
    public String userDetail(Authentication authentication) {
        log.info(authentication.getDetails().toString());
        return authentication.getPrincipal().toString();
    }
    
    @RequestMapping("/simple")
    public String hhhhh() {
        return "simple string";
    }
}
使用admin及密码采用password授权方式获取accessToken,header中需要带有基础basic认证,对应auth config中client配置的用户,响应结果中包含了自定义的jwt拓展,同时该拓展项存在于jwt的payload中

使用accessToken访问资源服务器中受保护的应用

使用错误的token访问受保护资源,响应401错误

使用权限不足的(没有admin角色的token访问需要admin权限的资源),响应403

如果需要自定义错误响应内容,可参考
Security OAuth2自定义异常响应










