【实现方案】Springboot整合token的权限管理实现(二)—— 配置服务

前置说明

前一篇文章介绍了如何使用 JWT 生成与解析 token。这篇文章给大家介绍,当我们使用 进行开发时,如何从后端解决跨域访问问题,以及如何配置 拦截器。

tokendata官网

跨域访问 一、什么是跨域访问?

tokenpocet官网

跨域的严格一点的定义是:只要协议imToken下载,域名,端口有任何一个的不同,就被当作是跨域。

tokenall中文官网

从现在的开发技术而言,大家越来越讲究前后端分离开发。如果前后端分离,那么势必会遇到跨域访问的问题。跨域访问可以从前端或后端做相应设置来进行解决。本文在后端进行配置,解决跨域访问的问题。

二、代码示例

多说一句token 权限管理·(中国)官方网站, 这个接口非常的重要,可以在这里面配置各种自定义的拦截器。大家可以多做了解。

import xxx.interceptor.AuthenticationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * @author amber
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    /**
     * 配置外部访问
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        System.out.println("----------------------");
        registry.addMapping("/**")
                //允许任何地址访问到服务器
                .allowedOrigins("*")
                //允许携带cookie访问
                .allowCredentials(true)
                //允许一下请求方法
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }
}

拦截器

通过拦截器,我们可以轻松地将没有携带 token,或携带了非法 token 的请求拦截在执行 之前。

代码示例 一、编写 eptor

编写自定义的拦截器本体,实现 的 函数,来自定义拦截器。

import com.fasterxml.jackson.databind.ObjectMapper;
import xxx.productLibbackend.base.dto.MyResponse;
import xxx.productLibbackend.base.utils.TokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
 * @author amber 
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    /**
     * 设置拦截器,对每次前端发送的请求做token校验
     *
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //验证是否是本系统的cookie
                if (cookie.getName().equals("token")) {
                    String oldToken = cookie.getValue();
                    String newToken = TokenUtil.refreshToken(oldToken);
                    //token过期或非法
                    if (newToken == null) {
                        addHeader(request, response);
                        return false;
                    }
                    cookie.setValue(newToken);
                    //与token过期时间一样,10min
                    cookie.setMaxAge(10 * 60);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    return true;
                }
            }
        }
        addHeader(request, response);
        return false;
    }
	public void addHeader(HttpServletRequest request, HttpServletResponse response){
        String origin = request.getHeader("Origin");
        response.addHeader("Access-Control-Allow-Origin", origin);
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Max-Age", "3600");
    }
}

这里为什么要在每次 false 之前要加头部信息,我会在下一篇进行叙述。

二、 注册拦截器

在编写完拦截器后,我们要在 中注册拦截器,让其发挥作用。

还是在刚才提到的 中实现函数来进行注册。

import xxx.interceptor.AuthenticationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * @author amber
 */
@Configuration
public class Config implements WebMvcConfigurer {
/**
     * 配置请求拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 将自定义的token拦截器在这里注册、参数设置
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/test/**")
                //对以下路由不进行拦截
                .excludePathPatterns("/test/getToken")
                .excludePathPatterns("/test/deToken");
    }
    @Bean
    //实例化
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}

返回顶部
跳到底部

Copyright © 2002-2024 imToken钱包下载官网 Rights Reserved.
备案号:晋ICP备13003952号

谷歌地图 | 百度地图
Powered by Z-BlogPHP Theme By open开发