当前位置:   article > 正文

spring-security 多类型用户登录+登录多参数验证_loaduserbyusername 怎么接收多个参数

loaduserbyusername 怎么接收多个参数

如果一个系统分为前台用户和后台用户那么就不能使用spring-security的默认配置了。 需要自己来分开配置两种用户的登录方式。

首先创建spring-disuser-security.xml 与 spring-etuser-security.xml 两个配置文件,分别来配置两种用户登录的权限与验证方式

spring-disuser-security.xml的内容如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xmlns:aop="http://www.springframework.org/schema/aop"
  9. xmlns:security="http://www.springframework.org/schema/security"
  10. xsi:schemaLocation="http://www.springframework.org/schema/beans
  11. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  14. http://www.springframework.org/schema/tx
  15. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  16. http://www.springframework.org/schema/context
  17. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  18. http://www.springframework.org/schema/security
  19. http://www.springframework.org/schema/security/spring-security-3.1.xsd">
  20. <!-- 使用自定义Filter时需要将http节点的auto-config="true"属性删除,并且要通过entry-point-ref指定一个入口 -->
  21. <security:http use-expressions="true" access-denied-page="/powermiss.jsp"
  22. authentication-manager-ref="disuserAuthManager" name="disuserSecurity"
  23. entry-point-ref="authenticationEntryPoint">
  24. <security:intercept-url pattern="/disuserlogin.jsp" access="permitAll"/>
  25. <!-- 配置自定义的Filter,并且将其放在FORM_LOGIN_FILTER节点,就会替换掉原来的FORM_LOGIN_FILTER节点 -->
  26. <security:custom-filter ref="loginProcessFilter" position="FORM_LOGIN_FILTER"/>
  27. </security:http>
  28. <security:authentication-manager id="disuserAuthManager" >
  29. <security:authentication-provider user-service-ref="DisuserserDetailService" />
  30. </security:authentication-manager>
  31. <!-- 登录处理Filter -->
  32. <bean id="loginProcessFilter" class="com.tuanfang.service.DisUsernamePasswordAuthenticationFilter">
  33. <property name="loginid" value="loginid" />
  34. <property name="yzm" value="yzm" />
  35. <property name="usernameParameter" value="username" />
  36. <property name="passwordParameter" value="password" />
  37. <property name="filterProcessesUrl" value="/disuserlogin.htm" />
  38. <property name="authenticationManager" ref="disuserAuthManager" />
  39. <property name="authenticationSuccessHandler" ref="successHandler" />
  40. <property name="authenticationFailureHandler" ref="failureHandler" />
  41. </bean>
  42. <!-- 登录成功处理 -->
  43. <bean id="successHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
  44. <property name="defaultTargetUrl" value="/index.jsp" />
  45. <property name="alwaysUseDefaultTargetUrl" value="true" />
  46. </bean>
  47. <!-- 登录失败处理 -->
  48. <bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
  49. <property name="defaultFailureUrl" value="/disuserlogin.jsp?error=true" />
  50. </bean>
  51. <!-- 登录入口 -->
  52. <bean id="authenticationEntryPoint"
  53. class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
  54. <property name="loginFormUrl" value="/disuserlogin.jsp" />
  55. </bean>
  56. </beans>


接下来编写DisUsernamePasswordAuthenticationFilter.java文件,处理用户登录。

spring-security默认的处理登录的类是org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter,可以将其中的代码复制到自己写的DisUsernamePasswordAuthenticationFilter.java文件中。

然后在进行自己的修改,达到验证验证码,与公司登录id的验证。

  1. /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. package com.tuanfang.service;
  16. import javax.servlet.http.HttpServletRequest;
  17. import javax.servlet.http.HttpServletResponse;
  18. import org.springframework.security.authentication.AuthenticationServiceException;
  19. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  20. import org.springframework.security.core.Authentication;
  21. import org.springframework.security.core.AuthenticationException;
  22. import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
  23. import org.springframework.util.Assert;
  24. /**
  25. * Processes an authentication form submission. Called {@code AuthenticationProcessingFilter} prior to Spring Security
  26. * 3.0.
  27. * <p>
  28. * Login forms must present two parameters to this filter: a username and
  29. * password. The default parameter names to use are contained in the
  30. * static fields {@link #SPRING_SECURITY_FORM_USERNAME_KEY} and {@link #SPRING_SECURITY_FORM_PASSWORD_KEY}.
  31. * The parameter names can also be changed by setting the {@code usernameParameter} and {@code passwordParameter}
  32. * properties.
  33. * <p>
  34. * This filter by default responds to the URL {@code /j_spring_security_check}.
  35. *
  36. * @author Ben Alex
  37. * @author Colin Sampaleanu
  38. * @author Luke Taylor
  39. * @since 3.0
  40. */
  41. public class DisUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  42. //~ Static fields/initializers =====================================================================================
  43. public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
  44. public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
  45. public static final String SPRING_SECURITY_FORM_YZM_KEY = "yzm";
  46. public static final String SPRING_SECURITY_FORM_LOGINID_KEY = "loginid";
  47. public static final String USERNAME_LOGINID_SPLIT = "/";
  48. /**
  49. * @deprecated If you want to retain the username, cache it in a customized {@code AuthenticationFailureHandler}
  50. */
  51. @Deprecated
  52. public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
  53. private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
  54. private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
  55. private String yzm = SPRING_SECURITY_FORM_YZM_KEY;
  56. private String loginid = SPRING_SECURITY_FORM_LOGINID_KEY;
  57. private boolean postOnly = true;
  58. //~ Constructors ===================================================================================================
  59. public DisUsernamePasswordAuthenticationFilter() {
  60. super("/j_spring_security_check");
  61. }
  62. //~ Methods ========================================================================================================
  63. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  64. if (postOnly && !request.getMethod().equals("POST")) {
  65. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  66. }
  67. String username = obtainUsername(request);
  68. String password = obtainPassword(request);
  69. String loginid = obtainLoginid(request);
  70. String yzm = obtainYzm(request);
  71. if (username == null) {
  72. username = "";
  73. }
  74. if (password == null) {
  75. password = "";
  76. }
  77. if (loginid == null) {
  78. loginid = "";
  79. }
  80. if (yzm == null) {
  81. yzm = "";
  82. }
  83. username = username.trim();
  84. password = password.trim();
  85. loginid = loginid.trim();
  86. yzm = yzm.trim();
  87. username = loginid + USERNAME_LOGINID_SPLIT + username ; //将公司登录id与登录用户名使用 / 连接起来
  88. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
  89. // Allow subclasses to set the "details" property
  90. setDetails(request, authRequest);
  91. return this.getAuthenticationManager().authenticate(authRequest);
  92. }
  93. /**
  94. * Enables subclasses to override the composition of the password, such as by including additional values
  95. * and a separator.<p>This might be used for example if a postcode/zipcode was required in addition to the
  96. * password. A delimiter such as a pipe (|) should be used to separate the password and extended value(s). The
  97. * <code>AuthenticationDao</code> will need to generate the expected password in a corresponding manner.</p>
  98. *
  99. * @param request so that request attributes can be retrieved
  100. *
  101. * @return the password that will be presented in the <code>Authentication</code> request token to the
  102. * <code>AuthenticationManager</code>
  103. */
  104. protected String obtainPassword(HttpServletRequest request) {
  105. return request.getParameter(passwordParameter);
  106. }
  107. //获取验证码
  108. protected String obtainYzm(HttpServletRequest request){
  109. return request.getParameter(yzm);
  110. }
  111. //获取公司id
  112. protected String obtainLoginid(HttpServletRequest request){
  113. return request.getParameter(loginid);
  114. }
  115. /**
  116. * Enables subclasses to override the composition of the username, such as by including additional values
  117. * and a separator.
  118. *
  119. * @param request so that request attributes can be retrieved
  120. *
  121. * @return the username that will be presented in the <code>Authentication</code> request token to the
  122. * <code>AuthenticationManager</code>
  123. */
  124. protected String obtainUsername(HttpServletRequest request) {
  125. return request.getParameter(usernameParameter);
  126. }
  127. /**
  128. * Provided so that subclasses may configure what is put into the authentication request's details
  129. * property.
  130. *
  131. * @param request that an authentication request is being created for
  132. * @param authRequest the authentication request object that should have its details set
  133. */
  134. protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
  135. authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
  136. }
  137. /**
  138. * Sets the parameter name which will be used to obtain the username from the login request.
  139. *
  140. * @param usernameParameter the parameter name. Defaults to "j_username".
  141. */
  142. public void setUsernameParameter(String usernameParameter) {
  143. Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
  144. this.usernameParameter = usernameParameter;
  145. }
  146. /**
  147. * Sets the parameter name which will be used to obtain the password from the login request..
  148. *
  149. * @param passwordParameter the parameter name. Defaults to "j_password".
  150. */
  151. public void setPasswordParameter(String passwordParameter) {
  152. Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
  153. this.passwordParameter = passwordParameter;
  154. }
  155. /**
  156. * Defines whether only HTTP POST requests will be allowed by this filter.
  157. * If set to true, and an authentication request is received which is not a POST request, an exception will
  158. * be raised immediately and authentication will not be attempted. The <tt>unsuccessfulAuthentication()</tt> method
  159. * will be called as if handling a failed authentication.
  160. * <p>
  161. * Defaults to <tt>true</tt> but may be overridden by subclasses.
  162. */
  163. public void setPostOnly(boolean postOnly) {
  164. this.postOnly = postOnly;
  165. }
  166. public final String getUsernameParameter() {
  167. return usernameParameter;
  168. }
  169. public final String getPasswordParameter() {
  170. return passwordParameter;
  171. }
  172. public String getYzm() {
  173. return yzm;
  174. }
  175. public void setYzm(String yzm) {
  176. this.yzm = yzm;
  177. }
  178. public String getLoginid() {
  179. return loginid;
  180. }
  181. public void setLoginid(String loginid) {
  182. this.loginid = loginid;
  183. }
  184. }


接下来编写提供Disuser的UserDetailsService类

  1. package com.tuanfang.service;
  2. import java.math.BigInteger;
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.List;
  6. import javax.annotation.Resource;
  7. import org.springframework.security.core.GrantedAuthority;
  8. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  9. import org.springframework.security.core.userdetails.User;
  10. import org.springframework.security.core.userdetails.UserDetails;
  11. import org.springframework.security.core.userdetails.UserDetailsService;
  12. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  13. import org.springframework.stereotype.Repository;
  14. import com.tuanfang.dao.impl.DisuserDaoImpl;
  15. import com.tuanfang.dao.impl.SysPowrDaoImpl;
  16. import com.tuanfang.pojo.Disuser;
  17. import com.tuanfang.pojo.SysPower;
  18. @Repository("DisuserserDetailService")
  19. public class DisuserserDetailService implements UserDetailsService{
  20. @Resource(name="DisuserDaoImpl")
  21. private DisuserDaoImpl disuserDao ;
  22. @Resource(name="SysPowrDaoImpl")
  23. private SysPowrDaoImpl sysPowrDao ;
  24. @Override
  25. public UserDetails loadUserByUsername(String usernameAndloginId)
  26. throws UsernameNotFoundException {
  27. //将公司登录id与登录用户名使用/分开
  28. String args[] = usernameAndloginId.split(DisUsernamePasswordAuthenticationFilter.USERNAME_LOGINID_SPLIT);
  29. String loginid = args[0];
  30. String username = args[1];
  31. Disuser disuser = disuserDao.findByLoginIdAndUserName(loginid , username);
  32. UserDetails userDetail = null ;
  33. if(disuser != null){
  34. userDetail = new User(username, disuser.getPassword(),disuser.getStatus() ==Disuser.ENABLE ,
  35. true, true, true, obtainUserPowers(disuser.getId()));
  36. }
  37. return userDetail;
  38. }
  39. public Collection<GrantedAuthority> obtainUserPowers(BigInteger userId){
  40. Collection<GrantedAuthority> gas = new ArrayList<GrantedAuthority>();
  41. List<SysPower> powers = sysPowrDao.findDisuserPowers(userId);
  42. if(powers != null && powers.size() > 0){
  43. for (SysPower sysPower : powers) {
  44. gas.add(new SimpleGrantedAuthority(sysPower.getCode()));
  45. }
  46. }
  47. gas.add(new SimpleGrantedAuthority("HAVE_LOGIN")); //登录
  48. return gas ;
  49. }
  50. }


