使用SpringBoot重构Django博客(二)基于JWT的用户认证api

JWT暂且不表,主要讲讲如何获取Django的用户表和验证密码,由于Django的用户密码都是通过pbkdf2_sha256加密后存入数据库的,那么需要用java重写这加密过程然后进行比对。

Pbkdf2Sha256.java

package com.arithmeticjia.zuul.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Random;

/**
 * @author ArithmeticJia
 * @version 1.0
 * @date 2021/3/14 1:49 下午
 */
public class Pbkdf2Sha256 {

    public static final Integer DEFAULT_ITERATIONS = 20000;
    public static final String algorithm = "pbkdf2_sha256";
    public Pbkdf2Sha256() {}

    public static String getEncodedHash(String password, String salt, int iterations) {
        // Returns only the last part of whole encoded password
        SecretKeyFactory keyFactory = null;
        try {
            keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        } catch (NoSuchAlgorithmException e) {
            System.err.println("Could NOT retrieve PBKDF2WithHmacSHA256 algorithm");
            System.exit(1);
        }
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(Charset.forName("UTF-8")), iterations, 256);
        SecretKey secret = null;
        try {
            secret = keyFactory.generateSecret(keySpec);
        } catch (InvalidKeySpecException e) {
            System.out.println("Could NOT generate secret key");
            e.printStackTrace();
        }

        byte[] rawHash = secret.getEncoded();
        byte[] hashBase64 = Base64.getEncoder().encode(rawHash);

        return new String(hashBase64);
    }
    /**
     * make salt
     * @return String
     */
    private static String getsalt(){
        int length = 12;
        Random rand = new Random();
        char[] rs = new char[length];
        for(int i = 0; i < length; i++){
            int t = rand.nextInt(3);
            if (t == 0) {
                rs[i] = (char)(rand.nextInt(10)+48);
            } else if (t == 1) {
                rs[i] = (char)(rand.nextInt(26)+65);
            } else {
                rs[i] = (char)(rand.nextInt(26)+97);
            }
        }
        return new String(rs);
    }
    /**
     * rand salt
     * iterations is default 20000
     * @param password
     * @return
     */
    public static String encode(String password) {
        return encode(password, getsalt());
    }
    /**
     * rand salt
     * @param password
     * @return
     */
    public static String encode(String password,int iterations) {
        return encode(password, getsalt(),iterations);
    }
    /**
     * iterations is default 20000
     * @param password
     * @param salt
     * @return
     */
    public static String encode(String password, String salt) {
        return encode(password, salt, DEFAULT_ITERATIONS);
    }
    /**
     *
     * @param password
     * @param salt
     * @param iterations
     * @return
     */
    public static String encode(String password, String salt, int iterations) {
        // returns hashed password, along with algorithm, number of iterations and salt
        String hash = getEncodedHash(password, salt, iterations);
        return String.format("%s$%d$%s$%s", algorithm, iterations, salt, hash);
    }

    public static boolean checkPassword(String password, String hashedPassword) {
        // hashedPassword consist of: ALGORITHM, ITERATIONS_NUMBER, SALT and
        // HASH; parts are joined with dollar character ("$")
        String[] parts = hashedPassword.split("\\$");
        if (parts.length != 4) {
            // wrong hash format
            return false;
        }
        Integer iterations = Integer.parseInt(parts[1]);
        String salt = parts[2];
        String hash = encode(password, salt, iterations);

        return hash.equals(hashedPassword);
    }
}


根据用户名查询密码

Login.dao
package com.arithmeticjia.zuul.dao;

import com.arithmeticjia.zuul.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Mapper
@Repository
public interface LoginDao {
    String getPasswordByName(@Param("username") String username);
}
LoginServiceImpl
package com.arithmeticjia.zuul.service.Impl;
import com.arithmeticjia.zuul.dao.LoginDao;
import com.arithmeticjia.zuul.pojo.User;
import com.arithmeticjia.zuul.service.LoginService;
import com.arithmeticjia.zuul.utils.Pbkdf2Sha256;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("LoginDao")
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginDao logindao;

    @Override
    public String getPasswordByName(String username){
        return logindao.getPasswordByName(username);
    }
}
LoginService.java
package com.arithmeticjia.zuul.service;

/**
 * @author ArithmeticJia
 * @version 1.0
 * @date 2021/1/5 4:15 下午
 */
public interface LoginService {
    String getPasswordByName(String username);
}
LoginDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 保证唯一 我这里填写的是映射类的名字 xml文件名和映射类的名字是一样的-->
<mapper namespace="com.arithmeticjia.zuul.dao.LoginDao">
    <!--id是映射类中的函数名字 返回类型是方法返回值中实体类型-->
    <!--当我们调用映射类的方法时候,实际上会来执行这句sql-->
    <select id="getPasswordByName" parameterType="java.lang.String" resultType="String">
      SELECT password FROM blogproject_user WHERE username = #{username}
    </select>
</mapper>
Controller
package com.arithmeticjia.zuul.controller;

import com.alibaba.fastjson.JSONObject;
import com.arithmeticjia.zuul.api.CommonResult;
import com.arithmeticjia.zuul.pojo.User;
import com.arithmeticjia.zuul.service.LoginService;
import com.arithmeticjia.zuul.service.TokenService;
import com.arithmeticjia.zuul.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.arithmeticjia.zuul.utils.Pbkdf2Sha256;


@RestController
@RequestMapping(value = "/api/v1")
public class LoginController {
    @Autowired
    private LoginService loginservice;
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResult login(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String passwordEncode = loginservice.getPasswordByName(username);
        boolean isValid = Pbkdf2Sha256.checkPassword(password, passwordEncode);
        if(username != null && password != null && isValid) {
            User userForBase = userService.findByUsername(username);
            String token = tokenService.getToken(userForBase);
            String res = "token=" + token + "&" + "username=" + userForBase.getUsername();
            res = res.replace("=","\":\"");
            res = res.replace("&","\",\"");
            res = "{\"" + res +"\"}";
            JSONObject jsonObject = JSONObject.parseObject(res);
            return CommonResult.success(jsonObject);
        }else {
            return CommonResult.validateFailed();
        }
    }

}

PostMan

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值