引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置文件:
server:
port: 8100
spring:
application:
name: app-eureka-center
security:
basic:
enable: true #开启基于HTTP basic的认证
user:
name: lucky
password: 666
eureka:
instance:
hostname: 127.0.0.1
client:
service-url:
defaultZone: http://${eureka.instance.hostname}:8100/eureka/
fetch-registry: false
register-with-eureka: false
在eurka服务端添加一个安全认证类:
package com.zpc.springcloud.eureka;
import org.springframework.context.annotation.Configuration;
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.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 高版本springcloud的丢弃了配置:
*
* security:
* basic:
* enabled: true
*
* 所以应该使用以下方式开启
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// Configure HttpSecurity as needed (e.g. enable http basic).
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
http.csrf().disable();
//注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,
// 如果是form方式,不能使用url格式登录
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
client端也需要输入账号密码才能注册:
服务注册到有认证需求的注册中心时,需要设置如下地址:
http://USER:PASSWORD@127.0.0.1:端口号/eureka/
###服务注册到eureka注册中心的地址
eureka:
client:
service-url:
defaultZone: http://zpc:123456@127.0.0.1:8100/eureka