代码地址:
https://gitee.com/DanShenGuiZu/learnDemo/tree/master/springboot_admin_learn
一、介绍
1、 spring-boot-admin-server-ui提供登录页面和注销按钮。结合 Spring Security 实现需要用户名和密码登录的安全认证。
二、服务器安全(admin-server,结合eureka)配置
2.1、核心配置和代码
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
application.yml
spring:
security:
user:
name: admin
password: admin
eureka:
# 配置 spring security 的用户名和密码,这时需要在服务注册时带上 metadata-map 的信息。
metadata-map:
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
SecurityConfig
package fei.zhou.adminserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler
= new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl("/");
http.authorizeRequests()
//授予公众对所有静态资产和登录页面的访问权限。
.antMatchers("/assets/**").permitAll()
//登陆页面排除
.antMatchers("/login").permitAll()
// 其他所有请求都必须经过验证。
.anyRequest().authenticated().and()
.formLogin().loginPage("/login")
.successHandler(successHandler).and()
.logout().logoutUrl("/logout").and()
.httpBasic().and()
.csrf()
// 使用Cookies启用CSRF保护
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
//对执行器端点禁用CSRF-Protection。
.ignoringAntMatchers(
"/instances",
"/actuator/**"
);
}
}