This commit is contained in:
shiziyuan9527 2020-06-22 18:46:30 +08:00
parent 8bcf1ebc4c
commit d9cc2c7d7f
8 changed files with 68 additions and 106 deletions

View File

@ -44,6 +44,7 @@ public class ShiroConfig {
filterChainDefinitionMap.put("/resource/**", "anon");
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/signin", "anon");
filterChainDefinitionMap.put("/ldap/signin", "anon");
filterChainDefinitionMap.put("/isLogin", "anon");
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");

View File

@ -36,52 +36,7 @@ public class LoginController {
@PostMapping(value = "/signin")
public ResultHolder login(@RequestBody LoginRequest request) {
String msg;
String username = StringUtils.trim(request.getUsername());
String password = StringUtils.trim(request.getPassword());
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return ResultHolder.error("user or password can't be null");
}
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
if (subject.isAuthenticated()) {
UserDTO user = (UserDTO) subject.getSession().getAttribute(ATTR_USER);
// 自动选中组织工作空间
if (StringUtils.isEmpty(user.getLastOrganizationId())) {
List<UserRole> userRoles = user.getUserRoles();
List<UserRole> test = userRoles.stream().filter(ur -> ur.getRoleId().startsWith("test")).collect(Collectors.toList());
List<UserRole> org = userRoles.stream().filter(ur -> ur.getRoleId().startsWith("org")).collect(Collectors.toList());
if (test.size() > 0) {
String wsId = test.get(0).getSourceId();
userService.switchUserRole("workspace", wsId);
} else if (org.size() > 0) {
String orgId = org.get(0).getSourceId();
userService.switchUserRole("organization", orgId);
}
}
// 返回 userDTO
return ResultHolder.success(subject.getSession().getAttribute("user"));
} else {
return ResultHolder.error(Translator.get("login_fail"));
}
} catch (ExcessiveAttemptsException e) {
msg = Translator.get("excessive_attempts");
} catch (LockedAccountException e) {
msg = Translator.get("user_locked");
} catch (DisabledAccountException e) {
msg = Translator.get("user_has_been_disabled");
} catch (ExpiredCredentialsException e) {
msg = Translator.get("user_expires");
} catch (AuthenticationException e) {
msg = e.getMessage();
} catch (UnauthorizedException e) {
msg = Translator.get("not_authorized") + e.getMessage();
}
return ResultHolder.error(msg);
return userService.login(request);
}
@GetMapping(value = "/signout")

View File

@ -25,19 +25,21 @@ public class LdapService {
public boolean authenticate(LoginRequest request) {
// String userDn, String credentials
DirContext ctx = null;
String dn = null;
String username = request.getUsername();
String credentials = request.getPassword();
List user = personRepo.findByName(username);
if (user.size() > 0) {
System.out.println(user);
dn = personRepo.getDnForUser(username);
} else {
MSException.throwException("no such user");
}
try {
ldapTemplate.authenticate(query()
.where("objectclass").is("person")
.and("cn").is(username), credentials);
ctx = ldapTemplate.getContextSource().getContext(dn, credentials);
// ldapTemplate.authenticate(dn, credentials);
// Take care here - if a base was specified on the ContextSource
// that needs to be removed from the user DN for the lookup to succeed.
// ctx.lookup(userDn);
@ -45,10 +47,11 @@ public class LdapService {
} catch (Exception e) {
// Context creation failed - authentication did not succeed
System.out.println("Login failed: " + e);
MSException.throwException("login failed...");
return false;
} finally {
// It is imperative that the created DirContext instance is always closed
// LdapUtils.closeContext((LdapContext) ctx);
LdapUtils.closeContext((LdapContext) ctx);
}
}
}

View File

@ -8,4 +8,6 @@ public interface PersonRepo {
List<String> getAllPersonNames();
List findByName(String name);
String getDnForUser(String name);
}

View File

@ -2,17 +2,13 @@ package io.metersphere.ldap;
import io.metersphere.ldap.domain.Person;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.*;
import org.springframework.ldap.core.support.AbstractContextMapper;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.ldap.LdapContext;
import java.util.List;
@ -44,11 +40,30 @@ public class PersonRepoImpl implements PersonRepo {
public List findByName(String name) {
ldapTemplate.setIgnorePartialResultException(true);
LdapQuery query = query()
.where("objectclass").is("person")
.and("cn").is(name);
// .where("objectclass").is("person")
// .and("cn").is(name);
.where("cn").is(name);
return ldapTemplate.search(query, getContextMapper());
}
@Override
public String getDnForUser(String uid) {
List<String> result = ldapTemplate.search(
query().where("cn").is(uid),
new AbstractContextMapper() {
@Override
protected String doMapFromContext(DirContextOperations ctx) {
return ctx.getNameInNamespace();
}
});
if(result.size() != 1) {
throw new RuntimeException("User not found or not unique");
}
return result.get(0);
}
protected ContextMapper getContextMapper() {
return new PersonContextMapper();
}
@ -64,21 +79,4 @@ public class PersonRepoImpl implements PersonRepo {
}
}
// public boolean authenticate(String userDn, String credentials) {
// DirContext ctx = null;
// try {
// ctx = ldapTemplate.getContextSource().getContext(userDn, credentials);
// // Take care here - if a base was specified on the ContextSource
// // that needs to be removed from the user DN for the lookup to succeed.
//// ctx.lookup(userDn);
// return true;
// } catch (Exception e) {
// // Context creation failed - authentication did not succeed
// System.out.println("Login failed: " + e);
// return false;
// } finally {
// // It is imperative that the created DirContext instance is always closed
// LdapUtils.closeContext((LdapContext) ctx);
// }
// }
}

