首页 > Spring Cloud
阅读:247
使用Spring Security给Spring Boot Admin开启认证
监控类的数据 Web 管理端最好不要设置成直接通过输入访问地址就可以访问,必须得进行用户认证才行,以保证数据的安全性。Spring Boot Admin 开启认证也可以借助于 spring-boot-starter-security。
加入依赖,代码如下所示。
这里需要注意的是,如果 Spring Boot Admin 服务开启了认证,监控的服务中也需要配置对应的用户名和密码,否则会注册失败。
在 spring-boot-admin-client 属性文件中加上用户认证信息:
加入依赖,代码如下所示。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
spring.security.user.name=zhangsan
spring.security.user.password=123456
@Configuration
public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
    private final String adminContextPath;
    public SecurityPermitAllConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        // 静态资源和登录页面可以不用认证
        http.authorizeRequests().antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                // 其他请求必须认证
                .anyRequest().authenticated()
                // 自定义登录和退出
                .and().formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and().logout()
                .logoutUrl(adminContextPath + "/logout")
                // 启用HTTP-Basic, 用于Spring Boot Admin Client注册
                .and().httpBasic().and().csrf().disable();
    }
}
重启程序,然后就会发现需要输入用户名和密码才能访问 Spring Boot Admin 的 Web 管理端,如下图所示。
这里需要注意的是,如果 Spring Boot Admin 服务开启了认证,监控的服务中也需要配置对应的用户名和密码,否则会注册失败。
在 spring-boot-admin-client 属性文件中加上用户认证信息:
spring.boot.admin.client.username=zhangsan
spring.boot.admin.client.password=123456
所有教程
- socket
 - Python基础教程
 - C#教程
 - MySQL函数
 - MySQL
 - C语言入门
 - C语言专题
 - C语言编译器
 - C语言编程实例
 - GCC编译器
 - 数据结构
 - C语言项目案例
 - C++教程
 - OpenCV
 - Qt教程
 - Unity 3D教程
 - UE4
 - STL
 - Redis
 - Android教程
 - JavaScript
 - PHP
 - Mybatis
 - Spring Cloud
 - Maven
 - vi命令
 - Spring Boot
 - Spring MVC
 - Hibernate
 - Linux
 - Linux命令
 - Shell脚本
 - Java教程
 - 设计模式
 - Spring
 - Servlet
 - Struts2
 - Java Swing
 - JSP教程
 - CSS教程
 - TensorFlow
 - 区块链
 - Go语言教程
 - Docker
 - 编程笔记
 - 资源下载
 - 关于我们
 - 汇编语言
 - 大数据
 - 云计算
 - VIP视频