ITPub博客

首页 > 架构设计 > 软件结构 > (65)java Spring Cloud企业快速开发架构之使用Spring Security给Spring Boot

(65)java Spring Cloud企业快速开发架构之使用Spring Security给Spring Boot

原创 软件结构 作者:JIAN2 时间:2021-10-08 15:42:37 0 删除 编辑

 监控类的数据 Web 管理端最好不要设置成直接通过输入访问地址就可以访问,必须得进行用户认证才行,以保证数据的安全性。Spring Boot Admin 开启认证也可以借助于 spring-boot-starter-security。  需要框架源码的朋友可以看我个人简介联系我

  

加入依赖,代码如下所示。

<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


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70006413/viewspace-2794925/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
华为资深架构师,曾参与华为数据中心迁移解决方案!有需要了解分布式微服务电商源码的朋友可以+我 v ❤: haiwabbc2 , 10余年互联网研发行业经验!博客里面是个人的一点技术总结,希望能够帮助到更多的IT朋友成长!

注册时间:2021-09-06

  • 博文量
    1404
  • 访问量
    622748