在 Spring 安全性中返回带有 LDAP 身份验证的 cookie 或令牌

Returning a cookie or token with LDAP authentication in Spring security

全部:

我有一个用于 Ldap 身份验证的基本程序,return它是一个“主要用户”

package com.bpm.cbl.premium.controller;

import java.security.Principal;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;


@RestController
@RequestMapping("custom")

public class LDAPAuthController {
    
    public static String domain;
    public static String URL;
    
    @Value("${activedirectory.domain}")
    private  String adDomain;
    
    @Value("${activedirectory.url}")
    private String adURL;
    
    @PostConstruct
    public void init(){
        domain = adDomain;
        URL = adURL;
    }

  @GetMapping("/user-login")
  @ResponseBody
  public Principal user(Principal user) {
     return user;
  }

 
  @Configuration
  @Order(SecurityProperties.BASIC_AUTH_ORDER)
  protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
      
  
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
        .httpBasic().and()
        .logout().and()
        .authorizeRequests()
        .antMatchers("/index.html", "/", "/home", "/login", "/assets/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

    @Bean
    public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider = new
        ActiveDirectoryLdapAuthenticationProvider(domain, URL);
      return activeDirectoryLdapAuthenticationProvider;
    }

}
}

我不知道如何 return cookie 或令牌而不是对象..我是 spring 安全的新手..有人可以帮忙吗 我参考了另一个 post 但不确定它是否有效

有人可以提供一些意见吗

好的,我找到了解决方案;发帖造福大家..

网上和论坛上有很多乱七八糟的文章,其实很简单

将上面@GetMapping("/user-login") 下的函数替换为 returns 响应中的 cookie body.. 将 httpsserveletresponse 作为参数传递给函数连同任何其他需要的参数.. 就是这样,cookie 将在响应中返回 header;