SpringSecurity自定义登录认证

前言

为啥要写这篇呢?昨天写了个security+jwt做token令牌及鉴权,其中登录认证是用自己的方法做的,只使用了授权校验,并没有用spring-security的登录认证。今天刚好有个水友碰到了登录认证的相关问题,帮忙解决后也在这里记一笔,方便以后回忆!!!

解决思路

  • 自定义一个登录认证处理器
  • 注入到security的登录认证管理器中(可以支持多个)
  • 登录接口中,使用认证管理器进行登录认证(认证时会使用策略模式进行适配)
  • 认证成功后,做一些业务处理(结合原有的token逻辑)

搞起来

1 自定义登录认证处理器

package com.zyu.boot.demo.security.handler;

import com.zyu.boot.demo.entity.User;
import com.zyu.boot.demo.mapper.UserMapper;
import com.zyu.boot.demo.security.entity.JwtUser;
import com.zyu.boot.demo.security.entity.Role;
import com.zyu.boot.demo.utils.pwd.PasswordHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;

/**
 * 自定义登录认证
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
   

    @Autowired
    private UserMapper userMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
   
        String username = authentication.getName();
        String presentedPassword = (String)authentication.getCredentials();
        JwtUser userDeatils = null;
        // 根据用户名获取用户信息
        User user = userMapper.selectByAccount(username);
        String passwordEncrypt = userMapper.selectPasswordByAccount(username);
        if (StringUtils.isEmpty(user)) {
   
            throw 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值