zuul+spring security oauth2 + thymeleaf问题

Angel_1987 2018-12-17 03:51:18
最近在做项目,搭建开发架构时遇到了两个问题。
第一个,是通过zuul转发到认证中心登录时,认证中心登录界面样式加载不成功。先贴出第一个配置。
网关配置

spring.application.name=service-zuul-gatway
server.port=8801

spring.aop.proxy-target-class=true


eureka.instance.prefer-ip-address=true
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://service-register-server1:8000/eureka,http://service-register-server2:8001/eureka

zuul.host.connect-timeout-millis=60000
zuul.host.socket-timeout-millis=60000
ribbon.ReadTimeout=50000
ribbon.ConnectTimeout=50000


zuul.ignored-services='*'
#zuul.prefix=/api
#fail to retry
zuul.retryable=true
#zuul.ignore-security-headers=false
#zuul.add-host-header=true
#ribbon.eureka.enabled=false
zuul.add-proxy-headers=true


zuul.routes.auth-center.path=/oauth/**
zuul.routes.auth-center.service-id=auth-center
zuul.routes.auth-center.sensitive-headers=
zuul.routes.auth-center.strip-prefix=false

zuul.routes.side.path=/side/**
zuul.routes.side.service-id=side
zuul.routes.side.sensitive-headers=
#zuul.routes.side.strip-prefix=false
#zuul.routes.side.sensitive-headers=Cookie,Set-Cookie,Authorization

zuul.routes.resource-test.path=/test/**
zuul.routes.resource-test.service-id=resource-test
#zuul.routes.resource-test.sensitive-headers=


#spring.security.user.name=user
#spring.security.user.password=123456


security.oauth2.sso.login-path=/login
security.oauth2.client.access-token-uri=http://auth-center/oauth/oauth/token
security.oauth2.client.user-authorization-uri=/oauth/oauth/authorize

#security.oauth2.sso.login-path=http://localhost:8801/oauth/login
#security.oauth2.client.access-token-uri=http://localhost:8801/oauth/oauth/token
#security.oauth2.client.user-authorization-uri=http://localhost:8801/oauth/oauth/authorize

security.oauth2.client.client-id=client
security.oauth2.client.client-secret=secret
#security.oauth2.client.grant-type=password
security.oauth2.resource.jwt.key-value=1q2w3e4rasdf
security.oauth2.resource.id=openid
security.oauth2.resource.service-id=resource

#security.oauth2.client.registered-redirect-uri=http://localhost:8801/side/dologin
#security.oauth2.client.pre-established-redirect-uri=http://localhost:8801/side/dologin
#security.oauth2.client.use-current-uri=false

网关的security控制
@Configuration
@EnableOAuth2Sso
@Order(value = 0)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
private static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN";

@Bean
@Primary
public OAuth2ClientContextFilter sideOauth2ClientContextFilter() {
return new SideOauth2ClientContextFilter();
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/oauth/**", "/login").permitAll().anyRequest().authenticated()
.and()
.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher()).csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.logout().permitAll()
.logoutSuccessUrl("/");
}


private RequestMatcher csrfRequestMatcher() {
return new RequestMatcher() {
// Always allow the HTTP GET method
private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|OPTIONS|TRACE)$");

// Disable CSFR protection on the following urls:
private final AntPathRequestMatcher[] requestMatchers = { new AntPathRequestMatcher("/oauth/**") };

@Override
public boolean matches(HttpServletRequest request) {
if (allowedMethods.matcher(request.getMethod()).matches()) {
return false;
}

for (AntPathRequestMatcher matcher : requestMatchers) {
if (matcher.matches(request)) {
return false;
}
}
return true;
}
};
}

private static Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = new Cookie(CSRF_COOKIE_NAME, csrf.getToken());
cookie.setPath("/");
cookie.setSecure(true);
response.addCookie(cookie);
}
filterChain.doFilter(request, response);
}
};
}

private static CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName(CSRF_HEADER_NAME);
return repository;
}


认证中心配置
#=============================================================
#server info configure
#=============================================================
server.port=8810
#\u4E0A\u4E0B\u6587\u914D\u7F6E
server.servlet.context-path=/oauth
#\u8BF7\u6C42\u5B57\u7B26\u96C6\u7F16\u7801
server.tomcat.uri-encoding=UTF-8
server.use-forward-headers=false
#springMVC\u89C6\u56FE\u9ED8\u8BA4\u8BBF\u95EE\u524D\u7F00
spring.mvc.view.prefix=/WEB-INF/pages/
#springMVC\u89C6\u56FE\u6587\u4EF6\u540E\u7F00
spring.mvc.view.suffix=.html
#\u8BBF\u95EE\u9759\u6001\u8D44\u6E90
spring.mvc.static-path-pattern=/**


#=================================================================
#thymeleaf configure
#=================================================================
spring.thymeleaf.prefix=/WEB-INF/pages/
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.check-template-location=false
spring.thymeleaf.cache=false

spring.resources.static-locations = classpath:/templates/,classpath:/WEB-INF/pages/,classpath:/webapp/common/,classpath:/webapp/css/,classpath:/webapp/images/,classpath:/webapp/js/


#=============================================================
#eureka service register configure
#=============================================================
eureka.instance.prefer-ip-address=true
eureka.client.register-with-eureka=true
eureka.client.service-url.defaultZone=http://service-register-server1:8000/eureka,http://service-register-server2:8001/eureka
spring.application.name=auth-center

#=============================================================
#logging configure
#=============================================================
logging.level.org.springframework.security=DEBUG


#=============================================================
#data source configure
#=============================================================
#spring.datasource.type=com.mchange.v2.c3p0.ComboPooledDataSource
#spring.datasource.url=jdbc:mysql://node1:3306/SIDEDB?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.url=jdbc:mysql://localhost:3306/SIDEDB?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=true


认证中心安全控制
@Configuration
@EnableWebSecurity
public class AuthServerWebSecurityConfig extends WebSecurityConfigurerAdapter{

@Autowired
@Qualifier("userDetailsService")
private UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login").permitAll()
.usernameParameter("userCode")
.passwordParameter("password")
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/images/**", "/css/**", "/common/**");
}

通过zuul进入认证中心登录页面时,所有静态资源加载失败。
查看页面请求信息会看到如下信息。Cross-Origin Read Blocking (CORB) blocked cross-origin response http://192.168.28.208:8810/oauth/login with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
貌似是因为跨域的问题引起。此问题如何解决?

第二个问题,界面加载成功,但查看后台日志发现thymeleaf模板渲染异常。

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/pages/index/login.html]")
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:354) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:187) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) [spring-webmvc-5.0.9
...全文
208 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Angel_1987 2018-12-17
  • 打赏
  • 举报
回复
请各位路过的大神指点一下。谢谢!
循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Cloud、Spring Security & Spring Security OAuth2,博客Spring系列源码 一、Spring Boot教程 开启Spring Boot Spring Boot基础配置 Spring Boot中使用MyBatis Spring Boot中使用JdbcTemplate Spring Boot MyBatis配置Druid多数据源 Spring Boot JdbcTemplate配置Druid多数据源 Spring Boot AOP记录用户操作日志 Spring Boot中使用thymeleaf Spring Boot中使用Redis缓存数据 Spring Boot中使用Ehcache缓存数据 Spring Boot中的JSON技术 Spring Boot中编写单元测试 Spring Boot整合Swagger2构建RESTful API 使用Actuator监控Spring Boot应用 使用Spring Boot发送邮件 使用Spring Boot Admin监控服务 Spring Boot Devtools热部署 Spring Boot logback日志配置 Spring Boot项目打包成war包 Linux下部署Spring Boot jar Spring Boot中使用Jsoup防御XSS攻击 Spring Boot异常处理 Spring Boot中使用过滤器和拦截器 Spring Boot整合MyBatis通用Mapper和PageHelper 深入学习Spring Boot自动装配 深入学习Spring Boot中的SpringApplication Spring Boot配合Hibernate Validator参数校验 自定义Spring Boot 内容协商 Spring Boot 中处理跨域 Spring Boot 中的异步调用 Spring Boot 整合Kafka Spring Boot整合Mongo DB Spring Boot 2.0 WebFlux编程 Spring Boot WebFlux增删改查样例 二、Spring Boot & Shiro教程 Spring Boot Shiro用户认证 Spring Boot Shiro Remember Me Spring Boot Shiro权限控制 Spring Boot Shiro Redis Spring Boot Shiro Ehcache Spring Boot Thymeleaf中使用Shiro标签 Spring Boot Shiro在线会话管理 Spring Boot Shiro整合JWT 三、Spring Boot & Security教程 Spring Boot中开启Spring Security Spring Security自定义用户认证 Spring Security添加图形验证码 Spring Security添加记住我功能 Spring Security短信验证码登录 Spring Security Session管理 Spring Security退出登录 Spring Security权限控制 Spring Security OAuth2入门 Spring Security OAuth2自定义Token获取方式 Spring Security OAuth2自定义令牌配置 Spring Security OAuth2单点登录 四、Spring Cloud教程 初识Spring Cloud与微服务 Spring Cloud Eureka服务治理 Spring Cloud Ribbon客户端负载均衡 Spring Cloud Hystrix服务容错 Spring Cloud Hystrix Dashboard仪表盘 Spring Cloud Hystrix Dashboard仪表盘 & RabbitMQ Spring Cloud Feign 声明式服务调用 Spring Cloud Zuul服务网关 Spring Cloud Config统一配置管理 使用Spring Cloud Bus刷新配置 使用Spring Cloud Sleuth跟踪微服务 Spring Cloud Consul服务治理 五、Spring Boot && Dubbo教程 Spring Boot整合Dubbo&Zookeeper; 监控Dubbo服务 Dubbo的高可用
本项目示例基于spring boot 最新版本(2.1.9)实现,Spring Boot、Spring Cloud 学习示例,将持续更新…… 在基于Spring Boot、Spring Cloud 分布微服务开发过程中,根据实际项目环境,需要选择、集成符合项目需求的各种组件和积累各种解决方案。基于这样的背景下,我开源了本示例项目,方便大家快速上手Spring Boot、Spring Cloud 。 每个示例都带有详细的介绍文档、作者在使用过程中踩过的坑、解决方案及参考资料,方便快速上手为你提供学习捷径,少绕弯路,提高开发效率。 有需要写关于spring boot、spring cloud示例,可以给我提issue哦 ## 项目介绍 spring boot demo 是一个Spring Boot、Spring Cloud的项目示例,根据市场主流的后端技术,共集成了30+个demo,未来将持续更新。该项目包含helloworld(快速入门)、web(ssh项目快速搭建)、aop(切面编程)、data-redis(redis缓存)、quartz(集群任务实现)、shiro(权限管理)、oauth2(四种认证模式)、shign(接口参数防篡改重放)、encoder(用户密码设计)、actuator(服务监控)、cloud-config(配置中心)、cloud-gateway(服务网关)、email(邮件发送)、cloud-alibaba(微服务全家桶)等模块 ### 开发环境 - JDK1.8 + - Maven 3.5 + - IntelliJ IDEA ULTIMATE 2019.1 - MySql 5.7 + ### Spring Boot 模块 模块名称|主要内容 ---|--- helloworld|[spring mvc,Spring Boot项目创建,单元测试](https://github.com/smltq/spring-boot-demo/blob/master/helloworld/HELP.md) web|[ssh项目,spring mvc,过滤器,拦截器,监视器,thymeleaf,lombok,jquery,bootstrap,mysql](https://github.com/smltq/spring-boot-demo/blob/master/web/HELP.md) aop|[aop,正则,前置通知,后置通知,环绕通知](https://github.com/smltq/spring-boot-demo/blob/master/aop/HELP.md) data-redis|[lettuce,redis,session redis,YAML配置,连接池,对象存储](https://github.com/smltq/spring-boot-demo/blob/master/data-redis/HELP.md) quartz|[Spring Scheduler,Quartz,分布式调度,集群,mysql持久化等](https://github.com/smltq/spring-boot-demo/blob/master/quartz/HELP.md) shiro|[授权、认证、加解密、统一异常处理](https://github.com/smltq/spring-boot-demo/blob/master/shiro/HELP.md) sign|[防篡改、防重放、文档自动生成](https://github.com/smltq/spring-boot-demo/blob/master/sign/HELP.md) security|[授权、认证、加解密、mybatis plus使用](https://github.com/smltq/spring-boot-demo/blob/master/security/HELP.md) mybatis-plus-generator|[基于mybatisplus代码自动生成](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-plus-generator) mybatis-plus-crud|[基于mybatisplus实现数据库增、册、改、查](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-plus-crud) encoder|[主流加密算法介绍、用户加密算法推荐](https://github.com/smltq/spring-boot-demo/blob/master/encoder/HELP.md) actuator|[autuator介绍](https://github.com/smltq/spring-boot-demo/blob/master/actuator/README.md) admin|[可视化服务监控、使用](https://github.com/smltq/spring-boot-demo/blob/master/admin/README.md) security-oauth2-credentials|[oauth2实现密码模式、客户端模式](https://github.com/smltq/spring-boot-demo/blob/master/security-oauth2-credentials/README.md) security-oauth2-auth-code|[基于spring boot实现oauth2授权模式](https://github.com/smltq/spring-boot-demo/blob/master/security-oauth2-auth-code/README.md) mybatis-multi-datasource|[mybatis、数据库集群、读写分离、读库负载均衡](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-multi-datasource) template-thymeleaf|[thymeleaf实现应用国际化示例](https://github.com/smltq/spring-boot-demo/blob/master/template-thymeleaf) mq-redis|[redis之mq实现,发布订阅模式](https://github.com/smltq/spring-boot-demo/blob/master/mq-redis) email|[email实现邮件发送](https://github.com/smltq/spring-boot-demo/blob/master/email) jGit|[java调用git命令、jgit使用等](https://github.com/smltq/spring-boot-demo/blob/master/jGit) webmagic|[webmagic实现某电影网站爬虫示例](https://github.com/smltq/spring-boot-demo/blob/master/webmagic) netty|[基于BIO、NIO等tcp服务器搭建介绍](https://github.com/smltq/spring-boot-demo/blob/master/netty) ### Spring Cloud 模块 模块名称|主要内容 ---|--- cloud-oauth2-auth-code|[基于spring cloud实现oath2授权模式](https://github.com/smltq/spring-boot-demo/blob/master/cloud-oauth2-auth-code) cloud-gateway|[API主流网关、gateway快速上手](https://github.com/smltq/spring-boot-demo/blob/master/cloud-gateway) cloud-config|[配置中心(服务端、客户端)示例](https://github.com/smltq/spring-boot-demo/blob/master/cloud-config) cloud-feign|[Eureka服务注册中心、负载均衡、声明式服务调用](https://github.com/smltq/spring-boot-demo/blob/master/cloud-feign) cloud-hystrix|[Hystrix服务容错、异常处理、注册中心示例](https://github.com/smltq/spring-boot-demo/blob/master/cloud-hystrix) cloud-zuul|[zuul服务网关、过滤器、路由转发、服务降级、负载均衡](https://github.com/smltq/spring-boot-demo/blob/master/cloud-zuul) cloud-alibaba|[nacos服务中心、配置中心、限流等使用(系列示例整理中...)](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba) #### Spring Cloud Alibaba 模块 模块名称|主要内容 ---|--- nacos|[Spring Cloud Alibaba(一)如何使用nacos服务注册和发现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README1.md) config|[Spring Cloud Alibaba(二)配置中心多项目、多配置文件、分目录实现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README2.md) Sentinel|[Spring Cloud Alibaba(三)Sentinel之熔断降级](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README3.md) Dubbo|[Spring Cloud Alibaba(四)Spring Cloud与Dubbo的融合](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README4.md) RocketMQ|[Spring Cloud Alibaba(五)RocketMQ 异步通信实现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README5.md) ### 其它 模块名称|主要内容 ---|--- leetcode|[力扣题解目录](https://github.com/smltq/spring-boot-demo/blob/master/leetcode) ## Spring Boot 概述 Spring Boot简化了基于Spring的应用开发,通过少量的代码就能创建一个独立的、产品级别的Spring应用。 Spring Boot为Spring平台及第三方库提供开箱即用的设置,这样你就可以有条不紊地开始。多数Spring Boot应用只需要很少的Spring配置。 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Sprin

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