Commit e83e6fb4 authored by zengtianlai3's avatar zengtianlai3

jwt

parent 9f33c1b4
package iot.sixiang.license.controller;
import iot.sixiang.license.jwt.JwtUtil;
import iot.sixiang.license.jwt.LoginUser;
import iot.sixiang.license.model.ResResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 登录Controller
*/
@Slf4j
@RestController
@RequestMapping("/")
public class LoginController {
//模拟数据库
static Map<Integer, LoginUser> userMap = new HashMap<>();
static {
LoginUser user1 = new LoginUser("root", "123456");
userMap.put(1, user1);
}
/**
* 模拟用户登录
*/
@GetMapping("login")
public ResResult login(@RequestParam("user_name") String userName, @RequestParam("password") String password) {
// @RequestBody JSONObject jsonObject
LoginUser user = new LoginUser();
user.setUser_name(userName);
user.setPassword(password);
for (LoginUser dbUser : userMap.values()) {
if (dbUser.getUser_name().equals(user.getUser_name()) && dbUser.getPassword().equals(user.getPassword())) {
log.info("登录成功!生成token!");
String token = JwtUtil.createToken(dbUser);
Map<String, String> map = new HashMap<>();
map.put("authorization", token);
return ResResult.success().record(map);
}
}
return ResResult.fail().msg("用户名或密码错误");
}
@GetMapping("logout")
public ResResult logout(@RequestParam("user_name") String userName, @RequestParam("password") String password) {
// @RequestBody JSONObject jsonObject
LoginUser user = new LoginUser();
user.setUser_name(userName);
user.setPassword(password);
for (LoginUser dbUser : userMap.values()) {
if (dbUser.getUser_name().equals(user.getUser_name()) && dbUser.getPassword().equals(user.getPassword())) {
log.info("登录成功!生成token!");
String token = JwtUtil.createToken(dbUser);
Map<String, String> map = new HashMap<>();
map.put("authorization", token);
return ResResult.success().record(map);
}
}
return ResResult.fail().msg("user_name or password is error");
}
}
package iot.sixiang.license.controller;
import com.alibaba.fastjson.JSONObject;
import iot.sixiang.license.model.ResResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/iot_license/operate")
public class OperateController {
@GetMapping("monitor/server")
public ResResult getDeviceTypes() {
List<JSONObject> list = new ArrayList<>();
JSONObject obj = new JSONObject();
obj.put("server_ip", "192.168.1.11");
obj.put("server_sam", 100);
obj.put("online_count",55);
list.add(obj);
JSONObject obj2 = new JSONObject();
obj2.put("server_ip", "192.168.1.12");
obj2.put("server_sam", 100);
obj2.put("online_count",55);
list.add(obj2);
return ResResult.success().record(list);
}
}
package iot.sixiang.license.jwt;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import iot.sixiang.license.model.ResResult;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@Slf4j
@WebFilter(filterName = "jwtFilter", urlPatterns = "/iot_license/*")
public class JwtFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setCharacterEncoding("UTF-8");
//获取header里的token
String token = request.getHeader("authorization");
if ("OPTIONS".equals(request.getMethod())) { //除了 OPTIONS请求以外, 其它请求应该被JWT检查
response.setStatus(HttpServletResponse.SC_OK);
filterChain.doFilter(request, response);
} else {
if (token == null) {
String resultStr = JSON.toJSONString(ResResult.fail().msg("认证信息不能为空"));
response.getWriter().write(resultStr);
// response.getWriter().write("miss token");
return;
}
}
// Map<String, Claim> userData = JwtUtil.verifyToken(token);
DecodedJWT jwt = JwtUtil.verifyToken(token);
if(jwt==null){
String resultStr = JSON.toJSONString(ResResult.fail().msg("认证信息非法"));
response.getWriter().write(resultStr);
return;
}else{
Map<String, Claim> userData = jwt.getClaims();
if (userData == null) {
// response.getWriter().write("token is illegal");
String resultStr = JSON.toJSONString(ResResult.fail().msg("认证信息非法"));
response.getWriter().write(resultStr);
return;
}
String userName = userData.get("user_name").asString();
String password = userData.get("password").asString();
//拦截器 拿到用户信息,放到request中
request.setAttribute("user_name", userName);
request.setAttribute("password", password);
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
package iot.sixiang.license.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JwtUtil {
/**
* 秘钥
*/
private static final String SECRET = "my_secret";
/**
* 过期时间
**/
private static final long EXPIRATION = 1800L;//单位为秒
private static HashMap<String,String> tokens = new HashMap<>();
/**
* 生成用户token,设置token超时时间
*/
public static String createToken(LoginUser user){
//过期时间
Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT");
String token= JWT.create()
.withHeader(map) //添加头部
//可以把数据存在claim中
.withClaim("user_name",user.getUser_name())
.withClaim("password",user.getPassword())
.withExpiresAt(expireDate) //超时设置,设置过期的日期
.withIssuedAt(new Date()) //签发时间
.sign(Algorithm.HMAC256(SECRET)); //SECRET加密
return token;
}
// /**
// * 检验token并解析token
// */
// public static Map<String, Claim> verifyToken(String token){
// DecodedJWT jwt=null;
// try {
// JWTVerifier verifier=JWT.require(Algorithm.HMAC256(SECRET)).build();
// jwt=verifier.verify(token);
// }catch (Exception e){
// log.error(e.getMessage());
// log.error("解析编码异常");
// }
//
// return jwt.getClaims();
// }
/**
* 检验token并解析token
*/
public static DecodedJWT verifyToken(String token){
DecodedJWT jwt=null;
try {
JWTVerifier verifier=JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt=verifier.verify(token);
}catch (Exception e){
log.error(e.getMessage());
log.error("解析编码异常");
}
return jwt;
}
}
package iot.sixiang.license.jwt;
import lombok.Data;
@Data
public class LoginUser {
private String user_name;
private String password;
public LoginUser() {
}
public LoginUser(String user_name, String password) {
this.user_name = user_name;
this.password = password;
}
}
package iot.sixiang.license.util;
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
class MyCorsConfig {
// 跨域请求处理
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
//允许所有域名进行跨域调用
config.addAllowedOrigin("*");
//允许所有请求头
config.addAllowedHeader("*");
//允许所有方法
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment