SpringSecurity基本介绍以及简单入门(内存用户认证)

本文介绍如何在SpringBoot项目中整合SpringSecurity框架,实现基于角色的访问控制。通过自定义配置类,实现用户认证与授权,配置登录页面、权限访问规则及自定义登录、注销流程。

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

    每个web项目中,都会涉及到安全,例如怎样防范跨域攻击,跨站脚本攻击等,现在比较流行的安全框架呢,有spring家族的SpringSecurity,和apache的shiro,每个框架都有自己的优点,今天我们来开始实战SpringSecurity,SpringSecurity主要分两大方面认证和授权,认证呢,就是我是谁,需要用户名和密码登录后,才能使用系统,授权呢就是我能做什么,登录认证完成后,我能访问那些系统的页面等,了解javaweb开发的小伙伴一定知道web的三大组件,Servlet、Filter(拦截器)和Listener(监听器),而SpringSecurity呢,底层实现原理就是使用拦截器链,SpringSecurity拦截器链很强大,有15个之多,主要有下边等等。

  • HttpSessionContextIntegrationFilter
  • LogoutFilter
  • AuthenticationProcessingFilter
  • DefaultLoginPageGeneratingFilter
  • BasicProcessingFilter
  • SecurityContextHolderAwareRequestFilter
  • RememberMeProcessingFilter
  • AnonymousProcessingFilter
  • ExceptionTranslationFilter
  • SessionFixationProtectionFilter
  • FilterSecurityInterceptor
  • UsernamePasswordAuthenticationFilter

 

    SpringSecurity是基于web项目的,我们就使用springboot搭建web项目,整合SpringSecurity,spring官网为我们提供了强大的支持,登录https://start.spring.io/,选择我们需要创建的项目,以及模块,模块呢就包括SpringSecurity,jpa等等,然后呢创建工程,我们就可以使用idea或者eclipse导入工程。

 

    确认pom文件,springsecurity已经被添加

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

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

 

    编写SpringSecurity配置类,开启springsecurity,继承WebSecurityConfigurerAdapter类,重写下边的两个方法

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {}


    protected void configure(HttpSecurity http) throws Exception {}

参数类型是HttpSecurity的configure方法主要是配置认证

参数类型是HttpSecurity的configure方法主要是配置授权

 

    这里把我自己定义的配置文件类,贴给大家,做一个简单的介绍。

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configurable
@EnableWebSecurity // 开启springsecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user")  // 基于内存创建用户名和密码,以及设定权限
                .password("{noop}123") // {noop}
                .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login.html", "/css/**", "/js/**").permitAll().antMatchers("/**")   // 释放不需要拦截的页面及请求
                .hasAnyRole("USER", "ADMIN").anyRequest().authenticated()  // 配置登陆这个系统使用的权限
                .and().formLogin().loginPage("/login.html") // 配置我们自己的登录页面,默认使用的springsecurity的登录页
                .loginProcessingUrl("/login").successForwardUrl("/index")  // 配置登陆成功后跳转的页面
                .failureForwardUrl("/failer.html").permitAll().and().logout().logoutUrl("/logout")
                .logoutSuccessUrl("/login.html").invalidateHttpSession(true).permitAll().and().csrf().disable();
    }

}

    首先,认证呢,没有连接数据库,在内存中自定义一个user的用户,密码是123,这里是简单的入门程序,由于企业级开发用户名和密码都是连接数据库认证,并且密码的保存都是进行加密的,这里是入门程序,我们就先设置个123,springsecurity中,默认密码都是加密的,那怎样将一个字符换作为一个明文密码呢,就是在密码前加上{noop}。

   配置springsecurity后,它会拦截所有的请求,包括静态资源以及登陆页面等,这是我们要使用authorizeRequests方法,来配置我们不需要拦截的静态资源和登录页面,springsecurity配置一个路径下,所有的文件正则匹配使用/**。

    还可以配置登陆系统需要的权限,和我们自定义的登录页面,注销页面,失败页面,默认的都是使用springsecurity为我们提供的页面。

    一个简单的web项目整合springsecurity已经完成,启动我们的Application.java,打开浏览器输入http://localhost:8080后,会进入到springsecurity的登录页,输入user和123后,能正常登陆,怎么样,大家期待的效果实现了吗?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值