簡體   English   中英

生產環境:Spring安全性登錄成功重定向到localhost

[英]Production environment: Spring security login success redirect to localhost

我使用Spring Boot 2.1.6.RELEASE,Apache 2.7

<VirtualHost demo.example.com:80>
    ProxyPass / "http://localhost:8081/"
    ServerName demo.example.com
    ProxyPassReverse / http://127.0.0.1:8081/
</VirtualHost>

Spring Securit配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    FunctionPathRepository functionPathRepository;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private DataSource dataSource;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // Set service for searching user in database. And set password_encoder.
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

        // Pages no need login request.
        http.authorizeRequests().antMatchers("/", "/login", "/logout", "/images", "/css", "/js").permitAll();

        // Trang /userInfo yêu cầu phải login với vai trò ROLE_USER hoặc ROLE_ADMIN.
        // Nếu chưa login, nó sẽ redirect tới trang /login.
        http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");

        // Page for admin only.
        http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");


        List<FunctionPath> functionPathList = functionPathRepository.findAllByRole("CHIEF_ACCOUNTANT");
        int size = functionPathList.size();
        String[] functionPathArray = new String[size];
        for(int i = 0; i < size; i++){
            functionPathArray[i] = functionPathList.get(i).getFunctionPath();
        }
        http.authorizeRequests().antMatchers(functionPathArray).access("hasRole('ROLE_ADMIN')");
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");

        // Configuration for login form.
        http.authorizeRequests().and().formLogin()
                .loginProcessingUrl("/j_spring_security_check") // Submit URL of Login page.
                .loginPage("/login")
                //.defaultSuccessUrl("/userAccountInfo")
                .defaultSuccessUrl("/desktop")

                .failureUrl("/login?error=true")
                .usernameParameter("username")
                .passwordParameter("password")
                // Configuration for logout page.
                .and().logout().logoutUrl("/logout")
                // .logoutSuccessUrl("/logoutSuccessful")
                .logoutSuccessUrl("/login")

        ;
        // Configuration for Remember me function (remember 24h).
        http.authorizeRequests().and().rememberMe().tokenRepository(this.persistentTokenRepository()).tokenValiditySeconds(1 * 24 * 60 * 60);
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

}

控制者

/**
 * Show desktop.
 *
 * @return
 */
@RequestMapping(value = "/desktop", method = RequestMethod.GET)
public ModelAndView desktop() {
    ModelAndView modelAndView = new ModelAndView("system/desktop");
    modelAndView.getModel().put("page_title", "Bàn làm việc");
    return modelAndView;
}

我跑

java -jar accounting-2019.07-SNAPSHOT.jar

步驟1.前往http://demo.example.com/

步驟2.登錄成功

步驟3. Web應用程序重定向到http:// localhost:8081 / desktop ,然后Webapp失敗。

如何重定向到http://demo.example.com/desktop

解決方案是:

  1. 轉向Spring Boot應用程序的原始協議,主機和端口(部分包含在其他HTTP標頭中,部分包含在常規HTTP標頭屬性中)

  2. 配置Spring Boot以評估此信息

通常,它是通過以下配置完成的:

Apache配置

添加ProxyPreserveHostProxyPreserveHost指令:

<VirtualHost demo.bkit.vn:80>
    ProxyPreserveHost on
    RequestHeader set X-Forwarded-Proto http
    RequestHeader set X-Forwarded-Port 80
    ProxyPass / "http://localhost:8081/"
    ServerName demo.example.com
    ProxyPassReverse / http://127.0.0.1:8081/
</VirtualHost>

Spring Boot配置

在Spring Boot配置中(例如application.properties ),添加以下行:

server.use-forward-headers=true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM