JWT實現單點登錄


一寫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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM