Skip to content

Commit

Permalink
过滤器
Browse files Browse the repository at this point in the history
使用过滤器对请求进行权限校验
  • Loading branch information
nbcoolkid committed Dec 9, 2019
1 parent 0ddcf63 commit 574fd22
Show file tree
Hide file tree
Showing 9 changed files with 179 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,25 @@
import org.springframework.boot.CommandLineRunner;
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.util.AntPathMatcher;

/**
* @author zhangliuning
*/
@SpringBootApplication
@ServletComponentScan
public class WsPushApplication implements CommandLineRunner {

@Autowired
private ILogWsConnectService iLogWsConnectService;

@Bean
public AntPathMatcher antPathMatcher(){
return new AntPathMatcher();
}

public static void main(String[] args) {
SpringApplication.run(WsPushApplication.class, args);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.zhangln.push.wspush.config.prop;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

/**
* @author sherry
* @description
* @date Create in 2019/12/9
* @modified By:
*/
@Data
@Component
@ConfigurationProperties(prefix = "user")
public class AppProp {

private String active;
private List<String> ignoreUrl;

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.zhangln.push.wspush.controller;

import com.zhangln.push.wspush.config.prop.AppProp;
import com.zhangln.push.wspush.controller.service.AccessService;
import com.zhangln.push.wspush.vo.GetTokenCondition;
import com.zhangln.push.wspush.vo.GetTokenResVo;
Expand Down Expand Up @@ -31,6 +32,9 @@ public class AccessController {
@Autowired
private AccessService accessService;

@Autowired
private AppProp appProp;

/**
* 获取token
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangln.push.wspush.config.prop.AppProp;
import com.zhangln.push.wspush.entity.AccessTokenEntity;
import com.zhangln.push.wspush.entity.RegUserEntity;
import com.zhangln.push.wspush.service.IAccessTokenService;
Expand Down Expand Up @@ -35,6 +36,9 @@ public class AccessService {
@Autowired
private RedisTemplate redisTemplate;

@Autowired
private AppProp appProp;

/**
* 检查认证信息是否正确
*
Expand Down Expand Up @@ -108,12 +112,20 @@ public boolean saveToken2Cache(String token, GetTokenCondition condition, Intege

/**
* 检查token是否存在
* @param access
*
* @param token
* @return
*/
public boolean exists(String access) {
String key = "access:"+access;
public boolean exists(String token) {

// 测试环境下,使用唯一的一个token就行
if ("DEV".equals(appProp.getActive())
&& "testToken".equals(token)) {
return true;
}

String key = "access:" + token;
Object o = redisTemplate.opsForValue().get(key);
return o!=null;
return o != null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.zhangln.push.wspush.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Date;

/**
* 时间过滤器
*/
@WebFilter("/**")
@Component
@Slf4j
public class TimeFilter implements Filter {

@Override
public void destroy() {
log.info("time filter destroy");
}


@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
log.info("time filter start");
long start = new Date().getTime();
chain.doFilter(request, response);
log.info("time filter 耗时:"+ (new Date().getTime() - start)+"毫秒");
log.info("time filter finish");
}

@Override
public void init(FilterConfig arg0) throws ServletException {
log.info("time filter init");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.zhangln.push.wspush.filter;

import com.alibaba.fastjson.JSONObject;
import com.zhangln.push.wspush.config.prop.AppProp;
import com.zhangln.push.wspush.controller.service.AccessService;
import com.zhangln.push.wspush.vo.HttpResVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

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.List;

/**
* @author sherry
* @description
* @date Create in 2019/12/9
* @modified By:
*/
@WebFilter("/**")
@Component
@Slf4j
public class UrlFilter implements Filter {

@Autowired
private AppProp appProp;

@Autowired
private AntPathMatcher antPathMatcher;

@Autowired
private AccessService accessService;

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
String url = httpRequest.getRequestURI();
log.info("当前请求地址:{}", url);
// 可以被忽略的地址
List<String> urls = appProp.getIgnoreUrl();

for (String tmp : urls) {
boolean flag = antPathMatcher.match(tmp, url);
if (flag) {
filterChain.doFilter(servletRequest, servletResponse);
}
}

// 执行token认证

String token = httpRequest.getHeader("access");
boolean exists = accessService.exists(token);

if (exists) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
// 校验不通过
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("content-type", "application/json;charset=utf-8");
log.info("token校验不通过");
response.getWriter().write(JSONObject.toJSONString(HttpResVo.buildError("token无效:"+token)));
}


}
}
5 changes: 5 additions & 0 deletions WebSocket/ws-push/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,8 @@ spring:
connection-init-sql: set names utf8mb4
pool-name: DatebookHikariCP
driver-class-name: com.mysql.jdbc.Driver

user:
active: ${spring.profiles.active}
ignoreUrl:
- /access/token
2 changes: 1 addition & 1 deletion WebSocket/ws-push/src/main/resources/static/ws.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
var ws = new WebSocket("ws://localhost:10002/ws");
ws.onopen = function () {
// ws.send("哇哈哈");
ws.send("{\"tokenId\":\"a71084ac-720f-438e-9ed1-f9475e73c523\",\"action\":1,\"jsonObjStr\":\"{\\\"app\\\":\\\"\\\",\\\"areaCode\\\":\\\"\\\",\\\"clientType\\\":\\\"\\\",\\\"country\\\":\\\"\\\",\\\"group\\\":\\\"\\\",\\\"user\\\":\\\"zln\\\"}\"}");
ws.send("{\"tokenId\":\"testToken\",\"action\":1,\"jsonObjStr\":\"{\\\"app\\\":\\\"\\\",\\\"areaCode\\\":\\\"\\\",\\\"clientType\\\":\\\"\\\",\\\"country\\\":\\\"\\\",\\\"group\\\":\\\"\\\",\\\"user\\\":\\\"zln\\\"}\"}");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.zhangln.push.wspush;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangln.push.wspush.config.prop.AppProp;
import com.zhangln.push.wspush.entity.RegUserEntity;
import com.zhangln.push.wspush.service.IRegUserService;
import org.junit.jupiter.api.Test;
Expand All @@ -18,6 +19,15 @@ class WsPushApplicationTests {
@Autowired
private IRegUserService iRegUserService;

@Autowired
private AppProp appProp;

@Test
public void testAppProp(){
System.out.println(appProp.getActive());
System.out.println(appProp.getIgnoreUrl());
}

@Test
void testRegUserQuerySuccess() {
List<RegUserEntity> list = iRegUserService.list(new QueryWrapper<RegUserEntity>()
Expand Down

0 comments on commit 574fd22

Please sign in to comment.