博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用SpringCloud Alibaba搭建属于自己的微服务(二十七)~业务开发~jwt实现用户登录
阅读量:4204 次
发布时间:2019-05-26

本文共 7647 字,大约阅读时间需要 25 分钟。

一.server-user服务中加入jwt的maven依赖和工具类.

com.auth0
java-jwt
2.2.0
package com.ccm.server.user.util;import com.auth0.jwt.JWTSigner;import com.auth0.jwt.JWTVerifier;import com.auth0.jwt.JWTVerifyException;import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;import com.ccm.common.exception.CustomerException;import com.ccm.common.exception.result.CodeEnum;import java.io.IOException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.SignatureException;import java.util.HashMap;import java.util.Map;/** *  @Description jwt工具类 *  @Author ccm *  @CreateTime 2020/08/06 16:10 */public class JwtUtil {
private static final String EXP = "exp"; private static final String PAYLOAD = "payload"; /** * @Description 生成token,设置超时时间 * @Author ccm * @CreateTime 2020/08/06 9:47 * @Params [object, maxAge, secret] * @Return java.lang.String */ public static
String sign(T object, long maxAge,String secret) throws IOException {
final JWTSigner signer = new JWTSigner(secret); final Map
claims = new HashMap
(); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(object); claims.put(PAYLOAD, jsonString); claims.put(EXP, System.currentTimeMillis() + maxAge); return signer.sign(claims); } /** * @Description 解密token * @Author ccm * @CreateTime 2020/08/06 9:47 * @Params [jwt, classT, secret] * @Return T */ public static
T unsign(String jwt, Class
classT,String secret) throws IOException, NoSuchAlgorithmException, JWTVerifyException, InvalidKeyException, SignatureException {
final JWTVerifier verifier = new JWTVerifier(secret); final Map
claims = verifier.verify(jwt); if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) { long exp = (Long) claims.get(EXP); long currentTimeMillis = System.currentTimeMillis(); if (exp > currentTimeMillis) { String json = (String) claims.get(PAYLOAD); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, classT); }else { //登录信息过期 throw new CustomerException(CodeEnum.LOGIN_INFORMATION_EXPIRED,"登录信息已经过期"); } } return null; }}
package com.ccm.common.exception.result;import lombok.AllArgsConstructor;import lombok.Getter;/** * @Description 统一状态码 * @Author ccm * @CreateTime 2020/7/14 17:35 */@Getter@AllArgsConstructorpublic enum CodeEnum {
/** * 请求成功 */ SUCCESS(0,"请求成功"), /** * 非法请求 */ ILLEGAL_REQUEST(1000,"非法请求"), LOGIN_INFORMATION_EXPIRED (1001,"登录信息国企"), /** * 客户端相关 */ SYSTEM_BUSY(4000,"系统繁忙"), /** * 系统内部问题 */ SYSTEM_INNER_ERROR(5000,"系统内部错误"); private Integer code; //状态码 private String codeMessage; //状态信息}

二.server-user服务加入自定义常量映射类,加入jwt秘钥字段.

package com.ccm.server.user.constants;import lombok.Data;import lombok.extern.slf4j.Slf4j;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** *  @Description server-user服务自定义配置实体类映射 *  @Author ccm *  @CreateTime 2020/08/06 16:23 */@Slf4j@Data@Component@ConfigurationProperties(prefix = "server-user")public class ServerUserProperties {
private String jwtSecretKey;}

bootstrap.yml中加入

server-user:  jwtSecretKey: ccmMall #生成token的秘钥

三.业务代码开发.

1.控制层

package com.ccm.server.user.controller;import com.ccm.common.exception.result.ResultSet;import com.ccm.server.user.controller.req.UserLoginReq;import com.ccm.server.user.controller.req.UserRegisterReq;import com.ccm.server.user.service.UserService;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.validation.Valid;import java.io.IOException;@Api(tags = "用户控制层")@RestController@RequestMapping(value = "user")public class UserController {
@Autowired private UserService userService; @ApiOperation(value = "登录") @PostMapping(value = "login") public ResultSet login(@Valid @RequestBody UserLoginReq userLoginReq) throws IOException {
String token = userService.login(userLoginReq.getUsername(),userLoginReq.getPassword()); return ResultSet.success(token); }}
package com.ccm.server.user.controller.req;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import javax.validation.constraints.NotBlank;@ApiModel(value = "用户登录入参")@Datapublic class UserLoginReq {
@NotBlank @ApiModelProperty(value = "用户名") private String username; @NotBlank @ApiModelProperty(value = "密码") private String password;}

2.业务层

package com.ccm.server.user.service;import java.io.IOException;/** * @Description 用户业务层 * @Author ccm * @CreateTime 2020/8/5 15:07 */public interface UserService {
/** * @Description 登录 * @Author zhouzhiwu * @CreateTime 2020/8/6 16:21 * @Params [username, password] * @Return java.lang.String */ String login(String username, String password) throws IOException;}
package com.ccm.server.user.service.impl;import com.ccm.common.exception.CustomerException;import com.ccm.server.user.constants.ServerUserProperties;import com.ccm.server.user.dao.mysql.domain.UserInfo;import com.ccm.server.user.dao.mysql.mapper.UserInfoMapper;import com.ccm.server.user.service.UserService;import com.ccm.server.user.util.JwtUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.io.IOException;/** *  @Description 用户业务层实现 *  @Author ccm *  @CreateTime 2020/08/05 15:17 */@Servicepublic class UserServiceImpl implements UserService {
@Autowired private UserInfoMapper userInfoMapper; @Autowired private ServerUserProperties serverUserProperties; @Override public String login(String username, String password) throws IOException {
UserInfo userInfo = userInfoMapper.selectByUsernameAndPassword(username,password); if(userInfo == null) {
throw new CustomerException("用户名或密码错误"); } //生成token,token的加密信息为用户id,token的失效时间为24小时 String token = JwtUtil.sign(userInfo.getUserId(), 24 * 60 * 60 * 1000L, serverUserProperties.getJwtSecretKey()); return token; }}

3.持久层

package com.ccm.server.user.dao.mysql.mapper;import com.ccm.server.user.dao.mysql.domain.UserInfo;import org.apache.ibatis.annotations.Param;/** *  @Description user_info表mapper *  @Author ccm *  @CreateTime 2020/08/05 15:20 */public interface UserInfoMapper {
UserInfo selectByUsernameAndPassword(@Param("username")String username, @Param("password")String password);}
package com.ccm.server.user.dao.mysql.domain;import lombok.Data;import java.util.Date;/** *  @Description user_info表实体类映射 *  @Author zhouzhiwu *  @CreateTime 2020/08/05 15:19 */@Datapublic class UserInfo {
private Long userId; private String username; private String password; private Date updateTime; private Date createTime;}

四.测试

在这里插入图片描述

成功返回了token
在这里插入图片描述

您的点赞、收藏、转发和关注是我持续创作的动力!

源码地址:

转载地址:http://qktli.baihongyu.com/

你可能感兴趣的文章