Springboot filter拦截token验证和跨域
背景
web验证授权合法的一般分为下面几种
- 使用session作为验证合法用户访问的验证方式
- 使用自己实现的token
- 使用OCA标准
在使用API接口授权验证时,token是自定义的方式实现起来不需要引入其他东西,关键是简单实用。
合法登陆后一般使用用户UID+盐值+时间戳使用多层对称加密生成token并放入分布式缓存中设置固定的过期时间长(和session的方式有些相同),这样当用户访问时使用token可以解密获取它的UID并据此验证其是否是合法的用户。
#springboot中实现filter
- 一种是注解filter
- 一种是显示的硬编码注册filter
先有filter
import javax.servlet.annotation.WebFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
//@WebFilter(urlPatterns = { "/api/v
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter{
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1
corsConfiguration.addAllowedHeader("*"); // 2
corsConfiguration.addAllowedMethod("*"); // 3
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
springboot配置Filter & 允许跨域请求
1.filter类
加注解:
@WebFilter(filterName = "authFilter", urlPatterns = "/*")
代码如下:
package com.activiti.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
// renwenqiang
@WebFilter(filterName = "authFilter", urlPatterns = "/*")
public class SystemFilter implements Filter {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin","*");
System.out.println(request.getRequestURL());
filterChain.doFilter(request, servletResponse);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
2.启动类
加注解:
@ServletComponentScan(basePackages = {"com.activiti.filter"})
代码如下:
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
org.activiti.spring.boot.SecurityAutoConfiguration.class })
@ServletComponentScan(basePackages = {"com.activiti.filter"})
public class DemoActiviti0108Application {
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
public static void main(String[] args) {
SpringApplication.run(DemoActiviti0108Application.class, args);
}
}
3.jquery ajax请求代码实例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="app">
<hr>
<h2>模型列表</h2>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="huizhi">绘制流程</a>
<hr>
<table border="1">
<tr>
<td>id</td>
<td>deploymentId</td>
<td>name</td>
<td>category</td>
<td>optional</td>
</tr>
<tr v-for="item in models">
<td>{{ item.id }}</td>
<td>{{ item.deploymentId }}</td>
<td>{{ item.name }}</td>
<td>{{ item.category }}</td>
<td>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >编辑</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >发布</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >删除</a>
</td>
</tr>
</table>
</div>
<script src="https://cdn.bootcss.com/jquery/2.2.2/jquery.js"></script>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
models: []
},
created: function () {
$.ajax({
type: 'GET',
url: 'http://localhost:8081/activiti/model/all',
beforeSend: function() {
console.log('beforeSend');
},
data:{},
dataType: "json",
xhrFields: {
withCredentials: false
},
crossDomain: true,
async: true,
//jsonpCallback: "jsonpCallback",//服务端用于接收callback调用的function名的参数
}).done((data) => {
console.log('done');
console.log(data);
this.models = data;
}).fail((error) => {
console.log('fail');
console.log('error');
});
}
})
</script>
</body>
</html>
大功告成 回家睡觉 嘻嘻嘻~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。