spring security导致登录后从https跳转至http解决方案

1. 项目为spring boot项目,由原来的http连接更换为https连接,因项目中配置的了spring security,登录被spring security拦截重定向后会跳转到http

解决办法:

nginx中增加

proxy_set_header   X-Forwarded-Proto 'https';

yml文件中增加

server:
  use-forward-headers: true
  tomcat:
    remote-ip-header: x-forwarded-for
    protocol-header: x-forwarded-proto

security代码中增加以下

protected void configure(HttpSecurity http) throws Exception {
     http.requiresChannel().anyRequest().requiresSecure();

2.因项目内部使用fegin调用仍采用了http方式,即项目中https针对前端,http针对后端fegin需要做https通道排除

RequestMatcher requestMatcher = new NegatedRequestMatcher(new AntPathRequestMatcher("fegin接口调用"));
http.requiresChannel().requestMatchers(requestMatcher).requiresSecure();

  遇到的坑;requestMatchers不能传入多个new NegatedRequestMatcher,需要使用 AndRequestMatcher进行合并才可以,如

RequestMatcher a = new NegatedRequestMatcher(new AntPathRequestMatcher("/a"));
RequestMatcher b= new NegatedRequestMatcher(new AntPathRequestMatcher("b"));
RequestMatcher c = new NegatedRequestMatcher(new AntPathRequestMatcher("/c"));
AndRequestMatcher andRequestMatcher = new AndRequestMatcher(a,b,c);
http.requiresChannel().requestMatchers(andRequestMatcher).requiresSecure();

 


版权声明:本文为zhuping2002原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。