【发布时间】: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