drew 5 anni fa
parent
commit
b8c4923467

+ 0 - 20
src/main/java/com/izouma/awesomeAdmin/config/ErrorPageConfig.java

@@ -1,20 +0,0 @@
-package com.izouma.awesomeAdmin.config;
-
-import org.springframework.boot.web.server.ConfigurableWebServerFactory;
-import org.springframework.boot.web.server.ErrorPage;
-import org.springframework.boot.web.server.WebServerFactoryCustomizer;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.http.HttpStatus;
-
-@Configuration
-public class ErrorPageConfig {
-    @Bean
-    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
-
-        return (factory -> {
-            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/static/admin/index.html");
-            factory.addErrorPages(errorPage404);
-        });
-    }
-}

+ 23 - 8
src/main/java/com/izouma/awesomeAdmin/exception/GlobalExceptionHandler.java

@@ -11,11 +11,14 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
 import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.servlet.ModelAndView;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.validation.ConstraintViolation;
 import javax.validation.ConstraintViolationException;
 import javax.validation.Path;
+import java.io.PrintWriter;
+import java.io.StringWriter;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -54,10 +57,11 @@ public class GlobalExceptionHandler {
         String message = e.getMessage();
         try {
             if (e.getCause().getCause() instanceof ConstraintViolationException) {
-                ConstraintViolationException violationException = (ConstraintViolationException) e.getCause().getCause();
+                ConstraintViolationException violationException = (ConstraintViolationException) e.getCause()
+                        .getCause();
                 message = violationException.getConstraintViolations().stream()
-                                            .map(constraintViolation -> constraintViolation.getPropertyPath() + constraintViolation.getMessage())
-                                            .collect(Collectors.joining(","));
+                        .map(constraintViolation -> constraintViolation.getPropertyPath() + constraintViolation.getMessage())
+                        .collect(Collectors.joining(","));
                 log.error(message);
             }
         } catch (Exception ignore) {
@@ -71,12 +75,23 @@ public class GlobalExceptionHandler {
     @ExceptionHandler(value = Exception.class)
     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
     @ResponseBody
-    public Map<String, Object> serviceExceptionHandler(Exception e) {
-        Map<String, Object> map = new HashMap<>();
-        map.put("error", e.getMessage());
-        map.put("code", -1);
+    public Object serviceExceptionHandler(Exception e, HttpServletRequest request) {
         log.error(e.getMessage(), e);
-        return map;
+        if (request.getHeader("Accept").contains("text/html")) {
+            ModelAndView modelAndView = new ModelAndView("commons/500");
+            StringWriter out = new StringWriter();
+            PrintWriter writer = new PrintWriter(out);
+            e.printStackTrace(writer);
+            String trace = out.toString();
+            trace = trace.replaceAll("\n", "<br>");
+            modelAndView.addObject("trace", trace);
+            return modelAndView;
+        } else {
+            Map<String, Object> map = new HashMap<>();
+            map.put("error", e.getMessage());
+            map.put("code", -1);
+            return map;
+        }
     }
 
     @ExceptionHandler({BindException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class})

+ 40 - 37
src/main/java/com/izouma/awesomeAdmin/security/WebSecurityConfig.java

@@ -38,7 +38,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
     @Autowired
     public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
         auth.userDetailsService(jwtUserDetailsService)
-            .passwordEncoder(passwordEncoderBean());
+                .passwordEncoder(passwordEncoderBean());
     }
 
     @Bean
@@ -56,29 +56,32 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
     protected void configure(HttpSecurity httpSecurity) throws Exception {
         // We don't need CSRF for this example
         httpSecurity.csrf().disable()
-                    .cors().and()
-                    // dont authenticate this particular request
-                    .authorizeRequests()
-                    //swagger-ui放行路径
-                    .antMatchers("/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**", "/webjars/**").permitAll()
-                    .antMatchers("/user/register").permitAll()
-                    .antMatchers("/upload/**").permitAll()
-                    .antMatchers("/static/**").permitAll()
-                    .antMatchers("/auth/**").permitAll()
-                    .antMatchers("/admin/**").permitAll()
-                    .antMatchers("/orderNotify/**").permitAll()
-                    .antMatchers("/order/logistic").permitAll()
-                    .antMatchers("/systemVariable/all").permitAll()
-                    .antMatchers("/**/excel").permitAll()
-                    .antMatchers("/wx/**").permitAll()
-                    .antMatchers("/sms/sendVerify").permitAll()
-                    // all other requests need to be authenticated
-                    .anyRequest().authenticated().and()
-                    // make sure we use stateless session; session won't be used to
-                    // store user's state.
-                    .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
-                    .and().sessionManagement()
-                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+                .cors().and()
+                // dont authenticate this particular request
+                .authorizeRequests()
+                //swagger-ui放行路径
+                .antMatchers("/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**", "/webjars/**").permitAll()
+                .antMatchers("/user/register").permitAll()
+                .antMatchers("/upload/**").permitAll()
+                .antMatchers("/static/**").permitAll()
+                .antMatchers("/auth/**").permitAll()
+                .antMatchers("/admin/**").permitAll()
+                .antMatchers("/systemVariable/all").permitAll()
+                .antMatchers("/**/excel").permitAll()
+                .antMatchers("/wx/**").permitAll()
+                .antMatchers("/sms/sendVerify").permitAll()
+                .antMatchers("/error").permitAll()
+                .antMatchers("/401").permitAll()
+                .antMatchers("/404").permitAll()
+                .antMatchers("/500").permitAll()
+                .antMatchers("/test500").permitAll()
+                // all other requests need to be authenticated
+                .anyRequest().authenticated().and()
+                // make sure we use stateless session; session won't be used to
+                // store user's state.
+                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
+                .and().sessionManagement()
+                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
         // Add a filter to validate the tokens with every request
         httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
     }
@@ -87,19 +90,19 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
     public void configure(WebSecurity web) throws Exception {
         // AuthenticationTokenFilter will ignore the below paths
         web.ignoring()
-           .antMatchers("/auth/**")
+                .antMatchers("/auth/**")
 
-           // allow anonymous resource requests
-           .and()
-           .ignoring()
-           .antMatchers(
-                   HttpMethod.GET,
-                   "/",
-                   "/*.html",
-                   "/**/favicon.ico",
-                   "/**/*.html",
-                   "/**/*.css",
-                   "/**/*.js"
-           );
+                // allow anonymous resource requests
+                .and()
+                .ignoring()
+                .antMatchers(
+                        HttpMethod.GET,
+                        "/",
+                        "/*.html",
+                        "/**/favicon.ico",
+                        "/**/*.html",
+                        "/**/*.css",
+                        "/**/*.js"
+                );
     }
 }

+ 51 - 0
src/main/java/com/izouma/awesomeAdmin/web/AppErrorController.java

@@ -0,0 +1,51 @@
+package com.izouma.awesomeAdmin.web;
+
+import org.springframework.boot.web.servlet.error.ErrorController;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+import javax.servlet.RequestDispatcher;
+import javax.servlet.http.HttpServletRequest;
+
+@Controller
+public class AppErrorController implements ErrorController {
+    @Override
+    public String getErrorPath() {
+        return "/error";
+    }
+
+    @RequestMapping("/error")
+    public String handleError(HttpServletRequest request, Model model) {
+        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
+
+        if (status != null) {
+            int statusCode = Integer.parseInt(status.toString());
+
+            if (statusCode == HttpStatus.NOT_FOUND.value()) {
+                return "commons/404";
+            } else if (statusCode == HttpStatus.UNAUTHORIZED.value()) {
+                return "commons/401";
+            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
+                return "commons/500";
+            }
+        }
+        return "commons/error";
+    }
+
+    @RequestMapping("/401")
+    public String error401() {
+        return "commons/401";
+    }
+
+    @RequestMapping("/404")
+    public String error404() {
+        return "commons/404";
+    }
+
+    @RequestMapping("/500")
+    public String error500() {
+        return "commons/500";
+    }
+}

+ 1 - 0
src/main/java/com/izouma/awesomeAdmin/web/AuthenticationController.java

@@ -14,6 +14,7 @@ import org.springframework.security.authentication.BadCredentialsException;
 import org.springframework.security.authentication.DisabledException;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;

+ 3 - 0
src/main/resources/application.yaml

@@ -5,6 +5,9 @@ server:
     compression:
         enabled: true
         mime-types: application/json,application/xml,text/html,text/xml,text/plain
+    error:
+        whitelabel:
+            enabled: false
 spring:
     profiles:
         active: dev

BIN
src/main/resources/static/401.png


BIN
src/main/resources/static/404.png


BIN
src/main/resources/static/500.png


+ 36 - 0
src/main/resources/templates/commons/401.ftl

@@ -0,0 +1,36 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport"
+          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Document</title>
+    <style>
+        html, body {
+            padding: 0;
+            margin: 0;
+            height: 100%;
+        }
+
+        .icon {
+            display: block;
+            height: 65%;
+            margin: 0 auto 0 auto;
+            position: relative;
+            top: 10%;
+        }
+
+        @media screen and (max-width: 600px) {
+            .icon {
+                width: 80%;
+                height: auto;
+                top: 10%;
+            }
+        }
+    </style>
+</head>
+<body>
+<img class="icon" src="../static/401.png"/>
+</body>
+</html>

+ 36 - 0
src/main/resources/templates/commons/404.ftl

@@ -0,0 +1,36 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport"
+          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Document</title>
+    <style>
+        html, body {
+            padding: 0;
+            margin: 0;
+            height: 100%;
+        }
+
+        .icon {
+            display: block;
+            height: 65%;
+            margin: 0 auto 0 auto;
+            position: relative;
+            top: 10%;
+        }
+
+        @media screen and (max-width: 600px) {
+            .icon {
+                width: 80%;
+                height: auto;
+                top: 10%;
+            }
+        }
+    </style>
+</head>
+<body>
+<img class="icon" src="../static/404.png"/>
+</body>
+</html>

+ 38 - 0
src/main/resources/templates/commons/500.ftl

@@ -0,0 +1,38 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport"
+          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Document</title>
+    <style>
+        html, body {
+            padding: 0;
+            margin: 0;
+            height: 100%;
+        }
+
+        .icon {
+            display: block;
+            height: 65%;
+            margin: 0 auto 0 auto;
+            position: relative;
+            top: 10%;
+        }
+
+        @media screen and (max-width: 600px) {
+            .icon {
+                width: 80%;
+                height: auto;
+                top: 10%;
+            }
+        }
+    </style>
+</head>
+<body>
+<img class="icon" src="../static/500.png"/>
+<script>
+</script>
+</body>
+</html>

+ 13 - 0
src/main/resources/templates/commons/error.ftl

@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport"
+          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Document</title>
+</head>
+<body>
+error
+</body>
+</html>