springboot整合spring security安全框架-简单验证账号密码
常用于简单的快速配置登录账号密码。例如swagger登录等
1.pom文件引入依赖
<!--spring security 权限框架 配置登录账户密码-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.application配置文件增加账号密码配置
spring.security.user.name=cmw123
spring.security.user.password=123456
3.sping security 安全框架配置类
/**
* 描述:
* sping security 安全框架配置类
* @author 闲走天涯
* @create 2021/8/11 10:37
*/
//1: 加载了WebSecurityConfiguration配置类, 配置安全认证策略。2: 加载了AuthenticationConfiguration, 配置了认证信息。
//@EnableWebSecurity
//开启方法级别的验证:prePostEnabled 、securedEnabled 和 jsr250Enabled
//1.prePostEnabled =true会解锁@PreAuthorize(在方法执行前进行验证,@PreFilter用于集合) 和 @PostAuthorize(在方法执行后进行验证@PostFilter用于集合)
//2.securedEnabled=true @Secured注解是用来定义业务方法的安全配置
//例如 @Secured({"ROLE_user"}),user角色有权限访问
//3.jsr250Enabled=true 开启三个注解
//@DenyAll: 拒绝所有访问
//@RolesAllowed({“USER”, “ADMIN”}): 该方法只要具有"USER", "ADMIN"任意一种权限就可以访问。这里可以省略前缀ROLE_,实际的权限可能是ROLE_ADMIN
//@PermitAll: 允许所有访问
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
// 静态资源和登录页面可以不用认证
http.authorizeRequests()
//不用登录认证的路径规则
.antMatchers("/actuator/**").permitAll()
.antMatchers("/instances/**").permitAll()
.antMatchers("/assets/**").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/jwt/**").permitAll()
.antMatchers("/feign/**").permitAll()
// 其他请求必须认证
.anyRequest().authenticated()
// 自定义登录和退出
.and()
.formLogin()//使用默认的登录界面
//.loginPage("/login")//自定义登录界面
.successHandler(successHandler)//登录成功则重定向
.and()
.logout()
.logoutUrl("/logout")//自定义退出登录连接/接口
// 启用HTTP-Basic, 用于Spring Boot Admin Client注册
.and().httpBasic().and().csrf().disable();
}
}