kaiyu
2020-09-15 c97552b69c0af01aadc2580a59a46f58d5545985
B/S登陆以及测试接口上传
1 files renamed
1 files deleted
4 files added
4 files modified
252 ■■■■ changed files
pom.xml 6 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/ScreenApiApplication.java 8 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/Webinterceptor/WebInterceptor.java 39 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/interceptor/WebInterceptor.java 106 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/webAnno/PassToken.java 18 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/common/webAnno/UserLoginToken.java 20 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/config/WebInterceptorConfig.java 12 ●●●● patch | view | raw | blame | history
src/main/java/com/moral/controller/WebController.java 16 ●●●● patch | view | raw | blame | history
src/main/resources/application.yml 4 ●●●● patch | view | raw | blame | history
src/main/resources/banner.txt 23 ●●●●● patch | view | raw | blame | history
pom.xml
@@ -193,6 +193,12 @@
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.4.0</version>
    </dependency>
        <!-- 阿里大于 -->
        <dependency>
src/main/java/com/moral/ScreenApiApplication.java
@@ -17,14 +17,6 @@
        return application.sources(ScreenApiApplication.class);
    }
    //Session失效时间
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return container -> {
            container.setSessionTimeout(28800);/*单位为S*/
        };
    }
    public static void main(String[] args) {
        SpringApplication.run(ScreenApiApplication.class, args);
    }
src/main/java/com/moral/Webinterceptor/WebInterceptor.java
File was deleted
src/main/java/com/moral/common/interceptor/WebInterceptor.java
New file
@@ -0,0 +1,106 @@
package com.moral.common.interceptor;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.moral.common.exception.WebAuthException;
import com.moral.common.webAnno.PassToken;
import com.moral.common.webAnno.UserLoginToken;
import com.moral.entity.Account;
import com.moral.service.AccountService;
import com.moral.service.impl.WebTokenServiceImpl;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;
/**
* @Description:
        * @Param: Web大屏端拦截器配置
        * @return:
        * @Author: 陈凯裕
        * @Date: 2020/9/14
        */
