WebSecurityConfigurerAdapter 關於成功之後頁面跳轉的配置

bf378發表於2024-10-14
package com.feitai.auth.config;

import com.feitai.manager.PtfUserDetailsManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class PtfSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PtfUserDetailsManager userDetailsManager;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsManager)
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.formLogin()
                .defaultSuccessUrl("http://localhost:8080/health") ;
//                .successForwardUrl("http://localhost:8080/health") ; // 這個forward 內部處理
//
//                .successHandler(new AuthenticationSuccessHandler() {
//                    @Override
//                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//                        response.sendRedirect("http://localhost:8080/health");
//                    }
//                });  // 這個是sendRedirect
//                .successForwardUrl("/health");  // 這個是內部的post請求
    }
}

  

相關文章