SpringSecurity 工作流程图及(简易)登录测试

本文介绍了SpringSecurity在SpringBoot项目中的配置过程,包括pom.xml的依赖配置、application.yml的数据库连接和Mybatis配置,以及核心的SpringSecurity配置类。在配置类中,自定义了用户服务实现,并通过WebSecurityConfigurerAdapter进行安全规则设置,如放行静态资源、登录登出授权。同时,展示了MyUser实体类和相关Mapper接口,用于用户权限管理。

SpringSecurity 工作流程图及(简易)登录测试

SpringSecurity 的大致工作流程图

在这里插入图片描述

pom.xml Maven依赖配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.chen</groupId>
    <artifactId>sec_demo1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sec_demo1</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.xmlunit</groupId>
            <artifactId>xmlunit-core</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.1</version>
            </plugin>
        </plugins>
    </build>

</project>

application.yml 配置文件

spring:
  # 配置数据库连接池
  datasource:
    username: root
    password: 123456
    # serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/dbams?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.cj.jdbc.Driver

# 配置 mybatis
mybatis:
  type-aliases-package: com.chen.entity
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

SpringSecurity 配置类,继承 WebSecurityConfigurerAdapter

@Configuration  //--> IOC 容器
@EnableWebSecurity // 启用Spring Security的Web安全支持  @import相关组件注册
public class ChenSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserServiceImpl myUserService;
    /**
     * 提供 用户名 密码 角色 权限
     *
     * 将用户设置在内存中
     *
     * Authen 认证
     * Manager 管理器
     * Builder 构造者
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void config(AuthenticationManagerBuilder auth) throws Exception {
        // 在内存中配置用户,配置多个用户调用`and()`方法
        /*auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder()) // 指定加密方式
                .withUser("admin").password(passwordEncoder().encode("123456")).roles("ADMIN")
                .and()
                .withUser("test").password(passwordEncoder().encode("123456")).roles("USER");*/
        auth.userDetailsService(myUserService);
    }

    /**
     * 放行静态资源
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers();
    }

    /**
     * 授权 登录 登出
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/resources/**", "/signup", "/about").permitAll()
                /*.antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")*/
                .anyRequest().authenticated()
                .and()
                .formLogin()
                /*.usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/login")*/
                .failureForwardUrl("/error1")
                .successForwardUrl("/hello")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/index")
                .permitAll()
                .and()
                .httpBasic()
                .disable();
    }

    /**
     * 加密
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        // BCryptPasswordEncoder:Spring Security 提供的加密工具,可快速实现加密加盐
        return new BCryptPasswordEncoder();
    }
}

MyUser 实体类

package com.chen.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

public class MyUser implements UserDetails { // 重点是实现 UserDetails 接口,这是SpringSecurity自带的接口
    // 和数据库对应的字段名和属性
    private Integer sysid;
    private String account;
    private String password;
    private Integer rid;
    private Integer userid;
    private Integer closed;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() { // 获取用户权限,本质上是用户的角色信息
        return null;
    }

    @Override
    public String getPassword() { // 获取密码
        return this.password;
    }

    @Override
    public String getUsername() { //获取用户名
        return this.account;
    }

    @Override
    public boolean isAccountNonExpired() { // 账户是否过期
        return true;
    }

    @Override
    public boolean isAccountNonLocked() { // 账户是否被锁定
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() { //密码是否过期
        return true;
    }

    @Override
    public boolean isEnabled() { // 账户是否可用
        return this.closed==0;
    }

    public Integer getSysid() {
        return sysid;
    }

    public void setSysid(Integer sysid) {
        this.sysid = sysid;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getRid() {
        return rid;
    }

    public void setRid(Integer rid) {
        this.rid = rid;
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public Integer getClosed() {
        return closed;
    }

    public void setClosed(Integer closed) {
        this.closed = closed;
    }

    @Override
    public String toString() {
        return "MyUser{" +
                "sysid=" + sysid +
                ", account='" + account + '\'' +
                ", password='" + password + '\'' +
                ", rid=" + rid +
                ", userid=" + userid +
                ", closed=" + closed +
                '}';
    }
}

MyUserMapper 接口类

@Mapper
@Repository
public interface MyUserMapper {
    public MyUser findStudentByAccount(String account);
}

MyUserService 接口类

public interface MyUserService {
    public MyUser findStudentByAccount(String account);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值