zoukankan      html  css  js  c++  java
  • SpringBoot-JWT

    1.pom.xml中加入依赖

            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt</artifactId>
                <version>0.9.1</version>
            </dependency>

    2.写TokenUtils 工具类,主要就2个方法(1.生成token 2.解析token)

    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    
    import io.jsonwebtoken.Claims;
    import io.jsonwebtoken.JwtBuilder;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    
    public class TokenUtils {
    	
        //its过期时间    7天
        private static final long EXPIRE_TIME = 60 * 60 * 1000 * 24 * 7;
        //its 私钥
        private static final String TOKEN_SECRET = "privateKey";
        
        /*
         *  生成token
         */
        public static String createToken(Map<String, Object> map) {
        	//its 过期时长
        	Date date=new Date(System.currentTimeMillis()+EXPIRE_TIME);
        	
        	JwtBuilder builder = Jwts.builder().signWith(SignatureAlgorithm.HS256, TOKEN_SECRET);
         //设置加密的内容 builder.setClaims(map);
         //设置过期时间 builder.setExpiration(date); String token=builder.compact(); return token; } /* * 解析token */ public static Map<String, Object> checkToken(String token) { Map<String,Object> map=new HashMap<>(); Claims claims = Jwts.parser().setSigningKey(TOKEN_SECRET).parseClaimsJws(token).getBody(); map.put("id", (int) claims.get("id")); map.put("currentName", (String) claims.get("currentName")); map.put("fullName", (String)claims.get("fullName")); map.put("role", (String)claims.get("role")); return map; } }

    3.写监听器(在拦击器中调用查询user方法时需要注入对象,但拦截器方法在前会导致对象注入失败,所以需要在监听器中手动创建@bean, 这样就能在Spring映射这个拦截器前,把拦截器中的依赖注入给完成了。)

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class LoginConfig implements WebMvcConfigurer {
    	
         //手动创建拦截器对象 @Bean public HandlerInterceptor getLoginInterceptor() { return new LoginInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration registration = registry.addInterceptor(getLoginInterceptor());
              //拦截所有请求 registration.addPathPatterns("/**");
              //放行请求的URL registration.excludePathPatterns("/login"); } }

      

    4.写拦截器

    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import com.wx5b.common.TokenUtils;
    import com.wx5b.entity.User;
    import com.wx5b.service.UserService;
    
    public class LoginInterceptor extends HandlerInterceptorAdapter {
    	
    	@Autowired
    	private UserService userService;
    
    	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
    		//获取请求携带的token
    		String requestToken = request.getHeader("X-Token");
              //解析token Map<String, Object> token = TokenUtils.checkToken(requestToken); Integer uer_id = (Integer) token.get("id"); try { User user = userService.findUserById(uer_id); if(user!=null) { return true; } } catch (Exception e) { throw new RuntimeException("用户不存在!"); } return false; } }

     5.登录controller

      获取前台提交的用户名密码,去数据库查询,如果存在就讲这个user查出来取出他的内容存放在map集合,再将此集合传给TokenUtils的createToken方法来获取产生的token,然后将此token返回给前台存储,以后每次请求都携带上。前台再次过来请求时拦截器解析出里面的内容,根据内容去数据库查询校验,如果通过就放行。

      

    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.wx5b.common.TokenUtils;
    import com.wx5b.entity.User;
    import com.wx5b.service.impl.LoginServiceImpl;
    import com.wx5b.service.impl.UserServiceImpl;
    
    
    @RestController
    @RequestMapping()
    public class LoginController {
    	
    	@Autowired
    	LoginServiceImpl loginServiceImpl;
    	@Autowired
    	UserServiceImpl userServiceImpl;
    
    	@RequestMapping(value = "login", method = RequestMethod.POST)
    	public Map<String, Object> login(@RequestBody User user,HttpServletResponse response) {
    		User user_info = loginServiceImpl.login(user);
    		Boolean result;
    		String token;
    		String message;
    		if (user_info != null) {
    			
    			Map<String,Object> map=new HashMap<>();
    			map.put("id",user_info.getId());
    			map.put("currentName", user_info.getLoginName());
    			map.put("fullName", user_info.getFullName());
    			map.put("role", user_info.getRole());
    			token = TokenUtils.createToken(map);
    			
    			user_info.setToken(token);
    			userServiceImpl.updateUser(user_info);
    			result = true;
    			message = null;
    		} else {
    			result = false;
    			token = null;
    			message = "登录失败!工号或密码不正确!";
    		}
    		Map<String, Object> map = new HashMap<String, Object>();
    		map.put("result", result);
    		map.put("token", token);
    		map.put("message", message);
    		map.put("code", 200);
    		map.put("roles", new String[] {"admin"});
    		return map;
    	}
    }
    

      

  • 相关阅读:
    Getting started with the Web ADF
    将搜狗浏览器设置为IIS的默认浏览器
    What is installed with the Web ADF?
    如何修改Flex的默认浏览器
    What is the Web Application Developer Framework
    windows C++获得本地IP地址
    lua table函数库
    【铸铁】C++服务器面试题.doc
    VC2008下提示找不到MSVCP90D.dll的解决办法
    排序
  • 原文地址:https://www.cnblogs.com/fansirHome/p/13100782.html
Copyright © 2011-2022 走看看