登录页面disuserlogin.jsp

  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <%
  7. String path = request.getContextPath();
  8. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  9. %>
  10. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  11. <title>DisuserLogin</title>
  12. </head>
  13. <body>
  14. <form action="<%=basePath %>disuserlogin.htm" method="post">
  15. <p>
  16. <label for="username">Username</label> <input id="username"
  17. name="username" type="text" />
  18. </p>
  19. <p>
  20. <label for="password">password</label> <input id="password"
  21. name="password" type="password" />
  22. </p>
  23. <p>
  24. <label for="loginid">LoginId</label> <input id="loginid"
  25. name="loginid" type="text" />
  26. </p>
  27. <p>
  28. <label for="yzm">验证码</label> <input id="yzm"
  29. name="yzm" type="text" />
  30. </p>
  31. <input type="submit" value="Login" />
  32. </form>
  33. </body>
  34. </html>




这样就配置好了Disuser的login



接下来配置EtdsUser的login。只需要username与password

spring-etuser-security.xml文件内容如下(使用spring-security默认的方式配置):

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xmlns:aop="http://www.springframework.org/schema/aop"
  9. xmlns:security="http://www.springframework.org/schema/security"
  10. xsi:schemaLocation="http://www.springframework.org/schema/beans
  11. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  14. http://www.springframework.org/schema/tx
  15. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  16. http://www.springframework.org/schema/context
  17. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  18. http://www.springframework.org/schema/security
  19. http://www.springframework.org/schema/security/spring-security-3.1.xsd">
  20. <security:http auto-config="true" pattern="/admin/**" use-expressions="true" access-denied-page="/powermiss.jsp"
  21. authentication-manager-ref="etuserAuthManager" name="etuserSecurity">
  22. <security:intercept-url pattern="/admin/etuserlogin.jsp" access="permitAll"/>
  23. <security:form-login login-processing-url="/admin/j_spring_security_check" authentication-failure-url="/admin/etuserlogin.jsp?error=true" login-page="/admin/etuserlogin.jsp"
  24. default-target-url="/index.jsp" />
  25. </security:http>
  26. <security:authentication-manager id="etuserAuthManager" >
  27. <security:authentication-provider user-service-ref="EtuserDetailService"/>
  28. </security:authentication-manager>
  29. </beans>

Etdsuser的UserDetailsService类如下:

  1. package com.tuanfang.service;
  2. import java.math.BigInteger;
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.List;
  6. import javax.annotation.Resource;
  7. import org.springframework.security.core.GrantedAuthority;
  8. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  9. import org.springframework.security.core.userdetails.User;
  10. import org.springframework.security.core.userdetails.UserDetails;
  11. import org.springframework.security.core.userdetails.UserDetailsService;
  12. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  13. import org.springframework.stereotype.Repository;
  14. import com.tuanfang.dao.impl.EtdsuserDaoImpl;
  15. import com.tuanfang.dao.impl.SysPowrDaoImpl;
  16. import com.tuanfang.pojo.EtdsUser;
  17. import com.tuanfang.pojo.SysPower;
  18. @Repository("EtuserDetailService")
  19. public class EtuserDetailService implements UserDetailsService{
  20. @Resource(name="EtdsuserDaoImpl")
  21. private EtdsuserDaoImpl etdsuserDao ;
  22. @Resource(name="SysPowrDaoImpl")
  23. private SysPowrDaoImpl sysPowrDao ;
  24. @Override
  25. public UserDetails loadUserByUsername(String username)
  26. throws UsernameNotFoundException {
  27. EtdsUser etuser = etdsuserDao.findUserByLoginName(username);
  28. UserDetails userDetail = null ;
  29. if(etuser != null){
  30. userDetail = new User(username, etuser.getPassword(),etuser.getStatus() ==EtdsUser.ENABLE ,
  31. true, true, true, obtainUserPowers(etuser.getId()));
  32. }
  33. return userDetail;
  34. }
  35. public Collection<GrantedAuthority> obtainUserPowers(BigInteger userId){
  36. Collection<GrantedAuthority> gas = new ArrayList<GrantedAuthority>();
  37. List<SysPower> powers = sysPowrDao.findEtuserPowers(userId);
  38. if(powers != null && powers.size() > 0){
  39. for (SysPower sysPower : powers) {
  40. gas.add(new SimpleGrantedAuthority(sysPower.getCode()));
  41. }
  42. }
  43. gas.add(new SimpleGrantedAuthority("HAVE_LOGIN")); //登录
  44. return gas ;
  45. }
  46. }

然后在applicationContext.xml中导入spring-disuser-security.xml与spring-etuser-security.xml


<import resource="spring-etuser-security.xml"/>
<import resource="spring-disuser-security.xml"/>




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/481612
推荐阅读
相关标签
  

闽ICP备14008679号