SpringSecurity主要流程(一)

本文详细介绍SpringBoot中集成SpringSecurity的过程,包括添加依赖、创建配置类及自定义登录验证操作。通过重写HttpSecurity和AuthenticationManagerBuilder的方法,实现自定义登录页面、处理登录成功与失败、设置请求权限及禁用CSRF。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要是介绍springboot配置springsecurity的大概步骤。

1 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2 新建SecurityConfig类继承自WebSecurityConfigurerAdapter,此类为Spring Security提供的Web应用安全配置的适配器,主要重写两个方法

@Override
protected void configure(HttpSecurity http) throws Exception {
    
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
}

第一个方法常用于http请求的认证授权等配置;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .successHandler(customAuthenticationSucessHandler) // 处理登录成功
                .failureHandler(customAuthenticationFailureHandler) // 处理登录失败
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .anyRequest()
                .authenticated()
                .and().csrf().disable();
    }

第二个方法则是自定义登录验证的操作,比如说根据用户名从数据库中获取到用户数据并和密码进行匹配来判断用户名和密码是否正确的程序,一般都会将这部分程序放到一个继承于UserDetailsService的类中。

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.userDetailsService(new CustomUserDetailsService());
        auth.authenticationProvider(new CustomAuthenticationProvider());
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值