你好,我一直在尝试配置 spring,让它在用户/通行证通过 LDAP 服务器身份验证时返回 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 https://youtu.be/mD3vmgksvz8我看过的指南以及来自演示源的拉取git https://github.com/szerhusenBC/jwt-spring-security-demo。非常有帮助!,感谢业主。必须了解过滤器如何工作。
上述源已经可以过滤掉所有受保护的API,并在未授权时发送未授权的回复作为响应。我唯一允许匿名访问的 api 是身份验证 api/auth
。它已经可以接收请求并通过网络过滤器。
但我不太清楚如何对 LDAP 服务器的上述请求进行身份验证并发送 JWT 令牌。在我读过的指南上,他们正在获取数据库上的用户信息。
我已经阅读了 WebConfiguration 中有关 LDAP 配置的一些文档,但无法将其与当前的过滤器关联起来。