Commit e13aba9a by 朱瑞泽

fix

parent 9073e614
......@@ -20,7 +20,7 @@ import org.springframework.context.annotation.ImportResource;
"classpath*:dubbo-gic-demo-web.xml",
"classpath*:spring-interceptor.xml"
})
@SpringBootApplication(scanBasePackages = {"com.gic.demo.*"}, exclude = {DataSourceAutoConfiguration.class})
@SpringBootApplication(scanBasePackages = {"com.gic.demo"}, exclude = {DataSourceAutoConfiguration.class})
public class Main {
public static void main(String[] args) {
......
package com.gic.demo.single.web.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
/**
* Created 2018/7/24.
*
* @author hua
*/
@ControllerAdvice
public class GlobalExceptionHandler2 {
private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler2.class);
@ResponseBody
@ExceptionHandler(Exception.class)
public String ControllerException(HttpServletResponse response, Exception ex) {
logger.error("err");
ex.printStackTrace();
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (PrintWriter printWriter = new PrintWriter(baos)) {
ex.printStackTrace(printWriter);
}
try {
sb.append(baos.toString());
} catch (Exception ignored) {
}
if (sb.length() == 0) {
sb.append(ex.getMessage());
}
// 输出详细错误信息,便于调试
return sb.toString();
}
}
package com.gic.demo.single.web.exception;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* @author zhurz
*/
@Component
public class CustomErrorPageRegistrar implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
for (HttpStatus httpStatus : HttpStatus.values()) {
errorPageRegistry.addErrorPages(new ErrorPage(httpStatus, "/error-" + httpStatus.value()));
}
}
}
\ No newline at end of file
package com.gic.demo.single.web.controller;
package com.gic.demo.single.web.exception;
import com.gic.commons.webapi.reponse.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -11,20 +11,23 @@ import org.springframework.web.bind.annotation.RestController;
*
* @author zhurz
*/
//@RestController
public class Test2Controller {
private static final Logger logger = LoggerFactory.getLogger(Test2Controller.class);
@RestController
public class ErrorController {
/**
* 获取门店信息
*
* @param storeId 门店id
* @return
* @param code 错误代码
* @return rest response
*/
@RequestMapping("/error")
public RestResponse getStoreInfo(String storeId) {
return RestResponse.failure("1111", "错了");
@RequestMapping("/error-{code}")
public RestResponse error(@PathVariable("code") String code) {
try {
HttpStatus httpStatus = HttpStatus.resolve(Integer.valueOf(code));
return RestResponse.failure(code, httpStatus != null ? httpStatus.getReasonPhrase() : "错了");
} catch (NumberFormatException e) {
return RestResponse.failure(code, "code 错误");
}
}
}
\ No newline at end of file
/**
*
*/
package com.gic.demo.single.web.security;
import com.gic.authcenter.security.core.authc.AuthcenterCookieClearingLogoutHandler;
import com.gic.authcenter.security.core.authc.AuthcenterLogoutSuccessHandler;
import com.gic.authcenter.security.core.authc.AuthcenterRedisSessionClearingLogoutHandler;
import com.gic.authcenter.security.core.authz.AuthcenterAccessDeniedHandler;
import com.gic.authcenter.security.core.authz.AuthcenterPermissionEvaluator;
import com.gic.demo.single.web.security.handler.CustomAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.autoconfigure.web.ServerProperties;
......@@ -11,26 +14,16 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.cors.CorsUtils;
import com.gic.authcenter.security.core.authc.AuthcenterCookieClearingLogoutHandler;
import com.gic.authcenter.security.core.authc.AuthcenterLoginUrlAuthenticationEntryPoint;
import com.gic.authcenter.security.core.authc.AuthcenterLogoutSuccessHandler;
import com.gic.authcenter.security.core.authc.AuthcenterRedisSessionClearingLogoutHandler;
import com.gic.authcenter.security.core.authz.AuthcenterAccessDeniedHandler;
import com.gic.authcenter.security.core.authz.AuthcenterPermissionEvaluator;
import com.gic.demo.single.web.security.handler.CustomAuthenticationSuccessHandler;
/**
*
* @author leeon
......@@ -40,84 +33,87 @@ import com.gic.demo.single.web.security.handler.CustomAuthenticationSuccessHandl
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ServerProperties serverProperties;
@Autowired
private ServerProperties serverProperties;
@Autowired
private RedisOperationsSessionRepository redisOperationsSessionRepository;
@Bean
@SuppressWarnings({"unchecked", "rawtypes"})
public SpringSessionBackedSessionRegistry sessionRegistry() {
return new SpringSessionBackedSessionRegistry(redisOperationsSessionRepository);
}
@Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
@Autowired
private RedisOperationsSessionRepository redisOperationsSessionRepository;
@Bean
public CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler() {
return new CustomAuthenticationSuccessHandler();
}
@Bean
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringSessionBackedSessionRegistry sessionRegistry() {
return new SpringSessionBackedSessionRegistry(((FindByIndexNameSessionRepository) redisOperationsSessionRepository));
}
@Bean
public AuthcenterAccessDeniedHandler authcenterAccessDeniedHandler() {
return new AuthcenterAccessDeniedHandler();
}
@Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler() {
return new CustomAuthenticationSuccessHandler();
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/error-*")
.permitAll()
.requestMatchers(CorsUtils::isPreFlightRequest)
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(customAuthenticationSuccessHandler())
.and()
.logout()
.addLogoutHandler(new AuthcenterCookieClearingLogoutHandler(
serverProperties.getServlet().getSession().getCookie().getName()
))
.addLogoutHandler(new AuthcenterRedisSessionClearingLogoutHandler(redisOperationsSessionRepository))
.addLogoutHandler(new SecurityContextLogoutHandler())
.logoutSuccessHandler(new AuthcenterLogoutSuccessHandler())
.and()
.exceptionHandling()
.accessDeniedHandler(authcenterAccessDeniedHandler())
.and()
.sessionManagement()
.maximumSessions(1)
.sessionRegistry(sessionRegistry())
.and()
.and().csrf().disable()
;
}
@Bean
public AuthcenterAccessDeniedHandler authcenterAccessDeniedHandler() {
return new AuthcenterAccessDeniedHandler();
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/","/login","/test-info")
.permitAll()
.requestMatchers(CorsUtils::isPreFlightRequest)
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(customAuthenticationSuccessHandler())
.and()
.logout()
.addLogoutHandler(new AuthcenterCookieClearingLogoutHandler(
serverProperties.getServlet().getSession().getCookie().getName()))
.addLogoutHandler(new AuthcenterRedisSessionClearingLogoutHandler(redisOperationsSessionRepository))
.addLogoutHandler(new SecurityContextLogoutHandler())
.logoutSuccessHandler(new AuthcenterLogoutSuccessHandler())
.and()
.exceptionHandling()
.accessDeniedHandler(authcenterAccessDeniedHandler())
.accessDeniedPage("/test-info")
.authenticationEntryPoint(new AuthcenterLoginUrlAuthenticationEntryPoint("/login"))
.and()
.sessionManagement()
.maximumSessions(1)
.sessionRegistry(sessionRegistry())
.and()
.and().csrf().disable()
;
// @formatter:on
}
@Bean
public AuthcenterPermissionEvaluator authcenterPermissionEvaluator() {
return new AuthcenterPermissionEvaluator();
}
// @Configuration
// @EnableGlobalMethodSecurity(prePostEnabled = true)
// public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
//
// @Bean
// public AuthcenterPermissionEvaluator authcenterPermissionEvaluator() {
// return new AuthcenterPermissionEvaluator();
// }
//
// @Override
// protected MethodSecurityExpressionHandler createExpressionHandler() {
// DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
// expressionHandler.setPermissionEvaluator(authcenterPermissionEvaluator());
// return expressionHandler;
// }
// }
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(authcenterPermissionEvaluator());
return expressionHandler;
}
}
}
package com.gic.demo.single.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
@Configuration
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800, redisNamespace = "gic_demo")
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
@Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
}
package com.gic.demo.single.web.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800, redisNamespace = "gic_demo")
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
@Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
}
package com.gic.demo.single.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.HttpPutFormContentFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public HttpPutFormContentFilter httpPutFormContentFilter() {
return new HttpPutFormContentFilter();
}
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
package com.gic.demo.single.web.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.HttpPutFormContentFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public HttpPutFormContentFilter httpPutFormContentFilter() {
return new HttpPutFormContentFilter();
}
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
......@@ -4,7 +4,7 @@ server:
context-path: /gic-demo-single-web
session:
cookie:
name: BIZDICTSESSIONID2
name: GIC_DEMO_SINGLE_WEB
timeout: 30m
tomcat:
uri-encoding: UTF-8
......@@ -19,15 +19,14 @@ spring:
charset: UTF-8
enabled: true
force: true
redis:
database: 11
host: 123.207.187.158
password: crs-6vmo0g9s:gic*0571
port: 27019
timeout: 5000
# redis:
# database: 11
# host: 123.207.187.158
# password: crs-6vmo0g9s:gic*0571
# port: 27019
# timeout: 5000
session:
store-type: REDIS
# store-type: none
logging:
level:
......@@ -35,12 +34,12 @@ logging:
springframework:
security: DEBUG
security:
oauth2:
client:
access-token-uri: https://www.gicdev.com/gic-authcenter/oauth/token
clientId: gicbizdictid
clientSecret: gicbizdictsecret
user-authorization-uri: https://www.gicdev.com/gic-authcenter/oauth/authorize
resource:
user-info-uri: https://www.gicdev.com/gic-authcenter/resource/userDetails
#security:
# oauth2:
# client:
# access-token-uri: https://www.gicdev.com/gic-authcenter/oauth/token
# clientId: gicbizdictid
# clientSecret: gicbizdictsecret
# user-authorization-uri: https://www.gicdev.com/gic-authcenter/oauth/authorize
# resource:
# user-info-uri: https://www.gicdev.com/gic-authcenter/resource/userDetails
......@@ -2,7 +2,7 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:interceptors>
<bean class="com.gic.commons.interceptor.HeaderTagInterceptor"/>
</mvc:interceptors>
<!-- <mvc:interceptors>-->
<!-- <bean class="com.gic.commons.interceptor.HeaderTagInterceptor"/>-->
<!-- </mvc:interceptors>-->
</beans>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment