一写jwt的配置类
public class JwtUtils { //定义两个常量 public static final long EXPIRE = 1000 * 60 * 60 * 24; //设置token过期时间 public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; //密钥,随便写,做加密操作 //生成token字符串的方法 public static String getJwtToken(String id, String nickname){ String JwtToken = Jwts.builder() //设置头信息,固定 .setHeaderParam("typ", "JWT") .setHeaderParam("alg", "HS256") //设置过期时间 .setSubject("guli-user")//名字随便取 .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) //设置token主体部分 .claim("id", id) .claim("nickname", nickname) //根据密钥生成字符串 .signWith(SignatureAlgorithm.HS256, APP_SECRET) .compact(); return JwtToken; } /** * 判断token是否存在与有效 * @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; } /** * 判断token是否存在与有效 * @param request * @return */ public static boolean checkToken(HttpServletRequest request) { try { String jwtToken = request.getHeader("token"); if(StringUtils.isEmpty(jwtToken)) return false; Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 根据token获取会员id * @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"); } }
二业务层编写
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.MD5;
import com.atguigu.eduservice.entity.UcenterMember;
import com.atguigu.eduservice.entity.vo.RegisterVo;
import com.atguigu.eduservice.mapper.UcenterMemberMapper;
import com.atguigu.eduservice.service.UcenterMemberService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
/**
* <p>
* 会员表 服务实现类
* </p>
*
* @author testjava
* @since 2020-06-05
*/
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {
//注入
@Autowired
private RedisTemplate<String,String> redisTemplate;
//登录的方法
@Override
public String login(UcenterMember member) {
String mobile = member.getMobile();
String password = member.getPassword();
//判断两者是否为空
if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
throw new GuliException(20001,"登录失败");
}
//判断手机号是否正确
QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
wrapper.eq("mobile",mobile);
UcenterMember mobilMenber = baseMapper.selectOne(wrapper);
//判断查出来的对象是否为空
if (mobilMenber == null){//没有这个手机号
throw new GuliException(20001,"登录失败手机号不存在");
}
//判断对应手机号的密码是否正确
//因为存储在数据库中的密码进行了加密, 解决办法:把输入的密码进行加密,在和数据库中的密码比较
//加密方式MD5
if (!MD5.encrypt(password).equals(mobilMenber.getPassword())){
throw new GuliException(20001,"密码错误");
}
//判断用户是否禁用
if (mobilMenber.getIsDisabled()){
throw new GuliException(20001,"用户名已被禁用");
}
//登录成功
//生成token字符串,使用JWT做到,传查出来的对象mobilMenber
String jwtToken = JwtUtils.getJwtToken(mobilMenber.getId(), mobilMenber.getNickname());
return jwtToken;
}
//注册
@Override
public void register(RegisterVo registerVo) {
//获取注册的数据
String code = registerVo.getCode();//验证码
String mobile = registerVo.getMobile();//手机号
String nickname = registerVo.getNickname();//昵称
String password = registerVo.getPassword();//密码
//非空判断
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(mobile) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password)){
throw new GuliException(20001,"注册失败");
}
//判断验证码是否正确,跟redis中验证吗是否一样
String rediscode = redisTemplate.opsForValue().get(mobile);
if (!code.equals(rediscode)){
throw new GuliException(20001,"注册失败");
}
//判断手机号是否重复
QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
wrapper.eq("mobile",mobile);
Integer integer = baseMapper.selectCount(wrapper);
if (integer > 0){
throw new GuliException(20001,"注册失败");
}
//数据添加到数据库中
UcenterMember member = new UcenterMember();
member.setMobile(mobile);
member.setPassword(MD5.encrypt(password));
member.setNickname(nickname);
member.setIsDisabled(false);
member.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
baseMapper.insert(member);
}
@Override
public UcenterMember getOpenIdMember(String openid) {
QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
wrapper.eq("openid",openid);
UcenterMember member = baseMapper.selectOne(wrapper);
return member;
}
}
三controller层
package com.atguigu.eduservice.controller; import com.atguigu.commonutils.JwtUtils; import com.atguigu.commonutils.R; import com.atguigu.eduservice.entity.UcenterMember; import com.atguigu.eduservice.entity.vo.RegisterVo; import com.atguigu.eduservice.service.UcenterMemberService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * <p> * 会员表 前端控制器 * </p> * * @author testjava * @since 2020-06-05 */ @RestController @RequestMapping("/educenter/member") @CrossOrigin public class UcenterMemberController { @Autowired private UcenterMemberService memberService; //登录 @PostMapping("login") public R loginUser(@RequestBody UcenterMember member) { //member对象封装手机号和密码 //调用service方法实现登录 //返回token值,使用jwt生成 String token = memberService.login(member); return R.ok().data("token",token); } //注册 @PostMapping("register") public R registerUser(@RequestBody RegisterVo registerVo) { memberService.register(registerVo); return R.ok(); } //根据token获取用户信息 @GetMapping("getMemberInfo") public R getMemberInfo(HttpServletRequest request) { //调用jwt工具类的方法。根据request对象获取头信息,返回用户id String memberId = JwtUtils.getMemberIdByJwtToken(request); //查询数据库根据用户id获取用户信息 UcenterMember member = memberService.getById(memberId); return R.ok().data("userInfo",member); } }
四前端调用方法获得token
