springboot整合spring security

本文介绍如何在SpringBoot项目中集成SpringSecurity,包括添加依赖、创建配置类、自定义登录页面及权限设置等。

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

个人博客地址:http://alexaccele.github.io/

springboot 要想使用spring security的模块需要导入相应的依赖

在pom文件中添加一下代码

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

然后编写一个简单的配置类 SecurityConfiger 这个配置类需要继承  WebSecurityConfigurerAdapter 这个抽象类

/*安全配置类*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)// 启用方法安全设置
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}

并标上@EnableWebSecurity注解,打开这个注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({WebSecurityConfiguration.class, SpringWebMvcImportSelector.class})
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
    boolean debug() default false;
}

可以看到其中是包含了@Configuration注解的,表示这是一个配置类

 

然后我们需要重载configure方法以达到我们想要的结果

方法描述
configure(WebSecurity webSecurity)通过重载,配置SpringSecurity的Filter链
configure(HttpSecurity http)通过重载,配置如何通过拦截器保护请求
configure(AuthenticationManagerBuilder auth)通过重载,配置userdetail服务

以上方法不用全部重载,只需要根据具体需求进行重载,下面给出重载例子:


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/css/**","/fonts/**","/js/**","/index").permitAll()//对静态文件允许访问
                .antMatchers("/admins/**").hasRole("ADMIN")//有相应角色才能访问
                .and()
                .formLogin()//基于form表单登录验证 前往/login页面
                .loginPage("/login").failureUrl("/login-error")//自定义登录界面和失败界面
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//认证信息存储于内存中
            .withUser("root").password("123456").roles("ADMIN");
    }

以上就是springboot整合spring security的一个简单配置类,其中配置了对静态文件的访问权限,对一些特定页面的权限设置,以及对登录验证,登录页面,登录失败的配置;以及适用于生产环境的配置,将User信息保存于内存中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值