为spring-boot-admin配置spring security(用于控制访问)

来源:互联网 发布:加拿大 留学 专业 知乎 编辑:程序博客网 时间:2024/06/05 17:10
在spring-boot-admin(SBA)监控端,为了防止没授权的访问,一般需要做访问控制。只需简单几步,就可以配置spring security来控制对SBA的访问。
1、引入依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>

2、配置:
@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Value("${spring.profiles}")private String env;@Overrideprotected void configure(HttpSecurity http) throws Exception {/*if("dev".equals(env)){ //如果需要在开发服中免登录http.authorizeRequests().antMatchers("*//**","*//**//*filters").permitAll();http.csrf().disable();http.httpBasic();return;}*/http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll().and().logout().logoutUrl("/logout").and().authorizeRequests().antMatchers("/login.html", "/**/*.css", "/img/**", "/api/**") //放开"/api/**":为了给被监控端免登录注册.permitAll().and().authorizeRequests().antMatchers("/**").authenticated();http.csrf().disable();http.httpBasic();}/*@Autowired //也可以在application.yml文件中配置登录账号密码:security.user.name/passwordpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("svcAdmin").password("pw").roles("USER");}*/}

application.yml:
security:  user:    name: sba    password: passwd

3、登录页面:
<html><head><meta charset="UTF-8"><title>sba登录</title><style>html,body{text-align:center;margin:0px auto;}form, div{margin: 5px;}</style></head><body><br/><form action="/svc-monitor/login" method="post"><div>请登录:</div><div><label><input type="text" name="username"  placeholder="用户名"/> </label></div><div><label><input type="password" name="password"  placeholder="密码"/> </label></div><div><input type="submit" value="登录"/></div></form></body></html>



0 0