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;
    }
}
相关推荐
ajsbxi1 分钟前
苍穹外卖学习记录
java·笔记·后端·学习·nginx·spring·servlet
StayInLove20 分钟前
G1垃圾回收器日志详解
java·开发语言
对许24 分钟前
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder“
java·log4j
鹿屿二向箔25 分钟前
基于SSM(Spring + Spring MVC + MyBatis)框架的咖啡馆管理系统
spring·mvc·mybatis
无尽的大道28 分钟前
Java字符串深度解析:String的实现、常量池与性能优化
java·开发语言·性能优化
小鑫记得努力37 分钟前
Java类和对象(下篇)
java
binishuaio41 分钟前
Java 第11天 (git版本控制器基础用法)
java·开发语言·git
zz.YE43 分钟前
【Java SE】StringBuffer
java·开发语言
老友@43 分钟前
aspose如何获取PPT放映页“切换”的“持续时间”值
java·powerpoint·aspose
wrx繁星点点1 小时前
状态模式(State Pattern)详解
java·开发语言·ui·设计模式·状态模式