Spring Boot Admin系列(3)-Spring Boot Admin添加登录认证

灰太狼 2023-10-10 11:43 69阅读 0赞

前言

在搭建成功并集成nacos后,未登录用户也可访问首页,然后敏感信息太多,肯定得需要进程登录认证,此处只是一个演示,实际需要整合自己项目得权限认证

步骤

  1. amdin服务端项目添加pom


    org.springframework.boot
    spring-boot-starter-security
  2. amdin项目添加security配置类

    package org.pearl.devops.admin.config;

    import de.codecentric.boot.admin.server.config.AdminServerProperties;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
    import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

  1. /**
  2. * Created by TD on 2020/10/26
  3. */
  4. @EnableWebSecurity
  5. @Configuration(proxyBeanMethods = false)
  6. public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
  7. private final String adminContextPath;
  8. public AdminSecurityConfig(AdminServerProperties adminServerProperties) {
  9. this.adminContextPath = adminServerProperties.getContextPath();
  10. }
  11. @Override
  12. protected void configure(HttpSecurity http) throws Exception {
  13. // @formatter:off
  14. SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
  15. successHandler.setTargetUrlParameter("redirectTo");
  16. successHandler.setDefaultTargetUrl(adminContextPath + "/");
  17. http.authorizeRequests()
  18. .antMatchers(adminContextPath + "/assets/**").permitAll()
  19. .antMatchers(adminContextPath + "/login").permitAll()
  20. .antMatchers(adminContextPath + "/instances/**").permitAll()
  21. .anyRequest().authenticated()
  22. .and()
  23. .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
  24. .logout().logoutUrl(adminContextPath + "/logout").and()
  25. .httpBasic().and()
  26. .csrf()
  27. .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
  28. .ignoringAntMatchers(
  29. adminContextPath + "/instances",
  30. adminContextPath + "/actuator/**"
  31. );
  32. // @formatter:on
  33. }
  34. @Override
  35. public void configure(WebSecurity web) {
  36. web.ignoring().antMatchers("/actuator/**");
  37. }
  38. }
  1. yml配置登录用户

    spring:
    application:

    1. name: pearl-admin

    cloud:

    1. nacos:
    2. discovery:
    3. server-addr: 127.0.0.1:8848 # nacos注册地址

    security:

    1. user:
    2. name: admin
    3. password: admin
  2. 跳转首页,使用admin/admin登录
    在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,69人围观)

还没有评论,来说两句吧...

相关阅读