Spring 5 LDAP身份验证和JWT令牌作为响应 [英] Spring 5 LDAP Authentication and JWT Token as response
问题描述
您好我一直在尝试配置spring以使其在用户/通过身份验证到LDAP服务器时返回JWT令牌;考虑下面的用例;
Hello i have been trying to configure spring to have it return JWT token if user/pass is authenticated to LDAP Server; Consider the use case below ;
< img src =https://i.stack.imgur.com/sak1e.pngalt =在此输入图像说明>
关于在上图中,我已将WebSecurity配置为使用Bearer检查/过滤请求。请参阅下面的代码
On the above diagram, i have configured WebSecurity to check/filter out requests with Bearer. See code below
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 。很棒的帮助!,给业主的信贷。了解过滤器如何以某种方式工作。
Above configuration was based on a youtube guide i've seen and also a pull from a demo source in git. Great help!, credits to the owners. Got to understand how filters work somehow.
上述来源可以过滤掉所有受保护的API,并在未经授权的情况下将未经授权的API作为响应发回。允许匿名访问的唯一API是身份验证api / auth
。它已经可以接收请求并通过Web过滤器传递。
The above source can already filter out all protected API and sends out unauthorized back as a response when it is not authorized. The only api i allowed to be accessed anonymously is the authentication api /auth
. It can already receive the request and passed through the web filters.
但我无法弄清楚如何验证对LDAP服务器的上述请求并发出JWT令牌。在我读过的指南中,他们正在获取数据库中的用户信息。
But i can't quite figure out how to authenticate the said request to LDAP server and sends out a JWT token. On the guide i've read they are getting the user information on a database.
我在WebConfiguration中阅读了一些关于LDAP配置的文档,但我无法将其与我当前的过滤器联系起来。
I've read some documentation on LDAP configuration in WebConfiguration, but i can't relate it to my current filters.
推荐答案
请查看我使用spring 4创建的以下链接。
Please check the below link I have created it using spring 4.
而不是类路径上的.ldif文件配置你自己的ldap服务器。
Instead of .ldif file on classpath configure your own ldap server.
https://github.com/merugu/springsecurity/tree/master/ldapauthenticationjwttoken
唯一的区别对于Spring 5,您应该使用
预先密码编码算法,如Bcryptpasswordencoder。由于LDAPpasswordEncoder已被弃用。
The only differences is for Spring 5 you should use advance password encoding algorithm like Bcryptpasswordencoder.As the LDAPpasswordEncoder is deprecated.
快乐编码!
这篇关于Spring 5 LDAP身份验证和JWT令牌作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!