2020/09/02更新
Github開源腳手架运准,在網(wǎng)關(guān)處統(tǒng)一進(jìn)行鑒權(quán)憨降,授權(quán)服務(wù)器可單獨(dú)部署或者走網(wǎng)關(guān),具體見 https://github.com/beifei1/fire-cloud
本文基于Spring Cloud Security OAuth2實(shí)現(xiàn)微服務(wù)應(yīng)用的保護(hù),具體概念理解可參考
深入理解Spring Cloud Security OAuth2及JWT
應(yīng)用版本
Spring Boot: 2.1.1.RELEASE
Spring Cloud:Greenwich.SR2
應(yīng)用實(shí)現(xiàn)
Eureka Server服務(wù)
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>
定義應(yīng)用配置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 #是否向注冊自己,該應(yīng)用為服務(wù)治理吏奸,不注冊自己
fetch-registry: false #服務(wù)治理應(yīng)用,不拉取注冊列表
server:
enable-self-preservation: false #禁用自我保護(hù)
eviction-interval-timer-in-ms: 5000 #剔除無用節(jié)點(diǎn)的間隔時(shí)間
定義啟動(dòng)類
@EnableEurekaServer //開啟eureka支持
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
Auth Server服務(wù)
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) //啟用方法級權(quán)限控制
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)) //切入點(diǎn)陶耍,可自定義未授權(quán)響應(yīng)體
.and()
.authorizeRequests()
.antMatchers("/**").authenticated() //所有路徑均啟用安全
.and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在內(nèi)存中創(chuàng)建兩個(gè)用戶便于測試奋蔚,實(shí)際應(yīng)用可用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 //開啟授權(quán)服務(wù)器支持
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager; //注入Security配置中的manager
@Autowired
private JwtTokenEnhancer jwtTokenEnhancer; //自定義JWT內(nèi)容(jwt增強(qiáng)器)
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//定義兩個(gè)client,授權(quán)范圍為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增強(qiáng)鏈
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> list = new ArrayList<>();
list.add(jwtTokenEnhancer); //注入定義好的自定義token增強(qiáng)
list.add(jwtAccessTokenConverter());
tokenEnhancerChain.setTokenEnhancers(list);
return tokenEnhancerChain;
}
}
定義JWT增強(qiáng)烈钞,可自由定義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;
}
}
關(guān)于JKS文件及pubkey相關(guān)使用可參考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/
啟動(dòng)類
@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();
//使用命令查看上節(jié)中生成的jks中的pubkey內(nèi)容,并復(fù)制到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);
//不設(shè)置會(huì)出現(xiàn) cant convert jwt to JSON 錯(cuò)誤
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(); //所有路徑均需要授權(quán)
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore);
}
}
測試controller
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/info")
@PreAuthorize("hasRole('ADMIN')") //需要授權(quán)并且必須擁有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授權(quán)方式獲取accessToken馒过,header中需要帶有基礎(chǔ)basic認(rèn)證,對應(yīng)auth config中client配置的用戶仪媒,響應(yīng)結(jié)果中包含了自定義的jwt拓展沉桌,同時(shí)該拓展項(xiàng)存在于jwt的payload中
使用accessToken訪問資源服務(wù)器中受保護(hù)的應(yīng)用
使用錯(cuò)誤的token訪問受保護(hù)資源谢鹊,響應(yīng)401錯(cuò)誤
使用權(quán)限不足的(沒有admin角色的token訪問需要admin權(quán)限的資源)算吩,響應(yīng)403
如果需要自定義錯(cuò)誤響應(yīng)內(nèi)容,可參考
Security OAuth2自定義異常響應(yīng)