Spring-Boot-Admin-快速集成Security

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/**"
                );
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

二、验证

1、效果如下

在这里插入图片描述

在这里插入图片描述

### 如何在Spring Boot项目中添加和配置`spring-boot-starter-security` #### 添加依赖 为了使Spring Security能够在Spring Boot应用程序中工作,需要向项目的构建文件(Maven的pom.xml或Gradle的build.gradle)中加入`spring-boot-starter-security`依赖。 对于Maven项目,在`<dependencies>`标签内增加如下内容: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 而对于采用Gradle作为构建工具的情况,则应在`dependencies`闭包里加上这行代码[^1]: ```groovy implementation 'org.springframework.boot:spring-boot-starter-security' ``` 一旦完成了上述操作,执行相应的命令刷新项目以下载所需的库文件。此时,Spring Security的基础安全特性已经被激活,并会对所有的HTTP请求实施访问控制[^2]。 #### 默认行为与自定义配置 默认情况下,当引入了`spring-boot-starter-security`之后,框架会自动创建一个用户名为"user"的账户,密码会在应用启动时随机生成并通过日志输出显示出来。如果希望更改这种默认的行为或者进一步调整安全性策略,可以通过实现WebSecurityConfigurerAdapter类来自定义配置逻辑,尽管官方建议直接使用`SecurityFilterChain` bean的方式来进行更灵活的安全设定[^3]。 下面是一个简单的例子展示如何通过Java Config方式覆盖默认设置: ```java import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; public class SecurityConfig { @Bean public UserDetailsService userDetailsService() { var manager = new InMemoryUserDetailsManager(); var encoder = passwordEncoder(); // 创建两个用户:"user"(ROLE_USER), "admin"(ROLE_ADMIN) manager.createUser(User.withUsername("user").password(encoder.encode("password")).roles("USER").build()); manager.createUser(User.withUsername("admin").password(encoder.encode("secret")).roles("ADMIN", "USER").build()); return manager; } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/","/home").permitAll()//允许所有人访问首页和主页 .anyRequest().authenticated();//其余所有URL都需要认证才能访问 http.formLogin(); //启用表单登录,默认页面位于/login http.logout().logoutSuccessUrl("/"); //登出成功后跳转到根目录 return http.build(); } ``` 这段代码片段展示了如何定义内存中的用户详情服务、加密算法以及基本的身份验证流程规则。请注意实际生产环境中应当更加严格地管理凭证存储和服务端点权限分配等问题[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值