首页 > 其他分享 >springboot--登录

springboot--登录

时间:2024-03-13 14:56:47浏览次数:26  
标签:return springboot 登录 -- token static import public String

 登录

1.根据用户名查询用户

2.判断用户是否存在

3.判断密码是否正确。

(1) password是密文

Md5Util.getMD5String(password).equals(loginUser.getPassword())

(2)把token存储到redis中

 

controller : UserController

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        //判断该用户是否存在
        if (loginUser == null) {
            return Result.error("用户名错误");
        }

        //判断密码是否正确  loginUser对象中的password是密文
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
}

 Service:UserService

public interface UserService {
    //根据用户名查询用户
    User findByUserName(String username);
}

Service:UserServiceImpl

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }
}

 

interceptors:LongiInterceptor

package com.example.interceptors;

import com.example.pojo.Result;
import com.example.utils.JwtUtil;
import com.example.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken==null){
                //token已经失效了
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);

            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            //http响应状态码为401
            response.setStatus(401);
            //不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}

 

utils : JwtUtils

package com.example.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "itheima";
    
    //接收业务数据,生成token并返回
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 ))
                .sign(Algorithm.HMAC256(KEY));
    }

    //接收token,验证token,并返回业务数据
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }

}

 

utils:Md5Utils

package com.example.utils;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    /**
     * 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
     */
    protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    protected static MessageDigest messagedigest = null;

    static {
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException nsaex) {
            System.err.println(Md5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");
            nsaex.printStackTrace();
        }
    }

    /**
     * 生成字符串的md5校验值
     *
     * @param s
     * @return
     */
    public static String getMD5String(String s) {
        return getMD5String(s.getBytes());
    }

    /**
     * 判断字符串的md5校验码是否与一个已知的md5码相匹配
     *
     * @param password  要校验的字符串
     * @param md5PwdStr 已知的md5校验码
     * @return
     */
    public static boolean checkPassword(String password, String md5PwdStr) {
        String s = getMD5String(password);
        return s.equals(md5PwdStr);
    }


    public static String getMD5String(byte[] bytes) {
        messagedigest.update(bytes);
        return bufferToHex(messagedigest.digest());
    }

    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>>
        // 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同
        char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

}

 

标签:return,springboot,登录,--,token,static,import,public,String
From: https://www.cnblogs.com/xmz88/p/18062870

相关文章

  • vue3 循环引用的解决办法问题,Cannot access ‘xxxx‘ before initialization
    ReferenceError:Cannotaccess‘xxxx‘beforeinitialization ,原因之前已经初始化过,但页面组件嵌套,需要被重复引用。1、开启异步引用来解决components:{DeviceManage:defineAsyncComponent(()=>import('@/views/operation/mechanism/index.vue'))}2、用ifrme来......
  • Spring学习
    目录Spring13、HelloSpring4、IOC创建对象方式5、Spring配置Spring2Spring3单例模式(面试)Spring4使用Java来配置beanpojo类包config包1+(1+3)@Component+(@Configuration+@Bean)1+(2+3)@Component+(@ComponentScan+@bean)1+(3)@Component+(@bean)(2+3)(@ComponentScan+@bean)(1+3)(@Configur......
  • 5-adding_general_force
    D’ALEMBERT’SPRINCIPLEForparticlesD’Alembert’sprincipleimpliesthat,ifwehaveasetofforcesactingonanobject,wecanreplaceallthoseforceswithasingleforce,whichiscalculatedby\[f=\sum\limits_{i}f_{i}\]Inotherwords,wes......
  • 6-springs_and_springlike_things
    Oneofthemostusefulforceswecancreateforourengineisaspringforce.Althoughspringshaveanobvioususeindrivinggames(forsimulatingthesuspensionofacar),theycomeintotheirowninrepresentingsoftordeformableobjectsofmanykinds......
  • Spring Boot 2.x中配置文件加载顺序分析
    一般springboot2.x的配置有多种方式,如resources文件夹中可以定义bootstrap.yml(或bootstrap.properties)、application.yml(或application.properties)、配置中心(如nacos),那么它们加载顺序是怎样的,如何使用?bootstrap.yml:首先加载bootstrap.yml(或bootstrap.properties)。这个......
  • gradle
    Maven和Gradle的区别二者都是java语言主流的构建工具,提供默认的软件包结构,生命周期管理以及依赖管理;Gradle相对于Maven来说减少了冗长的代码,引入依赖只需要将它的groupId,artifactId和version三者用:连接起来;并调用compile函数就可以啦Maven的pom文件:<dependencies>......
  • 7-hard_constraints
    Initiallywe’lllookatthemostcommonhardconstraint—collisionsandcontactbetweenobjects.Alltheengineswe’rebuildinginthisbooktreathardconstraintsdifferentfromforcegenerators.Attheendofthebook,we’lllookbrieflyatalternativeapp......
  • 《行业指标体系白皮书》重磅发布,剖析指标建设困境,构建前瞻性的指标体系(附下载)
    正处于企业指标建设过程中的你,是否经常遇到这样的问题:•各个部门独立建设信息系统,由此产生的指标定义和计算方式各异,导致管理层无法快速准确地掌握整体业务运行状况•缺乏对指标的统一管理和规范,产生重复的指标计算工作,导致数据计算资源被过度消耗,增加运维成本和数据处理压力......
  • 【算法】【线性表】【数组】从中序与后序遍历序列构造二叉树
    1 题目给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。示例1:输入:inorder=[9,3,15,20,7],postorder=[9,15,7,20,3]输出:[3,9,20,null,null,15,7]示例2:输入:inor......
  • AIOps 智能运维:有没有比专家经验更优雅的错/慢调用分析工具?
    作者:图杨工程师小A刚刚接手他们公司最核心的电商系统的运维工作,小A发现,在生产环境中,系统明明运行得非常稳定,但是总会出现一些“诡异”的情况。比如:偶尔会一些错误调用,但是,还没来得及修,系统又莫名奇妙地恢复正常。应用的平均响应时间很短,但是总会有一些响应时间非常长的离......