一.基于token的用户认证的实现
ResultVO
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
@ApiModel(value = "ResultVO对象",description = "封装接口返回给前端的数据")
public class ResultVO {
@ApiModelProperty(value="响应状态码",dataType = "int")
private int code;
@ApiModelProperty(value = "响应提示信息")
private String msg;
@ApiModelProperty(value = "响应数据")
private Object data;
}
用于加密用的帮助类
import java.util.Base64;
//base64 加密 解密 激活邮件的时候 为 邮箱地址 code验证码 进行加密
//当 回传回来后 进行邮箱地址 和 code 的解密
public class Base64Utils {
//加密
public static String encode(String msg){
return Base64.getEncoder().encodeToString(msg.getBytes());
}
//解密
public static String decode(String msg){
return new String(Base64.getDecoder().decode(msg));
}
}
UserServiceImpl
public class UserServiceImpl implements UserService {
@Resource
private UsersMapper usersMapper;
@Override
public ResultVO checkLogin(String name, String pwd) {
Example example = new Example(Users.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("username",name);
List<Users> users = usersMapper.selectByExample(example);
if(users.size()==0){
return new ResultVO(ResStatus.NO,"用户名不存在",null);
}else{
//String md5Pwd=MD5Utils.md5(pwd);
if(pwd.equals(users.get(0).getPassword())){//如果登录成功,则需要生成令牌token
String token= Base64Utils.encode(name+123456);
return new ResultVO(ResStatus.OK,token,users.get(0));
}else{
return new ResultVO(ResStatus.NO,"密码错误",null);
}
}
}
login.html
axios.get(url,
{
params:{
username:vm.username,
password:vm.password,
}
}).then((res)=>{
var vo=res.data;
console.log(vo.msg);<!--打印生成的token-->
if(vo.code=10000){
//window.location.href="index.html";
}else{
vm.tips="账号或密码错误";
}
});
控制台打印的token:
YWFhYTEyMzQ1Ng==
login.html
axios.get(url,
{
params:{
username:vm.username,
password:vm.password,
}
}).then((res)=>{
var vo=res.data;
setCookieValue("token",vo.msg);
if(vo.code=10000){
window.location.href="index.html";
}else{
vm.tips="账号或密码错误";
}
});
ShopcartController
import com.qfedu.fmmall.vo.ResStatus;
import com.qfedu.fmmall.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin
@RequestMapping("/shopcart")
@Api(value="提供购物车业务相关接口",tags = "用户管理")
public class ShopcartController {
@GetMapping("/list")
@ApiImplicitParam(dataType = "string",name = "token",value="令牌",required = true)
public ResultVO listCarts(String token){
return new ResultVO(ResStatus.OK,"success",null);
}
}
shopcart.html
<script>
var baseUrl="http://localhost:8080/";
var vm=new Vue({
el:"#container",
data:{
token:""
},
created:function(){
this.token=getCookieValue("token");
console.log("token:"+this.token);
axios({
method:"get",
url:baseUrl+"shopcart/list",
params:{
token:this.token
}
}).then(function(res){
console.log(res);
});
}
});
</script>
ShopcartController
import com.qfedu.fmmall.utils.Base64Utils;
import com.qfedu.fmmall.vo.ResStatus;
import com.qfedu.fmmall.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin
@RequestMapping("/shopcart")
@Api(value="提供购物车业务相关接口",tags = "用户管理")
public class ShopcartController {
@GetMapping("/list")
@ApiImplicitParam(dataType = "string",name = "token",value="令牌",required = true)
public ResultVO listCarts(String token){
if(token==null){
return new ResultVO(ResStatus.NO,"请登录",null);
}else{
String decode= Base64Utils.decode(token);
if (decode.endsWith("123456")) {
return new ResultVO(ResStatus.OK,"success",null);
}else{
return new ResultVO(ResStatus.NO,"请重新登录",null);
}
}
}
}
二.jwt的使用
在service子模块中添加如下依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
UserServiceImpl
import com.qfedu.fmmall.dao.UsersMapper;
import com.qfedu.fmmall.entity.Users;
import com.qfedu.fmmall.service.UserService;
import com.qfedu.fmmall.utils.Base64Utils;
import com.qfedu.fmmall.vo.ResStatus;
import com.qfedu.fmmall.vo.ResultVO;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UsersMapper usersMapper;
@Override
public ResultVO checkLogin(String name, String pwd) {
Example example = new Example(Users.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("username",name);
List<Users> users = usersMapper.selectByExample(example);
if(users.size()==0){
return new ResultVO(ResStatus.NO,"用户名不存在",null);
}else{
//String md5Pwd=MD5Utils.md5(pwd);
if(pwd.equals(users.get(0).getPassword())){
JwtBuilder builder= Jwts.builder();
HashMap<String,Object> map=new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
String token = builder.setSubject(name)//token中携带的数据
.setIssuedAt(new Date())
.setId(users.get(0).getUserId() + "")
.setClaims(map)
.setExpiration(new Date(System.currentTimeMillis() + 24*1000))//设置token过期时间
.signWith(SignatureAlgorithm.HS256, "QIANfeng6666")//设置加密方式和加密密码
.compact();
return new ResultVO(ResStatus.OK,token,users.get(0));
}else{
return new ResultVO(ResStatus.NO,"密码错误",null);
}
}
}
ShopcartController
import com.auth0.jwt.impl.JWTParser;
import com.qfedu.fmmall.utils.Base64Utils;
import com.qfedu.fmmall.vo.ResStatus;
import com.qfedu.fmmall.vo.ResultVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin
@RequestMapping("/shopcart")
@Api(value="提供购物车业务相关接口",tags = "用户管理")
public class ShopcartController {
@GetMapping("/list")
@ApiImplicitParam(dataType = "string",name = "token",value="令牌",required = true)
public ResultVO listCarts(String token){
if(token==null){
return new ResultVO(ResStatus.NO,"请登录",null);
}else{
JwtParser parser=Jwts.parser();
parser.setSigningKey("QIANfeng6666");//解析token的SigningKey必须和生成token时设置密码一致
try{
Jws<Claims> claimsJws = parser.parseClaimsJws(token);
Claims body = claimsJws.getBody();//获取token中用户数据
String subject = body.getSubject();//获取生成token设置的subject
String key1 = body.get("key1", String.class);
return new ResultVO(ResStatus.OK,"success",null);
}catch (Exception e){
return new ResultVO(ResStatus.NO,"请重新登录",null);
}
}
}
}