JWT(Java Web Token)集成token登录、SpringBoot前后端跨域、Mybatis-plus集成配置
pom
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
application.yml单个文件最大上传配置
spring:
servlet:
multipart:
max-file-size: 100MB
User
package com.example.springboot.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import jdk.nashorn.internal.parser.Token;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@TableName("user")
public class User implements Serializable {
@TableField(exist = false)
private Role role;
@TableField(exist = false)
private List<Menu> menuList;
@TableField(exist = false)
private List<Pet> petList;
@TableField("role_item_code")
private String roleItemCode;
@TableId("id")
private Integer id;
private String username;
private String password;
private String nickname;
private Integer age;
private String gender;
private String phone;
private String email;
private String homeAddressDetail;
private String homeAddressCountry;
private String homeAddressCity;
private String homeAddressPro;
private Integer fileId;
private Integer roleId;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createTime;
private static final long serialVersionUID = 1L;
}
UserDto.java
package com.example.springboot.controller.dto;
import com.example.springboot.entity.Menu;
import com.example.springboot.entity.Pet;
import com.example.springboot.entity.Role;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class UserDto {
private String token;
private Role role;
private List<Menu> menuList;
private List<Pet> petList;
private int id;
private String username;
private String password;
private String nickname;
private Integer age;
private String gender;
private String phone;
private String email;
private String homeAddressDetail;
private String homeAddressCountry;
private String homeAddressCity;
private String homeAddressPro;
private Integer fileId;
private Integer roleId;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createTime;
}
InterceptorConfig 拦截器实现类
package com.example.springboot.config.intereptor;
import org.springframework.context.annotation.Bean;
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 InterceptorConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/**/**");
}
@Bean
public JwtInterceptor jwtInterceptor() {
return new JwtInterceptor();
}
}
JwtInterceptor .java
package com.example.springboot.config.intereptor;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Constant;
import com.example.springboot.entity.User;
import com.example.springboot.service.UserService;
import com.example.springboot.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
public class JwtInterceptor implements HandlerInterceptor{
@Autowired
private UserServiceImpl userService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object object) throws Exception {
String token = httpServletRequest.getHeader("token");
if(!(object instanceof HandlerMethod)){
return true;
}
if (StrUtil.isBlank(token)) {
throw new ServiceException(Constant.CODE_401,"无token,请重新登录");
}
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new ServiceException(Constant.CODE_401,"token验证失败,请重新登录");
}
User user = userService.getById(userId);
if (user == null) {
throw new ServiceException(Constant.CODE_401,"用户不存在,请重新登录");
}
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new ServiceException(Constant.CODE_401,"token验证失败,请重新登录");
}
return true;
}
}
UserController 登录
@GetMapping("/login")
public Result selectToLogin(@RequestParam String username ,@RequestParam String password) {
UserDto userDto = new UserDto();
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username" , username);
queryWrapper.eq("password" ,password );
if(StrUtil.isBlank(password) || StrUtil.isBlank(username)){
throw new ServiceException(Constant.CODE_400, "参数错误");
}
User one;
try {
one = userService.getOne(queryWrapper);
} catch (Exception e) {
log.error(e.getMessage());
throw new ServiceException(Constant.CODE_500, "系统错误,可能存在多个一样账户" );
}
if(one!=null){
BeanUtil.copyProperties(one,userDto,true);
String token = TokenUtil.getToken(one);
userDto.setToken(token);
Integer roleId = userDto.getRoleId();
List<Menu> roleMenuList = userService.getRoleMenuList(roleId);
userDto.setMenuList(roleMenuList);
return new Result(Constant.CODE_200, "登录成功", userDto);
}else {
throw new ServiceException(Constant.CODE_600, "账号密码错误或用户不存在");
}
}
CorsConfig.java Springboot跨域配置类
package com.example.springboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
Mybatis-plus集成
pom
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
MybatisPlusConfig.java配置类
package com.example.springboot.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor pageInterceptor = new PaginationInnerInterceptor();
pageInterceptor.setDbType(DbType.MYSQL);
interceptor.addInnerInterceptor(pageInterceptor);
return interceptor;
}
}
|