Spring Security 6.1.2 认证 配置

UserDetail

java 复制代码
package com.mqb.springsecurity.domain.entities;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.experimental.FieldNameConstants;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户
 *
 * @author qingbo.ma
 * @since 2023-08-07
 */
@Getter
@Setter
@Accessors(chain = true)
@TableName("user")
@FieldNameConstants
public class User implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    /**
     * 主键ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 用户名
     */
    @TableField("username")
    private String username;

    /**
     * 密码
     */
    @TableField("`password`")
    private String password;

    /**
     * 姓名
     */
    @TableField("full_name")
    private String fullName;

    /**
     * 性别
     */
    @TableField("gender")
    private String gender;

    /**
     * 部门ID
     */
    @TableField("dept_id")
    private Long deptId;

    /**
     * 邮箱地址
     */
    @TableField("email_address")
    private String emailAddress;

    /**
     * 手机号码
     */
    @TableField("phone_number")
    private String phoneNumber;

    /**
     * 头像链接
     */
    @TableField("profile_picture")
    private String profilePicture;

    /**
     * 创建时间
     */
    @TableField("create_time")
    private Date createTime;

    /**
     * 修改时间
     */
    @TableField("update_time")
    private Date updateTime;


    public static final String ID = "id";

    public static final String USERNAME = "username";

    public static final String PASSWORD = "password";

    public static final String FULL_NAME = "full_name";

    public static final String GENDER = "gender";

    public static final String DEPT_ID = "dept_id";

    public static final String EMAIL_ADDRESS = "email_address";

    public static final String PHONE_NUMBER = "phone_number";

    public static final String PROFILE_PICTURE = "profile_picture";

    public static final String CREATE_TIME = "create_time";

    public static final String UPDATE_TIME = "update_time";

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

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

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

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

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

UserDetailsService

我实现了UserDetailsService (loadUserByUsername通过用户名查用户) 以及UserDetailsPasswordService(updatePassword)更改密码

java 复制代码
package com.mqb.springsecurity.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mqb.springsecurity.domain.entities.User;
import com.mqb.springsecurity.infra.mapper.UserMapper;
import com.mqb.springsecurity.app.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author qingbo.ma
 * @since 2023-08-07
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService, UserDetailsPasswordService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq(User.Fields.username, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户名未找到");
        }
        return user;
    }

    /**
     * 修改密码
     * @param user
     * @param newPassword
     * @return
     */

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        User userDb = userMapper.selectOne(new QueryWrapper<User>().eq(User.Fields.username, user.getUsername()));
        userDb.setPassword(newPassword);
        userMapper.updateById(userDb);
        return userDb;
    }
}

SecurityConfig

java 复制代码
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    private final AuthenticationConfiguration authenticationConfiguration;
    private final UserDetailsService userDetailService;
    private final DataSource datasource;


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();

    }
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailService);
        provider.setHideUserNotFoundExceptions(false);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }
}
相关推荐
路在脚下@6 分钟前
spring boot的配置文件属性注入到类的静态属性
java·spring boot·sql
啦啦右一8 分钟前
Spring Boot | (一)Spring开发环境构建
spring boot·后端·spring
森屿Serien9 分钟前
Spring Boot常用注解
java·spring boot·后端
苹果醋31 小时前
React源码02 - 基础知识 React API 一览
java·运维·spring boot·mysql·nginx
Hello.Reader2 小时前
深入解析 Apache APISIX
java·apache
菠萝蚊鸭2 小时前
Dhatim FastExcel 读写 Excel 文件
java·excel·fastexcel
旭东怪2 小时前
EasyPoi 使用$fe:模板语法生成Word动态行
java·前端·word
007php0072 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
∝请叫*我简单先生2 小时前
java如何使用poi-tl在word模板里渲染多张图片
java·后端·poi-tl
ssr——ssss2 小时前
SSM-期末项目 - 基于SSM的宠物信息管理系统
java·ssm