spring secrity ldap

网友投稿 636 2022-05-30

spring 4 没有使用spring-boot,也不想退到spring3

ldap manager的密码加密方案

---继承DefaultSpringSecurityContextSource,然后在里面使用 jasypt解密,感觉可行

---附件:jasypt工具

参考文档:

https://stackoverflow.com/questions/22067552/encryption-decrypt-using-jasypt

https://docs.spring.io/spring-security/site/docs/4.2.11.RELEASE/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html

http://www.sephiroth-j.de/java/spring-security-ltpa2/usage.html

https://github.com/spring-projects/spring-security-kerberos

https://github.com/spring-projects/spring-security-kerberos/blob/master/spring-security-kerberos-client/src/main/java/org/springframework/security/kerberos/client/ldap/KerberosLdapContextSource.java

https://docs.spring.io/spring-security/site/docs/4.0.x/reference/html/ldap.html

https://spring.io/guides/gs/authenticating-ldap/

https://memorynotfound.com/spring-security-spring-ldap-authentication-example/

https://stackoverflow.com/questions/20149939/encrypting-a-password-within-a-spring-configuration-file

https://stackoverflow.com/questions/33952246/how-to-avoid-plain-text-ldap-password-in-spring-security

https://serverfault.com/questions/271872/hudson-how-to-manually-encode-the-ldap-managerpassword

https://github.com/spring-projects/spring-security/blob/master/crypto/src/main/java/org/springframework/security/crypto/password/LdapShaPasswordEncoder.java

https://www.mkyong.com/spring-security/spring-security-password-hashing-example/

https://stackoverflow.com/questions/52647983/spring-security-without-ldap-password

https://blog.csdn.net/gdfsbingfeng/article/details/16886805

https://stackoverflow.com/questions/32244500/jasypt-with-spring-4-0

http://www.jasypt.org/springsecurity.html

https://www.baeldung.com/spring-boot-jasypt

https://stackoverflow.com/questions/23235314/spring-4-javaconfig-for-jasypt-and-profile

https://suryanarayanjena.wordpress.com/jasypt/

https://monibu1548.github.io/2017/02/09/jasypt/

https://github.com/spring-projects/spring-security/blob/master/ldap/src/main/java/org/springframework/security/ldap/DefaultSpringSecurityContextSource.java

https://github.com/ulisesbocchio/jasypt-spring-boot/issues/58

https://github.com/tfredrich/jasypt/issues/1

spring 配置多auth

https://www.programmergate.com/spring-boot-spring-security-oauth2/

https://blog.csdn.net/li90hou/article/details/77851845

https://geeks18.com/spring-security-password-configurations/

http://www.giuseppeurso.eu/en/multiple-authentication-providers-in-spring-security/

https://coderanch.com/t/653951/frameworks/Spring-Boot-Security-Config-Multiple

https://blog.csdn.net/wei_ya_wen/article/details/8529000

https://guides.micronaut.io/micronaut-database-authentication-provider-groovy/guide/index.html

https://stackoverflow.com/questions/25729008/using-both-ldap-and-db-authentication-with-spring-security

https://stackoverflow.com/questions/22115493/pre-authentication-without-authorization-using-spring-security/25114782#25114782

https://www.baeldung.com/spring-security-multiple-auth-providers

spring ldap配置

web.xml中添加

