当前位置:网站首页>JWT login authentication

JWT login authentication

2022-06-29 18:18:00 Math kids who don't like fitness are not good programmers


Catalog

One 、JWT What is it? ?

1. Concept

2. structure

Two 、 writing tool (config) package

1.JwtUtils

2.JsonResult

3.ResultCode

4.ResultTool

3、 ... and 、Controller layer


One 、JWT What is it? ?

1. Concept

JWT It's a simple way to transfer security information between two parties 、URL Specification of safety statements . Is the user name 、 Password to login , After server verification , Will generate a token, Return to the client , The client will carry this in the next visit token, The server is responsible for verifying this every time token. Because of the existence of digital signature , This information is credible ,JWT have access to HMAC Algorithm or RSA The public and private key pair of .

2. structure

  • header (Header)
  • Payload (Payload)
  • Signature (Signature)

Two 、 writing tool (config) package

stay SpringBoot Create... Under the project config( tool kit ) package , Create classes and enumerations under the package .

1.JwtUtils

package com.alanx.java.util;


import com.alanx.java.bean.Users;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


public class JwtUtils {

    // Constant 
    public static final long EXPIRE = 1000 * 60 * 60 * 24; //token Expiration time 
    public static final String APP_SECRET = "13579"; // Secret key , Add salt 

    //	@param id  The current user ID
    //	@param issuer  The JWT Issued by , Whether to use is optional 
    //	@param subject  The JWT Target users , Whether to use is optional 
    //	@param ttlMillis  When does it expire , Here is a Unix Time stamp , Whether to use is optional 
    //	@param audience  To receive JWT On the side of , Whether to use is optional 
    // Generate token String method 
    public static String getJwtToken(Users user) {

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")    // Header information 
                .setHeaderParam("alg", "HS256")    // Header information 
                // The next part is payload part 
                //  Set the default label 
                .setSubject("alanx")    // Set up jwt Target users 
                .setIssuedAt(new Date())    // Set the time when the visa will take effect 
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))    // Set the expiration date of the visa 
                // Customized information , It's stored here id And name information 
                .claim("id", user.getId())  // Set up token Main part  , Store user information 
                .claim("name", user.getUserName())
                .claim("nickName",user.getNickName())
                // Here's the third part 
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        //  The resulting string is jwt Information , This one usually goes back out 
        return JwtToken;
    }

    /**
     *  Judge token Whether it exists and works 
     *  Directly determine the string form of jwt character string 
     *
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *  Judge token Whether it exists and works 
     *  Because usually jwt It's all carried in the request header , The parameter passed in by this method is request 
     *
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");// Note that the name must be token To get jwt
            if (StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *  according to token String to get members id
     *  This method also comes directly from http In the request of id Of 
     *
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }

    /**
     *  analysis JWT
     *
     * @param jwt
     * @return
     */
    public static Claims parseJWT(String jwt) {
        Claims claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwt).getBody();
        return claims;
    }
}

2.JsonResult

package com.alanx.java.util;

import lombok.Data;

import java.io.Serializable;

/**
 * @Description:  Unified return entity 
 */
@Data
public class JsonResult<T> implements Serializable {
    private Boolean success;
    private Integer errorCode;
    private String errorMsg;
    private T data;

    public JsonResult() {
    }

    public JsonResult(boolean success) {
        this.success = success;
        this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
        this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
    }

    public JsonResult(boolean success, ResultCode resultEnum) {
        this.success = success;
        this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
        this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
    }

    public JsonResult(boolean success, T data) {
        this.success = success;
        this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
        this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
        this.data = data;
    }

    public JsonResult(boolean success, ResultCode resultEnum, T data) {
        this.success = success;
        this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
        this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
        this.data = data;
    }

}

3.ResultCode

package com.alanx.java.util;

/**
 * @Description:  Return code definition 
 *  Regulations :
 * #1 It means success 
 * #1001~1999  Interval indicates parameter error 
 * #2001~2999  Interval indicates user error 
 * #3001~3999  The interval indicates that the interface is abnormal 
 */
public enum ResultCode {
    /*  success  */
    SUCCESS(200, " success "),

    /*  Default failure  */
    COMMON_FAIL(999, " Failure "),

    /*  Parameter error :1000~1999 */
    PARAM_NOT_VALID(1001, " Invalid parameter "),
    PARAM_IS_BLANK(1002, " The parameter is empty. "),
    PARAM_TYPE_ERROR(1003, " Wrong parameter type "),
    PARAM_NOT_COMPLETE(1004, " Missing parameter "),

    /*  User error  */
    USER_NOT_LOGIN(2001, " The user is not logged in "),
    USER_ACCOUNT_EXPIRED(2002, " Account has expired "),
    USER_CREDENTIALS_ERROR(2003, " Wrong password "),
    USER_CREDENTIALS_EXPIRED(2004, " Password expired "),
    USER_ACCOUNT_DISABLE(2005, " Account not available "),
    USER_ACCOUNT_LOCKED(2006, " The account is locked "),
    USER_ACCOUNT_NOT_EXIST(2007, " Account does not exist "),
    USER_ACCOUNT_ALREADY_EXIST(2008, " Account already exists "),
    USER_ACCOUNT_USE_BY_OTHERS(2009, " Account offline "),

    /*  Business error  */
    NO_PERMISSION(3001, " No authority ");
    private Integer code;
    private String message;

    ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     *  according to code obtain message
     *
     * @param code
     * @return
     */
    public static String getMessageByCode(Integer code) {
        for (ResultCode ele : values()) {
            if (ele.getCode().equals(code)) {
                return ele.getMessage();
            }
        }
        return null;
    }
}

4.ResultTool

package com.alanx.java.util;


/**
 * @Description:  Return body construction tool 
 */
public class ResultTool {
    public static JsonResult success() {
        return new JsonResult(true);
    }

    public static <T> JsonResult<T> success(T data) {
        return new JsonResult(true, data);
    }

    public static JsonResult fail() {
        return new JsonResult(false);
    }

    public static JsonResult fail(ResultCode resultEnum) {
        return new JsonResult(false, resultEnum);
    }
}

3、 ... and 、Controller layer

After the first successful login , Store information in Rides in

package com.alanx.java.controller;

import com.alanx.java.bean.Users;
import com.alanx.java.service.UserService;
import com.alanx.java.util.JsonResult;
import com.alanx.java.util.JwtUtils;
import com.alanx.java.util.ResultTool;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Resource
    private UserService service;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public String login(Users users) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", users.getUserName());
        wrapper.eq("password", users.getPassWord());
        List<Users> list = service.list(wrapper);
        if (list.size() == 0) {
            return JSON.toJSONString(ResultTool.fail());    // Failure returns an error code 
        }
        Users u = list.get(0);
        String token = JwtUtils.getJwtToken(u);
        stringRedisTemplate.opsForValue().set(u.getId() + "", token, 1, TimeUnit.DAYS); // Store in redis in 
        JsonResult<String> result = ResultTool.success(token);
        return JSON.toJSONString(result);
    }
}

  Use Postman Test the result. If the password is wrong, an error code will be returned

If the password is correct , There will be jwt

  stay Redis Query results in , Copy results to ​​​​​​​JWT Official website After decoding, information other than the password will appear .

 

In the second part of the carrier, the decoded results can be customized , stay JwtUtils Class getJwtToken Method


原网站

版权声明
本文为[Math kids who don't like fitness are not good programmers]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/180/202206291757513250.html