天天看点

springsecurity自定义数据库模型的认证与授权1. 引入依赖2. 数据库准备3. 实现UserDetails4.启动测试

部分控制器代码参考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要扫描的映射文件目录
    springsecurity自定义数据库模型的认证与授权1. 引入依赖2. 数据库准备3. 实现UserDetails4.启动测试

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.启动测试