public class WebInterceptor implements HandlerInterceptor {
    @Resource
    AccountService accountService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token = request.getHeader("token");
        Enumeration<String> headerNames = request.getHeaderNames();
        //如果不是映射到方法则直接通过
        if(!(o instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)o;
        Method method = handlerMethod.getMethod();
        //如果有passtoken注解则放行
        if(method.isAnnotationPresent(PassToken.class)){
            PassToken passToken= method.getAnnotation(PassToken.class);
            //验证注解是否过期
            if(passToken.required())
                return true;
        }
        //判断请求的方法是否需要登录
        if(method.isAnnotationPresent(UserLoginToken.class)){
            //判断注解是否失效
            UserLoginToken loginToken = method.getAnnotation(UserLoginToken.class);
            if(loginToken.required()){
                if(ObjectUtils.isEmpty(token)){
                    throw new WebAuthException("无token,请重新登陆");
                }
                //获取ID
                String id = "";
                try {
                    Map<String, Claim> claims = JWT.decode(token).getClaims();
                    Claim accountId = claims.get("aid");
                    id = accountId.asString();
                }catch (JWTDecodeException e){
                    throw new WebAuthException("401,token无效");
                }
                Account account = accountService.getAccountById(Integer.parseInt(id));
                if(ObjectUtils.isEmpty(account)){
                    throw new WebAuthException("用户不存在,请重新登陆");
                }
                //验证token
                Algorithm algorithm = Algorithm.HMAC256(WebTokenServiceImpl.SECRET);
                JWTVerifier jwtVerifier = JWT.require(algorithm)
                        .withIssuer("qxpc")
                        .build();
                try{
                    jwtVerifier.verify(token);
                }catch (JWTVerificationException e){
                    throw new WebAuthException("401,token过期或者无效");
                }
                return true;
            }
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
src/main/java/com/moral/common/webAnno/PassToken.java
New file
@@ -0,0 +1,18 @@
package com.moral.common.webAnno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description: 可跳过web路径下的验证
        * @Param:
        * @return:
        * @Author: 陈凯裕
        * @Date: 2020/9/14
        */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
    boolean required() default true;
}
src/main/java/com/moral/common/webAnno/UserLoginToken.java
New file
@@ -0,0 +1,20 @@
package com.moral.common.webAnno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description: 作用在web路径下的接口,则该接口必须进行验证。
        * @Param:
        * @return:
        * @Author: 陈凯裕
        * @Date: 2020/9/14
        */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
    boolean required() default true;
}
src/main/java/com/moral/config/WebInterceptorConfig.java
File was renamed from src/main/java/com/moral/config/WebLoginConfig.java
@@ -1,6 +1,7 @@
package com.moral.config;
import com.moral.Webinterceptor.WebInterceptor;
import com.moral.common.interceptor.WebInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
@@ -9,16 +10,21 @@
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;
@Configuration
public class WebLoginConfig implements WebMvcConfigurer {
public class WebInterceptorConfig implements WebMvcConfigurer {
    @Bean
    public HandlerInterceptor getTokenInterceptor(){
        return new WebInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        InterceptorRegistration registration = interceptorRegistry.addInterceptor(new WebInterceptor());
        InterceptorRegistration registration = interceptorRegistry.addInterceptor(getTokenInterceptor());
        registration.addPathPatterns("/web/**");
        registration.excludePathPatterns("/web/login");
    }
src/main/java/com/moral/controller/WebController.java
@@ -1,13 +1,15 @@
package com.moral.controller;
import com.moral.Webinterceptor.WebInterceptor;
import com.moral.common.util.BeanUtils;
import com.moral.common.webAnno.UserLoginToken;
import com.moral.entity.AreaNames;
import com.moral.entity.Organization;
import com.moral.service.AccountService;
import com.moral.service.DictionaryDataService;
import com.moral.service.OrganizationService;
import com.moral.service.WebTokenService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -30,6 +32,8 @@
    @Resource
    DictionaryDataService dictionaryDataService;
    OrganizationService organizationService;
    @Resource
    WebTokenService webTokenService;
    @RequestMapping("login")
    public Map<String, Object> login(HttpServletRequest request){
@@ -44,7 +48,9 @@
            Object orgId = resultMap.get("orgId");
            if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) {
                StringBuilder areaNamesBuilder = new StringBuilder("中国");
                //判断是否为本公司开发者
                if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) {
                    //不是本公司开发者则获取用户所属地区
                    Organization organization = organizationService.getOrganizationById((Integer) orgId);
                    if (organization.getAreaNames() != null) {
                        Map<String, String> areaNameMap = BeanUtils.beanToMap(organization.getAreaNames());
@@ -78,14 +84,16 @@
                    resultMap.put("mapAreaCode", mapAreaCode.toString());
                }
                resultMap.put("mapPath", areaNamesBuilder.toString());
                String accountId= String.valueOf(resultMap.get("accountId"));
                resultMap.put("token",webTokenService.getToken(accountId));
            }
        }
        request.getSession().setAttribute(WebInterceptor.SESSION_KEY,resultMap);
        return resultMap;
    }
    @RequestMapping("add")
    @UserLoginToken
    @GetMapping("test")
    public String add(){
        return "123123";
        return "test success!";
    }
}
src/main/resources/application.yml
@@ -53,9 +53,9 @@
    password: guest
    channelCacheSize: 10
  redis:
    host: 47.100.8.247
    host: r-bp1672d21a422a14pd.redis.rds.aliyuncs.com
    port: 6379
    password: moral_2018
    password: KtElFcI1sYm9NP3
    database: 1
    timeout: 5000
    pool:
src/main/resources/banner.txt
New file
@@ -0,0 +1,23 @@
${AnsiColor.BRIGHT_BLACK}
////////////////////////////////////////////////////////////////////
//                          _ooOoo_                               //
//                         o8888888o                              //
//                         88" . "88                              //
//                         (| ^_^ |)                              //
//                         O\  =  /O                              //
//                      ____/`---'\____                           //
//                    .'  \\|     |//  `.                         //
//                   /  \\|||  :  |||//  \                        //
//                  /  _||||| -:- |||||-  \                       //
//                  |   | \\\  -  /// |   |                       //
//                  | \_|  ''\---/''  |   |                       //
//                  \  .-\__  `-`  ___/-. /                       //
//                ___`. .'  /--.--\  `. . ___                     //
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
//      ========`-.____`-.___\_____/___.-`____.-'========         //
//                           `=---='                              //
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//            佛祖保佑       永不宕机      永无BUG                //
////////////////////////////////////////////////////////////////////