sky:
jwt:
#Set the secret key used when encrypting jwt signatures
admin-secret-key: itcast
# Set jwt expiration time to 2 hours
admin-ttl: 7200000
#Set the token name passed by the front end
admin-token-name: token
Get configuration class related attributes
package com.sky.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "sky.jwt")
@Data
public class JwtProperties {<!-- -->
/**
* Related configurations for management-side employees to generate jwt tokens
*/
private String adminSecretKey;
private long adminTtl;
private String adminTokenName;
/**
* Configuration related to jwt token generation by WeChat users on the client side
*/
private String userSecretKey;
private long userTtl;
private String userTokenName;
}
Login setting token
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "Employee related interface")
public class EmployeeController {<!-- -->
@Autowired
private EmployeeService employeeService;
@Autowired
private JwtProperties jwtProperties;
/**
* Log in
*
* @param employeeLoginDTO
* @return
*/
@PostMapping("/login")
@ApiOperation(value = "Employee login")
public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {<!-- -->
log.info("Employee login: {}", employeeLoginDTO);
Employee employee = employeeService.login(employeeLoginDTO);
//After successful login, generate jwt token
Map<String, Object> claims = new HashMap<>();
claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
String token = JwtUtil.createJWT(
jwtProperties.getAdminSecretKey(),
jwtProperties.getAdminTtl(),
claims);
EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
.id(employee.getId())
.userName(employee.getUsername())
.name(employee.getName())
.token(token)
.build();
return Result.success(employeeLoginVO);
}
}
The service layer handles login operations (demo)
/**
* Employee login
*
* @param employeeLoginDTO
* @return
*/
public Employee login(EmployeeLoginDTO employeeLoginDTO) {<!-- -->
String username = employeeLoginDTO.getUsername();
String password = employeeLoginDTO.getPassword();
//1. Query the data in the database according to the user name
Employee employee = employeeMapper.getByUsername(username);
//2. Handle various abnormal situations (username does not exist, password is incorrect, account is locked)
if (employee == null) {<!-- -->
//Account does not exist
throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
}
//Password comparison
//Encrypt the plaintext password passed in from the front end with md5, and then compare it.
password = DigestUtils.md5DigestAsHex(password.getBytes());
if (!password.equals(employee.getPassword())) {<!-- -->
//wrong password
throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
}
if (employee.getStatus() == StatusConstant.DISABLE) {<!-- -->
//Account is locked
throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
}
//3. Return the entity object
return employee;
}
Storing the current user’s ThreadLocal
package com.sky.context;
public class BaseContext {<!-- -->
public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void setCurrentId(Long id) {<!-- -->
threadLocal.set(id);
}
public static Long getCurrentId() {<!-- -->
return threadLocal.get();
}
public static void removeCurrentId() {<!-- -->
threadLocal.remove();
}
}
package com.sky.interceptor;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Interceptor for jwt token verification
*/
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {<!-- -->
@Autowired
private JwtProperties jwtProperties;
/**
* Verify jwt
*
* @param request
* @param response
* @param handler
* @return
* @throwsException
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<!-- -->
//Determine whether the currently intercepted method is the Controller's method or other resources
if (!(handler instanceof HandlerMethod)) {<!-- -->
//The currently intercepted method is not a dynamic method, so let it go directly.
return true;
}
//1. Get the token from the request header
String token = request.getHeader(jwtProperties.getAdminTokenName());
//2. Verification token
try {<!-- -->
log.info("jwt verification:{}", token);
Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
log.info("Current employee id:", empId);
//3. Pass, release
BaseContext.setCurrentId(empId);
return true;
} catch (Exception ex) {<!-- -->
//4. If it fails, respond with 401 status code
response.setStatus(401);
return false;
}
}
}
Register to relevant configuration classes
package com.sky.config;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.List;
/**
* Configuration class, register web layer related components
*/
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {<!-- -->
@Autowired
private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
/**
* Register custom interceptor
*
* @param registry
*/
protected void addInterceptors(InterceptorRegistry registry) {<!-- -->
log.info("Start registering custom interceptor...");
registry.addInterceptor(jwtTokenAdminInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/employee/login");
}
/**
* Generate interface documents through knife4j
* @return
*/
@Bean
public Docket docket() {<!-- -->
ApiInfo apiInfo = new ApiInfoBuilder()
.title("Cangqiong Takeaway Project Interface Document")
.version("2.0")
.description("Cangqiong Takeaway Project Interface Document")
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.sky.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
/**
* Set static resource mapping
* @param registry
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {<!-- -->
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* Extend the message converter of Spring MVC framework
*
* @param converters converters
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {<!-- -->
log.info("Extended message converter...");
//Create a message converter object
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
// You need to set up an object converter for the message converter. The object converter can serialize Java objects into json data.
converter.setObjectMapper(new JacksonObjectMapper());
// Add your own message converter to the container
converters.add(0,converter);
}
}