Spring-Boot-Admin-快速集成Security
一、介绍
1、 spring-boot-admin-server-ui 提供登录页面和注销按钮。结合 Spring Security 实现需要用户名和密码
登录的安全认证。
二、服务器安全(admin-server,结合eureka)配置
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 yuanlx.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;
/**
* @Description 请描述下该类是做什么的
* @Author <a href="mailto:yuanlx@smartdot.com.cn">袁凌霄</a>
* @Date 2021/5/31 14:30
* @Verson 1.0
**/
@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/**"
);
}
}