Spring Security的使用,如何实现一个简单的登录功能

之前貌似写过一个博客
实现用户登录,这里采取Spring Security再来试试。

首先我们随便写一个controller层的接口如下,假设用户没登录过,会被filter拦截然后跳转去/login界面(框架生成的),成功登陆后会跳会你访问的页面比如下面的/hello:

package org.pp.springsecurity.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class controller {

    @GetMapping("/hello")
    public String hello() {
        return "hello world";
    }

}

正常的登录流程就是用户输入用户名和密码,然后拿去和数据库比对,那我们先来完成一下entity以及mapper等服务的代码:

package org.pp.springsecurity.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;

@Data
@TableName("t_user")
public class TUser implements Serializable {

    private Integer id;

    private String loginAct;

    private String loginPwd;

    private String name;

    private String phone;

    private String email;

    private Integer accountNoExpired;

    private Integer credentialsNoExpired;

    private Integer accountNoLocked;

    private Integer accountEnabled;

    private LocalDateTime createTime;

    private Integer createBy;

    private LocalDateTime editTime;

    private Integer editBy;

    private LocalDateTime lastLoginTime;

}
package org.pp.springsecurity.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.pp.springsecurity.entity.TUser;

/**
 * @author yuuki
 * @description 针对表【t_user(用户表)】的数据库操作Mapper
 * @createDate 2025-06-09 15:31:51
 * @Entity org.pp.springsecurity.entity.TUser
*/
@Mapper
public interface TUserMapper extends BaseMapper<TUser> {

}

spring security里面的UsernamePasswordAuthenticationFilter接收账号和密码,并调用loadUserByUsername(String username)方法,根据用户名去查数据库中对应的用户。在数据库里查到之后,会将这一用户报装为UserDetail对象,返回给Spring Security框架。所以我们需要来实现一下UserDetailsService这个接口里的loadUserByUsername方法:

package org.pp.springsecurity.security;


import org.pp.springsecurity.entity.TUser;
import org.pp.springsecurity.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
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;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private TUserService tUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserService.lambdaQuery()
                .eq(TUser::getLoginAct, username)
                .one();
        if (tUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return User.builder()
                .username(tUser.getLoginAct())
                .password(tUser.getLoginPwd())
                .authorities(AuthorityUtils.NO_AUTHORITIES)
                .build();
    }
}

Spring Security框架接收到这个UserDetails后,会继续在filter里判断用户状态、密码等,都ok了才能登录否则失败。

值得一说的是,我们还要额外配置一个密码加密,这是Spring Security要求的,否则会报错

在这里插入图片描述
只需要额外写歌config就可以:

package org.pp.springsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
public class SecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
    	// BCryptPasswordEncoder是默认推荐的加密方案,是PasswordEncoder接口的实现类
        return new BCryptPasswordEncoder();
    }
}

当然,存到数据库里的也是加密的,你需要注意
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值