contextConfigLocation /WEB-INF/spring/root-context.xml, /WEB-INF/spring/spring-security.xml     springSecurityFilterChain     org.springframework.web.filter.DelegatingFilterProxy     springSecurityFilterChain     /*

spring-security.xml

                                                                                                                                                                                                                                                                                                                                                                                                 sAMAccountName={0}                                                                                                                                                                                             

AuthenticationFailureHandlerImpl.java//认证失败后的回调

public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler{ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException exception) throws IOException, ServletException {    // AuthenticationException 存放着异常信息,获取出来,放到 Request 中,转发到登录页面。         request.setAttribute("error", exception.getMessage());         request.getRequestDispatcher("/xxx/login").forward(request, response); } }

AuthenticationSuccessHandlerImpl.java//认证成功后的回调

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {     @Resource     private UserMapper userMapper;     @Override     public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,             Authentication authentication) throws IOException, ServletException {         // UserDetails 中存放着用户名等信息         //UserDetails userDetails = (UserDetails) authentication.getPrincipal();         // 获取该用户信息,根据自己的业务规则写         //User user = this.userMapper.getUserByUserName(username);     List info = new ArrayList(((LdapUserDetailsImpl)authentication.getPrincipal()).getAuthorities());     User user = new User();     user.setMail(info.get(0).toString());     ...     if(info.size()<7) {        user.setId(info.get(3).toString().hashCode());     }else {        user.setId(Integer.parseInt(info.get(6).toString()));     }         // 将用户放到 Session     //userMapper.insert(user);         request.getSession().setAttribute("currUser", user);         // 跳转到主页         String redirect = request.getParameter("redirect");         if(redirect.contains("/xxx/index.html")) {         response.sendRedirect(request.getContextPath() + "/xxx/xxxHome.html#!/index");         }else {         redirect = UriUtils.decode(redirect, "UTF-8");         response.sendRedirect(redirect);//request.getContextPath() +         }     } }

ContinueEntryPoint.java//保存认证前请求的链接 以便认证成功后跳转 (有一点#hashcode要在前端转义)

public class ContinueEntryPoint extends LoginUrlAuthenticationEntryPoint { public ContinueEntryPoint(String loginFormUrl) {         super(loginFormUrl);     }     @Override     protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response,             AuthenticationException exception) {         String continueParamValue=""; try { continueParamValue = UriUtils.encode(buildHttpReturnUrlForRequest(request),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }//UrlUtils.buildRequestUrl         String redirect = super.determineUrlToUseForThisRequest(request, response, exception);//         String ret = UriComponentsBuilder.fromPath(redirect).queryParam("redirect", continueParamValue).toUriString();         return ret;     }     protected String buildHttpReturnUrlForRequest(HttpServletRequest request) {             RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();             urlBuilder.setScheme("http");             urlBuilder.setServerName(request.getServerName());             ....             return urlBuilder.getUrl();     } }

CustomLdapAuthoritiesPopulator.java//构造用户信息--这段代码有点挫

public class CustomLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {    @Resource    private UserMapper userMapper;    public Collection getGrantedAuthorities( DirContextOperations context, String username) {                ArrayList list = new ArrayList();         String mail=context.getStringAttribute("mail")!=null?context.getStringAttribute("mail"):"nonemail";        ...         list.add((new SimpleGrantedAuthority(mail)));         ....         if(id==null) {         User user = new User();         user.setMail(mail);         ...             // 将用户放到 Session         userMapper.insert(user);         id = user.getId();         }         list.add(new SimpleGrantedAuthority(String.valueOf(id)));         return list;             } }

xxxcontroller.java//相关控制器

@RequestMapping(value="login" , method={ RequestMethod.GET, RequestMethod.POST }, name="login") public String login( ModelMap model,HttpServletRequest request) throws Exception { logger.info("params::::" + request.getRequestURI()); String redirect=request.getParameter("redirect"); model.addAttribute("redirect", redirect); return "xxx/employee-jsons/login"; } @RequestMapping(value="employee-jsons/logout.action" , method=RequestMethod.POST, name="logout") @ResponseBody public Map logout( HttpServletRequest request, HttpServletResponse response) throws Exception { logger.info("params::::" + request.getRequestURI());     Map ret = new HashMap();     ret.put("ajaxResult","success");     Authentication auth = SecurityContextHolder.getContext().getAuthentication();     if (auth != null){             new SecurityContextLogoutHandler().logout(request, response, auth);     }     return ret; }

spring同时配置db和ldap验证

spring-security.xml中添加过滤器

                                                                                                                   

clientDetailsUserDetailsService.java

@Service public class clientDetailsUserDetailsService implements UserDetailsService { @Autowired protected LdapService LdapService; public UserDetails loadUserByUsername(String input) throws UsernameNotFoundException {        String[] split = input.split(":");     User user = null;     if(split.length>=4) {         String u = split[0];         String passwd = split[1];         String uid = split[2];         String uname = split[3];     UserDetails userDetails = null;  List> info = null; if(uid!=null && !uid.isEmpty()) { info = LdapService.selectLdapUsersOri(uid); } if(info.size()>0) { user = new User(); String mail = info.get(0).get("mail").toString(); user.setMail(mail); ....         list.add((new SimpleGrantedAuthority(mail)));                 ....     user.setAuthorities(list);     return user; }     }     if(user == null)     {         throw new UsernameNotFoundException("Invalid username or corporate domain");     } return null;  } }

spring secrity ldap

TwoFactorAuthenticationFilter.java//我这块db验证的场景比较特殊 只有一个特定的账号信息放行

public class TwoFactorAuthenticationFilter extends UsernamePasswordAuthenticationFilter {     @Override     protected String obtainUsername(HttpServletRequest request)     {         String user = request.getParameter("user");         String passwd = request.getParameter("passwd");         String uid = xxx;         String uname = xxx;           String combinedUsername = user + ":" + passwd + ":" + uid + ":" + uname;         request.setAttribute("username","...");         request.setAttribute("password","...");         return combinedUsername;     } }

MyMessageDigestPasswordEncoder.java

public class MyMessageDigestPasswordEncoder extends MessageDigestPasswordEncoder  { public MyMessageDigestPasswordEncoder(String algorithm) {         super(algorithm);     }     @Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) {        /* if(StringUtils.isEmpty(rawPass)) {             throw new BadCredentialsException("密码不能为空");         }         return encPass.equals(rawPass);*/     return true;  } }

附件: nginx-1.14.2.zip 1.41M 下载次数:1次

附件: jasypt-1.9.2-dist.zip 6.95M 下载次数:0次

登录 Spring

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:软件论道一:能力与复杂度
下一篇:Apache Flink On Yarn模式高可用(HA)集群部署
相关文章