學習使用Spring Cloud 微服務間的調用都是RestFul風格,如何保證調用之間的安全性,這是一個很重要的問題。java
經過查閱資料http://wiselyman.iteye.com/blog/2379419 查看了github上提供的例子https://github.com/wiselyman/uaa-zuulgit
1.引入github
<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>
2.添加配置類web
package com.rraj.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; /** * Created by hqm */ @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() .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } }
3啓動的Application中添加註解 spring
@EnableGlobalMethodSecurity(prePostEnabled = true)
4.application.properties中添加
#安全認證 security.oauth2.resource.id=feign-consumer security.oauth2.resource.user-info-uri=http://localhost:8702 security.oauth2.resource.prefer-token-info=false
以上幾步能夠完成服務之間調用的安全性,歡迎指正錯誤的問題和評論安全