java – 如何使用spring security(spring boot)实现Ldap身份验证
我跟随代码我正在尝试实现ldap身份验证,但我认为它没有发生.
我的安全配置
@EnableWebSecurity
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/*")
.permitAll().anyRequest().authenticated().and().csrf()
.disable().httpBasic().and().csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.ldapAuthentication()
.userSearchFilter("(uid={0})")
.userSearchBase("dc=intern,dc=xyz,dc=com")
.contextSource()
.url("ldap://192.168.11.11:1234/dc=intern,dc=xyz,dc=com")
.managerDn("username")
.managerPassword("password!")
.and()
.groupSearchFilter("(&(objectClass=user)(sAMAccountName=" + "username" + "))");
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request
.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
response.sendRedirect("/notAllowed");
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
我的控制器
@RequestMapping(value = { "/test" }, method = RequestMethod.GET)
public @ResponseBody String retrieve() {
System.out.println("line 1");
System.out.println("line 2");
return "hello";
}
@RequestMapping(value = { "/notAllowed" }, method = RequestMethod.GET)
public @ResponseBody HttpStatus login() {
return HttpStatus.FORBIDDEN;
}
我的目标是:
我想实现ldap身份验证.用户名和密码将来自浏览器,虽然我也尝试过使用硬编码的用户名和密码.
如果用户是真实的,那么过滤器将通过检查令牌来检查授权.
如果这是第一次请求,则将生成并发送新令牌.如果未找到,则会发送禁止的HTTP状态.
我有以下问题:
>当我第一次从浏览器运行它返回禁止但它也在控制台中打印“第1行和第2行”虽然它不会返回你好但是禁止.>我的htpSecurity和ldap配置好吗?>从第二个请求它总是返回你好,我试图打开新选项卡,新请求,但它仍然工作正常.如果我重新启动服务器,然后只生成令牌并将其与cookie令牌进行比较.如果两个人使用相同的系统(如果不同时期).>我究竟如何测试ldap身份验证?我使用POSTMAN作为客户端.
如果我遗漏了一些信息,请告诉我.我会感谢你的答案.