View File

@ -1,23 +1,14 @@
package io.metersphere.ldap.controller;
import io.metersphere.base.domain.UserRole;
import io.metersphere.base.domain.User;
import io.metersphere.controller.ResultHolder;
import io.metersphere.controller.request.LoginRequest;
import io.metersphere.dto.UserDTO;
import io.metersphere.i18n.Translator;
import io.metersphere.ldap.LdapService;
import io.metersphere.ldap.PersonRepoImpl;
import io.metersphere.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import static io.metersphere.commons.constants.SessionConstants.ATTR_USER;
@ -25,34 +16,34 @@ import static io.metersphere.commons.constants.SessionConstants.ATTR_USER;
@RequestMapping("/ldap")
public class LdapController {
@Resource
private PersonRepoImpl personRepo;
@Resource
private UserService userService;
@Resource
private LdapService ldapService;
@GetMapping("/test")
public List<String> test() {
return personRepo.getAllPersonNames();
}
@GetMapping("/find/{name}")
public List test(@PathVariable String name) {
return personRepo.findByName(name);
}
@GetMapping("/testUser")
public void testUser() {
// TODO LDAP 认证
// personRepo.authenticate("Administrator@fit2cloud.com", "Calong@2015");
}
@PostMapping(value = "/signin")
public ResultHolder login(@RequestBody LoginRequest request) {
// TODO 1. LDAP 认证 2. 认证之后 重新登录系统 3. 执行其它
ldapService.authenticate(request);
SecurityUtils.getSubject().getSession().setAttribute("authenticate", "ldap");
String username = request.getUsername();
String password = request.getPassword();
User u = userService.selectUser(request.getUsername());
if (u == null) {
User user = new User();
user.setId(username);
user.setName(username);
// todo user email ?
user.setEmail(username + "@fit2cloud.com");
user.setPassword(password);
userService.createUser(user);
} else {
request.setUsername(u.getId());
request.setPassword(u.getPassword());
}
return userService.login(request);
}

View File

@ -8,6 +8,7 @@ import io.metersphere.dto.UserDTO;
import io.metersphere.i18n.Translator;
import io.metersphere.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
@ -89,6 +90,14 @@ public class ShiroDBRealm extends AuthorizingRealm {
SessionUtils.putUser(sessionUser);
return new SimpleAuthenticationInfo(userId, password, getName());
}
String login = (String) SecurityUtils.getSubject().getSession().getAttribute("authenticate");
if (StringUtils.equals(login, "ldap")) {
SessionUser sessionUser = SessionUser.fromUser(user);
SessionUtils.putUser(sessionUser);
return new SimpleAuthenticationInfo(userId, password, getName());
}
// 密码验证
if (!userService.checkUserPassword(userId, password)) {
throw new IncorrectCredentialsException(Translator.get("password_is_incorrect"));

View File

@ -31,7 +31,6 @@ import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import javax.annotation.Resource;
import java.util.*;
@ -78,6 +77,10 @@ public class UserService {
return getUserDTO(user.getId());
}
public User selectUser(String id) {
return userMapper.selectByPrimaryKey(id);
}
private void insertUserRole(List<Map<String, Object>> roles, String userId) {
for (int i = 0; i < roles.size(); i++) {
Map<String, Object> map = roles.get(i);
@ -127,7 +130,7 @@ public class UserService {
// password
}
private void createUser(User userRequest) {
public void createUser(User userRequest) {
User user = new User();
BeanUtils.copyProperties(userRequest, user);
user.setCreateTime(System.currentTimeMillis());