bu'ybuyshenglombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
添加依赖 lombok
package com.example.demo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//注解了解
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
private Integer code;//业务状态码 0 成功 1失败
private String message;//提示信息
private T dataa;//响应数据
public static <E> Result<E> success(E data){
return new Result<>(0,"操作成功",data);
}
public static Result success(Integer code, String message) {
return new Result(0,"操作成功",null);
}
public static Result error(Integer code, String message) {
return new Result(1,message,null);
}
}
@Insert("insert into users(password,username) values(#{possword},#{username})")
void add(@Param("possword")String possword, @Param("username")String username);
如果找不到要用Param参数
<!--validation 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
校验依赖
import com.example.demo.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//处理全局的异常
@RestControllerAdvice
public class GlobbalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public Result handleException(Exception e) {
e.printStackTrace();
return Result.error(StringUtils.hasLength(e.getMessage())?e.getMessage():"参数不正确");
}
}
处理全局异常
登录认证
JWT令牌
{}
数字签名 token
第一部分 头部 第二部分 payload有效荷载 第三部分 签名 确保安全
login生成令牌
验证令牌
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
public void test() {
Map<String,Object> map = new HashMap<>();
map.put("id",1);
map.put("username","张三");
// 生成jwt
String token = JWT.create()
.withClaim("user",map)
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60))//过期时间 60分钟
.sign(Algorithm.HMAC256("123456"));//指定算法,密钥
System.out.println(token);
}
生成密钥token
public void test2() {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3MTQ5MTY0ODN9.eGbO7aZ5MFlr_mt0h5-Nn0Nl7nXdgIMCQroDngmOB50";
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123456")).build();
DecodedJWT jwt = jwtVerifier.verify(token);//验证token
Map<String, Claim> map = jwt.getClaims();
System.out.println(map.get("user"));
}
获取解析密钥
package com.example.demo.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import java.util.Date;
import java.util.Map;
public class JwtUtil {
private static final String Key = "123456";
public static String genToken(Map<String,Object> map){
// Map<String,Object> map = new HashMap<>();
// map.put("id",1);
// map.put("username","张三");
// 生成jwt
return JWT.create()
.withClaim("user",map)
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60))//过期时间 60分钟
.sign(Algorithm.HMAC256(Key));//指定算法,密钥
// System.out.println(token);
}
public static Map<String, Claim> parseToken(String token){
return JWT.require(Algorithm.HMAC256(Key)).build().verify(token).getClaims();
}
}
Map<String,Object> map = new HashMap<>();
map.put("username",username);
map.put("password",password);
String token = JwtUtil.genToken(map);
生成token
@PostMapping("/login")
public Result login(@RequestParam("username") String username,@RequestParam("password") String password) {
System.out.println(username+"登录,"+password);
Map<String,Object> map = new HashMap<>();
map.put("username",username);
map.put("password",password);
String token = JwtUtil.genToken(map);
System.out.println("生成的:::"+token);
Users u = usersService.findByUserNameAndPwd(username,password);
if (u != null) {
return Result.success(u);
}else{
return Result.error("不存在");
}
}
@GetMapping("/gettoken")
public Result gettoken(@RequestHeader(name = "Authorization")String token, HttpServletResponse response) {
System.out.println("jinrule ma ????"+token);
// return Result.success("所有的数据----------");
try {
Map<String, Claim> claim = JwtUtil.parseToken(token);
response.setStatus(200);
System.out.println("jinrule ma ????"+claim);
return Result.success("所有的数据----------");
} catch (Exception e) {
response.setStatus(401);
// throw new RuntimeException(e);
return Result.success("未登录");
}
}
}
拦截器进行拦截
统一的
编写拦截器,统一拦截
package com.example.demo.config;
import com.example.demo.interceptors.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// WebMvcConfigurer.super.addInterceptors(registry);
// 登录接口和注册接口不拦截
registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/logout","/user/register");
}
}
//实现拦截器 注册拦截器
@Component //注入Ioc容器中
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 令牌验证
String token = request.getHeader("Authorization");
// 解析token
try {
Map<String, Claim> claim = JwtUtil.parseToken(token);
response.setStatus(200);
System.out.println("拦截器????"+claim);
return true;
} catch (Exception e) {
response.setStatus(401);
// throw new RuntimeException(e);
return false;
}
}
}
拦截和注册
public class JwtUtil {
private static final String Key = "123456";
public static String genToken(Map<String,Object> map){
// Map<String,Object> map = new HashMap<>();
// map.put("id",1);
// map.put("username","张三");
// 生成jwt
return JWT.create()
.withClaim("user",map)
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60))//过期时间 60分钟
.sign(Algorithm.HMAC256(Key));//指定算法,密钥
// System.out.println(token);
}
public static Map<String, Object> parseToken(String token){
return JWT.require(Algorithm.HMAC256(Key)).build().verify(token).getClaim("cliams").asMap();
}
}
public class JwtUtil {
private static final String Key = "123456";
public static String genToken(Map<String,Object> map){
// Map<String,Object> map = new HashMap<>();
// map.put("id",1);
// map.put("username","张三");
// 生成jwt
return JWT.create()
.withClaim("user",map)
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60))//过期时间 60分钟
.sign(Algorithm.HMAC256(Key));//指定算法,密钥
// System.out.println(token);
}
public static Map<String, Object> parseToken(String token){
return JWT.require(Algorithm.HMAC256(Key)).build().verify(token).getClaim("user").asMap();
}
}