package cn.reghao.bnt.web.admin.security.session;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;

/**
 * spring-security 6 中 使用 SecurityContextHolderFilter 代替了 SecurityContextPersistenceFilter
 * SecurityContextHolderFilter 只会从 SecurityContextRepository 中读取 SecurityContext 并设置到 SecurityContextHolder
 * 用户需要手动保存 SecurityContext, 这也是此类的目的
 * 详见 https://docs.spring.io/spring-security/reference/servlet/authentication/persistence.html
 * 和 https://docs.spring.io/spring-security/reference/servlet/authentication/session-management.html
 *
 * @author reghao
 * @date 2025-10-30 16:19:50
 */
public class MySessionAuthenticationStrategy implements SessionAuthenticationStrategy {
    private final SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();

    public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
        SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
        SecurityContext context = securityContextHolderStrategy.createEmptyContext();
        context.setAuthentication(authentication);
        securityContextHolderStrategy.setContext(context);
        securityContextRepository.saveContext(context, request, response);
    }
}
