spring cloud–>账号密码登录生成token–>单点登录

  • Post author:
  • Post category:其他




单点登录



1.父工程jar依赖

<jwt.version>0.7.0</jwt.version>
 <!-- JWT -->
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt</artifactId>
                <version>${jwt.version}</version>
            </dependency>



2.配置yml文件 application.yml

server:
  port: 8150
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/aaa?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: 123456
  application:
    name: ucenter-service

  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
  redis:
    host: 192.168.211.100
    port: 6379
#指定xml文件的路径
mybatis-plus:
  mapper-locations: classpath:com/lee/ucenterservice/mapper/xml/*.xml
#日志
logging:
  level:
    com.lee.ucenterservice.mapper: debug

wx:
  open:
    # 微信开放平台 appid
    appid: wxed9954c01bb89b47
    # 微信开放平台 appsecret
    appsecret: a7482517235173ddb4083788de60b90e
    # 微信开放平台 重定向url(guli.shop需要在微信开放平台配置)
    redirecturl: http://guli.shop/api/ucenter/wx/callback



3.JwtUtils —>工具类—>生成token令牌

package com.lee.util;

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;

/**
 * @author
 */
public class JwtUtils {

    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 得到你的token值
     *
     * @param id
     * @param nickname
     * @return
     */
    public static String getJwtToken(String id, String nickname) {

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("AAA-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id", id)
                .claim("nickname", nickname)   //不要放置一些隐秘。不安全的
                .signWith(SignatureAlgorithm.HS256, APP_SECRET) //签名:Base64Url加密
                .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");
    }

}



4.实体Vo—>LoginVo—>UcenterVo

@Data
public class LoginVo {
    @ApiModelProperty(value = "手机号")
    private String mobile;

    @ApiModelProperty(value = "密码")
    private String password;

}

@Data
public class UcenterVo {
    @ApiModelProperty(value = "手机号")
    private String mobile;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "昵称")
    private String nickname;

    @ApiModelProperty(value = "验证码")
    private String code;

}



4.UcenterMemberController —->登录,并生成token令牌—>获取token中的id—-根据id查询用户的详细信息

@RestController
@RequestMapping("/ucenterservice/member")
@Api(tags="登录与注册管理接口")
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService ucenterMemberService;
    @ApiOperation(value = "账号密码登录")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo){
        String token=ucenterMemberService.login(loginVo);
        return R.ok().data("token",token);
    }
    //接口 根据token获取用户的详细信息
    @ApiOperation(value = "根据token获取用户的详细信息")
    @GetMapping("getUserInfoDetail")
    public R getUserInfoDetail(HttpServletRequest request){
        String id = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember member = this.ucenterMemberService.getById(id);
        return R.ok().data("member",member);
    }
    }



5.service–>UcenterMemberService

public interface UcenterMemberService extends IService<UcenterMember> {
 String login(LoginVo loginVo);
 }



6.service—>impl—>UcenterMemberServiceImpl

@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {
  
 @Override
    public String login(LoginVo loginVo) {
        String mobile = loginVo.getMobile();
        String password=loginVo.getPassword();
        if(StringUtils.isEmpty(mobile)|| StringUtils.isEmpty(password)){
            throw new AAAException(20001,"账户或密码不能为空");
        }
        //查询数据库是否存在该手机号
        UcenterMember ucenterMember2 = this.getOne(new QueryWrapper<UcenterMember>().eq("mobile", mobile));
        if(ucenterMember2==null){
            throw  new AAAException(20001,"账户不存在");
        }

        //判断密码是否正确
        if(!StringUtils.equals(MD5.encrypt(password),ucenterMember2.getPassword())){
            throw new AAAException(20001,"密码错误");
        }

        //判断该用户是否可用
        if(ucenterMember2.getIsDisabled()){
            throw new AAAException(20001,"该账户被冻结");
        }
        String token = JwtUtils.getJwtToken(ucenterMember2.getId(), ucenterMember2.getNickname());

        return token;
    }
    }



版权声明:本文为nnnnnnnnnnii原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。