springsecurity自定义数据库模型的认证与授权

部分控制器代码参考Spring Security默认数据库模型的认证于授权

1. 引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--        其他spring-security依赖-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.7.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.7.3</version>
        </dependency>

        <!-- 数据库依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.23</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
            <scope>test</scope>
        </dependency>

2. 数据库准备


create table users(
	id bigint(20) not null auto_increment,
	username varchar(50) not null,
	password varchar(60),
	enable tinyint(4) not null default 1 comment '用户是否可用',
	roles text character set utf8 comment '用户角色,多个角色之间用逗号隔开',
	primary key(id),
	key username (username)
);

insert into users(username, password, roles) values ('admin', '123', 'ROLE_ADMIN;ROLE_USER');
insert into users(username, password, roles) values ('user', '123', 'ROLE_USER');

用户信息和角色放在同一张表中,roles字段设定为text,多个角色之间通过逗号隔开,也可用通过分号等其他字符隔开。

  • 在入口类MapperScan指定mybatis要扫描的映射文件目录
    在这里插入图片描述

3. 实现UserDetails

3.1 实现xxx.xxx.config.WebSecurityConfig.java

package com.lzd.springsecuritydemo.config;

import jdk.nashorn.internal.runtime.logging.Logger;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author li
 * @date 2022年10月03日 16:12
 */

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                // 只对ADMIN角色放行
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .csrf().disable();
    }
}

3.2 在pojo包下创建User.java类,继承UserDetails

package com.lzd.springsecuritydemo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

/**
 * @author li
 * @date 2022年10月04日 16:53
 * @Description
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements UserDetails {
    private Long id;

    private String username;

    private String password;

    private String roles;

    private boolean enable;

    private List<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enable;
    }
}

实现UserDetails定义的几个方法:

  • isAccountNonExpired、isAccountNonLocked、isCredentialsNonExpired暂时用不到,统一返回true,否则会账号异常。
  • isEnabled对映enable字段。
  • getAuthorities方法本身对应的是roles字段

3.3 在mapper下实现UserMapper接口

package com.lzd.springsecuritydemo.mapper;

import com.lzd.springsecuritydemo.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

/**
 * @author: li
 * @date: 2022年10月04日 17:03
 * @description: TODO
 */

@Component
public interface UserMapper {
    @Select("select * from users where username=#{username}")
    User findByUserName(@Param("username") String username);
}

3.4 在service下编写UserDetailsService

package com.lzd.springsecuritydemo.service;

import com.lzd.springsecuritydemo.mapper.UserMapper;
import com.lzd.springsecuritydemo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: li
 * @date: 2022年10月04日 17:06
 * @description: TODO
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询用户
        User user = userMapper.findByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // AuthorityUtils.commaSeparatedStringToAuthorityList是spring security提供的 默认根据
        // 逗号分割权限字符集字符串切割成可用权限对象列表
        //user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));

        // 使用自定义的分隔方法
        user.setAuthorities(generateAuthorities(user.getRoles()));
        return user;
    }

    /**
     * 自行实现通过分号隔开权限集字符串
     * @param roles
     * @return
     */
    private List<GrantedAuthority> generateAuthorities(String roles) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (roles != null && !"".equals(roles)) {
            String[] roleArray = roles.split(";");
            for (String role : roleArray) {
                // SimpleGrantedAuthority是GrantedAuthority是一个实现类
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        return authorities;
    }
}

4.启动测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值