Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LDAP][Seatunnel-web] Add ldap support for seatunnel web api calls #245

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,16 @@
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>6.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>6.3.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
Expand Down
10 changes: 10 additions & 0 deletions seatunnel-server/seatunnel-app/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,16 @@
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -655,4 +655,6 @@ private Constants() {
public static final int DEFAULT_ALERT_GROUP_ID = 1;

public static final String TASK_ID = "taskId";

public static final String LDAP = "ldap";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.seatunnel.app.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;

import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class ConfiguredAuthenticationProvider implements AuthenticationProvider {

@Autowired LdapAuthenticationBuilder ldapAuthenticationBuilder;

@Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}

@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
try {
LdapAuthenticationProvider ldapAuthenticationProvider =
ldapAuthenticationBuilder.buildLdapAuthenticationProvider(authentication);
return ldapAuthenticationProvider.authenticate(authentication);
} catch (BadCredentialsException ex) {
log.error("Invalid credentials for user : {}", authentication.getName());
throw new BadCredentialsException("Invalid credentials");
} catch (Exception ex) {
log.error(
"Error while authenticating user : {}, reason :{}",
authentication.getName(),
ex.getMessage());
ex.printStackTrace();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the stack trace

throw new AuthenticationException(ex.getMessage().toString()) {
@Override
public String getMessage() {
return super.getMessage();
}
};
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.seatunnel.app.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy;
import org.springframework.security.core.Authentication;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class LdapAuthenticationBuilder {

@Value("${spring.ldap.url}")
private String ldapUrl;

@Value("${spring.ldap.search.base}")
private String ldapSearchBase;

@Value("${spring.ldap.search.domain}")
private String ldapSearchDomain;

public LdapAuthenticationProvider buildLdapAuthenticationProvider(
Authentication authentication) {

LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
String ldapBindUser = authentication.getName();
ldapContextSource.setUserDn(
new StringBuilder()
.append(ldapBindUser)
.append("@")
.append(ldapSearchDomain)
.toString());
ldapContextSource.setPassword(authentication.getCredentials().toString());
ldapContextSource.setCacheEnvironmentProperties(false);
ldapContextSource.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy());
ldapContextSource.afterPropertiesSet();

String ldapAuthID =
ldapBindUser.toLowerCase().endsWith("@" + ldapSearchDomain)
? ldapBindUser
: ldapBindUser + "@" + ldapSearchDomain;
String searchFilter = "(userPrincipalName=" + ldapAuthID + ")";
FilterBasedLdapUserSearch userSearch =
new FilterBasedLdapUserSearch(ldapSearchBase, searchFilter, ldapContextSource);
userSearch.setSearchSubtree(true);
BindAuthenticator authenticator = new BindAuthenticator(ldapContextSource);
authenticator.setUserSearch(userSearch);
LdapAuthenticationProvider ldapAuthenticationProvider =
new LdapAuthenticationProvider(authenticator);
return ldapAuthenticationProvider;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
Expand Down Expand Up @@ -110,8 +111,10 @@ public Result<Void> disable(
}

@PostMapping("/login")
public Result<UserSimpleInfoRes> login(@RequestBody UserLoginReq req) {
return Result.success(iUserService.login(req));
public Result<UserSimpleInfoRes> login(
@RequestBody UserLoginReq req,
@RequestHeader(value = "Auth-Type", required = false) String authType) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we make the auth-type part of UserLoginReq?

return Result.success(iUserService.login(req, authType));
}

@PatchMapping("/logout")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ public interface IUserService {

void disable(int id);

UserSimpleInfoRes login(UserLoginReq req);
UserSimpleInfoRes login(UserLoginReq req, String authType);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

package org.apache.seatunnel.app.service.impl;

import org.apache.seatunnel.app.common.Constants;
import org.apache.seatunnel.app.common.UserTokenStatusEnum;
import org.apache.seatunnel.app.config.ConfiguredAuthenticationProvider;
import org.apache.seatunnel.app.dal.dao.IUserDao;
import org.apache.seatunnel.app.dal.entity.User;
import org.apache.seatunnel.app.domain.dto.user.ListUserDto;
Expand All @@ -37,7 +39,11 @@
import org.apache.seatunnel.server.common.PageData;
import org.apache.seatunnel.server.common.SeatunnelException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -60,6 +66,8 @@ public class UserServiceImpl implements IUserService {
@Value("${user.default.passwordSalt:seatunnel}")
private String defaultSalt;

@Autowired private ConfiguredAuthenticationProvider configuredAuthenticationProvider;

@Override
@Transactional(rollbackFor = Exception.class)
public AddUserRes add(AddUserReq addReq) {
Expand Down Expand Up @@ -139,16 +147,13 @@ public void disable(int id) {
}

@Override
public UserSimpleInfoRes login(UserLoginReq req) {

final String username = req.getUsername();
final String password = PasswordUtils.encryptWithSalt(defaultSalt, req.getPassword());

final User user = userDaoImpl.checkPassword(username, password);
if (Objects.isNull(user)) {
throw new SeatunnelException(USERNAME_PASSWORD_NO_MATCHED);
public UserSimpleInfoRes login(UserLoginReq req, String authType) {
User user = null;
if (Constants.LDAP.equalsIgnoreCase(authType)) {
user = ldapAuthentication(req);
} else {
user = dbAuthentication(req);
}

UserSimpleInfoRes translate = translate(user);
final String token = jwtUtils.genToken(translate.toMap());
translate.setToken(token);
Expand All @@ -160,10 +165,38 @@ public UserSimpleInfoRes login(UserLoginReq req) {
.userId(user.getId())
.build();
userDaoImpl.insertLoginLog(logDto);

return translate;
}

private User ldapAuthentication(UserLoginReq req) {
String username = req.getUsername();
String password = req.getPassword();
Authentication authenticationRequest =
new UsernamePasswordAuthenticationToken(username, password);
try {
configuredAuthenticationProvider.authenticate(authenticationRequest);
} catch (AuthenticationException ex) {
throw new SeatunnelException(USERNAME_PASSWORD_NO_MATCHED);
}

if (userDaoImpl.getByName(username) == null) {
// 2. add a new user.
final UpdateUserDto dto =
UpdateUserDto.builder().id(null).username(username).password("").build();
userDaoImpl.add(dto);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the first login, an LDAP user is added to the database. From the second login onwards, the same user can log in as a DB_USER by just not providing Auth-Type header.
There should be a way to differentiate between user types.

}
return userDaoImpl.getByName(username);
}

private User dbAuthentication(UserLoginReq req) {
final String password = PasswordUtils.encryptWithSalt(defaultSalt, req.getPassword());
final User user = userDaoImpl.checkPassword(req.getUsername(), password);
if (Objects.isNull(user)) {
throw new SeatunnelException(USERNAME_PASSWORD_NO_MATCHED);
}
return user;
}

private UserSimpleInfoRes translate(User user) {
final UserSimpleInfoRes info = new UserSimpleInfoRes();
info.setId(user.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
# please add below details when you configure ldap
ldap:
url:
search:
base:
filter:
domain:

jwt:
expireTime: 86400
Expand Down
3 changes: 3 additions & 0 deletions tools/dependencies/known-dependencies.txt
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@ spring-core-5.3.20.jar
spring-expression-5.3.20.jar
spring-jcl-5.3.20.jar
spring-jdbc-5.3.20.jar
spring-ldap-core-3.2.3.jar
spring-plugin-core-1.2.0.RELEASE.jar
spring-plugin-metadata-1.2.0.RELEASE.jar
spring-security-core-6.3.0.jar
spring-security-ldap-6.3.0.jar
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is spring 6.x java 8 compatible? can you use java 8 compatible version of spring?

spring-tx-5.3.20.jar
spring-web-5.3.20.jar
spring-webmvc-5.3.20.jar
Expand Down
Loading