【问题标题】:Spring 5 LDAP Authentication and JWT Token as responseSpring 5 LDAP 身份验证和 JWT 令牌作为响应
【发布时间】:2019-02-07 14:40:34
【问题描述】:

您好,如果用户/密码通过 LDAP 服务器的身份验证,我一直在尝试配置 spring 以使其返回 JWT 令牌;考虑下面的用例;

在上图中,我已将 WebSecurity 配置为使用 Bearer 检查/过滤请求。见下面的代码

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    JwtAuthorizationTokenFilter authenticationTokenFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Configure Web Security
        // Allow only /auth/
        // Disallow all others
        http
        .csrf().disable()
        .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST,
                     "/auth/**")
        .permitAll()
        .anyRequest().authenticated();      

        //Custom JWT 
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // disable page caching
        http.headers().cacheControl();

    }
}

AuthCtrl.java

@RestController
@RequestMapping("auth")
public class AuthCtrl {

    private static final Logger logger = LoggerFactory.getLogger(AuthCtrl.class);

    @Autowired
    @Qualifier("authenticationManagerImpl")
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) 
    public @ResponseBody String post(@RequestBody Map<String, String> credentials) {
        logger.info("POST: {} | {} ",credentials.get("username"), credentials.get("password"));
        String username = credentials.get("username");
        String password = credentials.get("password");

        Objects.requireNonNull(username);
        Objects.requireNonNull(password);

        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
            // Reload password post-security so we can generate the token
            final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            final String token = jwtTokenUtil.generateToken(userDetails);
            return token;
        } catch (DisabledException e) {
            throw new AuthenticationException("User is disabled!", e);
        } catch (BadCredentialsException e) {
            throw new AuthenticationException("Bad credentials!", e);
        }
    }

    @ExceptionHandler({AuthenticationException.class})
    public ResponseEntity<String> handleAuthenticationException(AuthenticationException e) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
    }
}

以上配置基于我看过的youtube 指南以及git 中的演示源。很大的帮助!,感谢业主。必须了解过滤器如何以某种方式工作。

上述来源已经可以过滤掉所有受保护的 API,并在未授权时将未授权的 API 作为响应返回。我唯一允许匿名访问的 api 是身份验证 api/auth。它已经可以接收请求并通过网络过滤器。

但我不太清楚如何验证对 LDAP 服务器的所述请求并发送 JWT 令牌。在我读过的指南上,他们正在获取数据库上的用户信息。

我在 WebConfiguration 中阅读了一些关于 LDAP 配置的文档,但我无法将其与我当前的过滤器相关联。

【问题讨论】:

  • 你解决了吗?
  • @tooptoop4 还没有,实现了一个与上面完全不同的解决方法。

标签: java spring spring-security jwt spring-ldap


【解决方案1】:

请查看我使用 spring 4 创建的以下链接。

配置您自己的 ldap 服务器,而不是类路径上的 .ldif 文件。

https://github.com/merugu/springsecurity/tree/master/ldapauthenticationjwttoken

唯一的区别是你应该使用 Spring 5 高级密码编码算法,如 Bcryptpasswordencoder。由于 LDAPpasswordEncoder 已弃用。

编码愉快!

【讨论】:

  • 我能够生成令牌。但是在您的代码中之后无法访问 validatetoken api(我收到未经授权的错误)。你有什么特别的理由不使用过滤器吗?等待您的回复。
  • github中的这个mergu示例存在严重缺陷,不推荐使用。
猜你喜欢
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 2012-02-18
  • 2020-04-13
  • 2020-07-07
  • 2019-08-04
  • 2019-01-22
相关资源
最近更新 更多