SpringSecurity专题从入门到源码剖析(四) 核心配置

本文主要介绍了SpringSecurity的核心配置类WebSecurityConfigurerAdapter,详细阐述了它如何为应用提供安全功能,包括路径访问控制、登录注销配置、内存中用户认证以及CSRF防护。此外,还提及了在SpringBoot中集成JSP的简要说明和一个简单的SpringSecurity配置案例。
摘要由CSDN通过智能技术生成

视频教程地址:  https://www.bilibili.com/video/BV1kT4y1F7Tc

代码地址:     https://gitee.com/crazyliyang/video-teaching

1. 核心配置类 WebSecurityConfigurerAdapter

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)  // 注意
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()   // 配置请求地址的权限
                .antMatchers("/demo").permitAll() // 所有用户可访问,无需登录认证, @PermitAll 功能一样
                .antMatchers("/config/admin").hasRole("ADMIN")  // 需要 ADMIN 角色
                .antMatchers("/config/normal").access("hasRole('ROLE_NORMAL')") // 需要 NORMAL 角色。
                .anyRequest().authenticated()  // 任何请求,访问的用户都需要经过认证
                .and()
                .formLogin()             // 设置 Form 表单登陆
//              .loginPage("/login")     // 登陆 URL 该地址这里可以自定义配置
                .permitAll()
                .and()
                .logout()                // 配置退出相关
//              .logoutUrl("/logout")    // 退出 URL 该地址这里可以自定义配置
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.
                inMemoryAuthentication()// 使用内存中的 InMemoryUserDetailsManager
                .passwordEncoder(NoOpPasswordEncoder.getInstance())// 不使用 PasswordEncoder 密码编码器
                .withUser("admin").password("admin").roles("ADMIN") // 配置 admin 用户
                .and().withUser("user").password("user").roles("NORMAL");// 配置 normal 用户
    }

}

如上的注释已经解释和常规的配置什么含义, 下边是总结:

当配置了上述的 WebSecurityConfigurerAdapter Java的配置类之后,我们的应用便具备了如下的功能:

除了“/”,”/home”(首页),”/login”(登录),”/logout”(注销)之外,其他路径都需要认证。

指定“/login”该路径为登录页面,当未认证的用户尝试访问任何受保护的资源时,都会跳转到“/login”。

默认指定“/logout”为注销页面

配置一个内存中的用户认证器,使用admin/admin作为用户名和密码,具有USER角色

防止CSRF攻击

 

 

还可以继续配置, 如下:

 

@Configuration
public class CustomWe
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值