【问题标题】:Spring Security ConfigurationSpring 安全配置
【发布时间】:2013-10-22 04:15:25
【问题描述】:

在发布问题之前我已经阅读了许多关于 Spring Security 的主题,但仍然无法解决。

我正在尝试配置自定义的 spring 安全性,即拥有一个执行身份验证的服务类 (UserService)。但是,要么它无法访问 UserService。我试图只把相关的代码 sn-p 放在下面:

我已更新异常日志

Web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
                /WEB-INF/spring/root-context.xml
    </param-value>
</context-param>

<filter>
     <filter-name>springSecurityFilterChain</filter-name>
     <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
     </filter-class>
 </filter>

<filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

appServlet-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"   
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">



<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

 <context:component-scan base-package="com.autoshipcart.service, com.autoshipcart.serviceImpl, com.autoshipcart.dao, com.autoshipcart.admin, com.autoshipcart.admin.service, com.autoshipcart.admin.serviceImpl, com.autoshipcart.admin.dao, com.autoshipcart.admin.validator, com.autoshipcart.framework" />
 <context:annotation-config />

<beans:bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <beans:property name="basename" value="classpath:adminproperties/messages" />
    <beans:property name="defaultEncoding" value="UTF-8" />
</beans:bean>
<beans:bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <!-- one of the properties available; the maximum file size in bytes -->
   <beans:property name="maxUploadSize" value="50000000" />

   </beans:bean>

<beans:bean id="localeChangeInterceptor"
      class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <beans:property name="paramName" value="siteLanguage"/>
</beans:bean>

<beans:bean id="localeResolver"
      class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>

root-context.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"   
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">


<!-- Root Context: defines shared resources visible to all other web components -->
    <context:component-scan base-package="com.autoshipcart.service, com.autoshipcart.serviceImpl, com.autoshipcart.dao, com.autoshipcart.admin, com.autoshipcart.admin.service, com.autoshipcart.admin.serviceImpl, com.autoshipcart.admin.dao, com.autoshipcart.admin.validator, com.autoshipcart.framework" />
    <context:annotation-config />

    <bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:adminproperties/jdbc.properties</value>
            <value>classpath:adminproperties/mail.properties</value>

       </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true"/>        
</bean>

<bean id="dataSourceMaster"
    class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${master.jdbc.driverClassName}"/>
    <property name="url" value="${master.jdbc.databaseurl}"/>
    <property name="username" value="${master.jdbc.username}"/>
    <property name="password" value="${master.jdbc.password}"/>
</bean>

<bean id="dataSourceCart1"
    class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${cart1.jdbc.driverClassName}"/>
    <property name="url" value="${cart1.jdbc.databaseurl}"/>
    <property name="username" value="${cart1.jdbc.username}"/>
    <property name="password" value="${cart1.jdbc.password}"/>
</bean>

<bean id="sessionFactoryMaster"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSourceMaster" />
    <property name="configLocation">
        <value>classpath:hibernate.master.cfg.xml</value>
    </property>
    <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${master.jdbc.dialect}</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.connection.charSet">UTF-8</prop>
            <prop key="hibernate.cache">false</prop>                  
            <prop key="hibernate.cglib.use_reflection_optimizer">false</prop>  
            <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>  
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="hibernate.transaction.flush_before_completion">true</prop>  
        </props>
    </property>
</bean>

<bean id="sessionFactoryCart1"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSourceCart1" />
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
    <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${cart1.jdbc.dialect}</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.connection.charSet">UTF-8</prop>
            <prop key="hibernate.cache">false</prop>                  
            <prop key="hibernate.cglib.use_reflection_optimizer">false</prop>  
            <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>  
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="hibernate.transaction.flush_before_completion">true</prop>  
        </props>
    </property>
</bean>
    <tx:annotation-driven proxy-target-class="true" />
<bean id="transactionManagerMaster"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactoryMaster" />
</bean>
    <bean id="transactionManagerCart1"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactoryCart1" />
</bean>

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
    <property name="velocityProperties">
        <value>
            resource.loader=class
            class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
        </value>
    </property>
</bean>

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${mail.host}" />
    <property name="port" value="${mail.port}" />
    <property name="username" value="${mail.username}" />
    <property name="password" value="${mail.password}" />

    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
            <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
        </props>
    </property>

</bean>

<bean id="mailSenderUtil" class="com.autoshipcart.framework.util.MailSenderUtil">
    <property name="mailSender" ref="mailSender"></property>
</bean>


  <bean id="userService" class="com.autoshipcart.admin.serviceImpl.UserServiceImpl"></bean>
<bean id="userDAO" class="com.autoshipcart.admin.hibernatedao.UserHibernateDAO"></bean>

<!-- <bean id="webExpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/> -->



<security:http auto-config="true" use-expressions="false">


     <security:intercept-url pattern="/dashboard" access="IS_AUTHENTICATED_ANONYMOUSLY" />

    <security:form-login login-page="/login"
        login-processing-url="/static/j_spring_security_check"
        default-target-url="/dashboard" 
        authentication-failure-url="/logout"
         />         
 </security:http>

<security:authentication-manager>
    <security:authentication-provider user-service-ref="userService">
        <security:password-encoder hash="plaintext"/>
    </security:authentication-provider>
</security:authentication-manager>

UserServiceImpl.java

package com.autoshipcart.admin.serviceImpl;

/*@Service("userService")*/
@Transactional
public class UserServiceImpl implements UserService,UserDetailsService {

@Autowired
private UserDAO userDAO;


@Transactional
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException {
    System.out.println("test>>>>"+ username);
    System.out.println("test2>>>>"+ username);
    UserVO temp= new UserVO();
try{
    User user= userDAO.authenticateUser(username);
        if(user!=null){
            new UserVO();
        }else{          
            throw new UsernameNotFoundException("UserName or Password is incorrect!");
        }



temp.setEmail(user.getEmailId());
temp.setFirstName(user.getFirstName());
temp.setLastName(user.getLastName());
temp.setPassword(user.getPassword());
temp.setUsername(user.getUserName());

}catch(Exception e){
    e.printStackTrace();

}
    return temp;    
}

}

AdminController.java

    @RequestMapping(value = {"/","/dashboard"}, method = {RequestMethod.GET})
public String showDashboard(HttpSession session, 
        Map<String, Object> map, Model model) {
System.out.println("In controller>>");
        String loggedIn= (String) session.getAttribute("loggedIn"); // This job will be done by AOP Intercepor

        if(loggedIn==null)
                return "login";
            else
                return "dashboard";
}   


@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpSession session, HttpServletResponse response,
        Map<String, Object> map, Model model) {
    logger.info("logout function is called>>>>>");
    System.out.println("logout function is called");
    if(session.getAttribute("loggedIn")=="true"&&session.getAttribute("configMap")!=null)
    {    System.out.println("session");
        session.setAttribute("loggedIn", null);
        session.setAttribute("configMap", null);
        session.invalidate();
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        response.setDateHeader("Expires", 0); // Proxies.
    }
  return "login";//"redirect:/";
}   

我不再遇到任何异常。以下是我尝试登录时的日志:

调试:org.springframework.security.web.FilterChainProxy - /j_spring_security_check 在附加过滤器链中的第 10 个位置;触发过滤器:'SecurityContextPersistenceFilter' 调试:org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession 为 SPRING_SECURITY_CONTEXT 返回空对象 调试:org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession 没有可用的 SecurityContext:org.apache.catalina.session.StandardSessionFacade@6ab494c6。将创建一个新的。 调试:org.springframework.security.web.FilterChainProxy - /j_spring_security_check 在附加过滤器链中的第 10 位的第 2 位;触发过滤器:'LogoutFilter' 调试:org.springframework.security.web.FilterChainProxy - /j_spring_security_check 在附加过滤器链中的第 10 个位置;触发过滤器:'UsernamePasswordAuthenticationFilter' 调试:org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - 请求是处理身份验证 调试:org.springframework.security.authentication.ProviderManager - 使用 org.springframework.security.authentication.dao.DaoAuthenticationProvider 进行身份验证尝试 调试:org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - 身份验证请求失败:**

org.springframework.security.authentication.AuthenticationServiceException: 没有定义名为“transactionManager”的 bean

调试:org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - 更新 SecurityContextHolder 以包含空身份验证 调试:org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - 委托给身份验证失败处理程序org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@125e3283 调试:org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler - 重定向到 /logout 调试:org.springframework.security.web.DefaultRedirectStrategy - 重定向到'/ascartadmin/logout' 调试:org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext 为空或内容是匿名的 - 上下文不会存储在 HttpSession 中。 调试:org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder 现在清除,请求处理完成 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的第 10 个位置;触发过滤器:'SecurityContextPersistenceFilter' 调试:org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession 为 SPRING_SECURITY_CONTEXT 返回空对象 调试:org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession 没有可用的 SecurityContext:org.apache.catalina.session.StandardSessionFacade@6ab494c6。将创建一个新的。 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的第 10 个位置;触发过滤器:'LogoutFilter' 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的第 10 个位置;触发过滤器:'UsernamePasswordAuthenticationFilter' 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的第 10 位的位置;触发过滤器:'BasicAuthenticationFilter' 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的 10 位置 5;触发过滤器:'RequestCacheAwareFilter' 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的第 10 位中的 10 位;触发过滤器:'SecurityContextHolderAwareRequestFilter' 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的第 10 个位置;触发过滤器:'AnonymousAuthenticationFilter' 调试:org.springframework.security.web.authentication.AnonymousAuthenticationFilter - 使用匿名令牌填充 SecurityContextHolder:'org.springframework.security.authentication.AnonymousAuthenticationToken@6fa90ed4:主体:anonymousUser;凭证:[受保护];已认证:真实;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c:RemoteIpAddress:0:0:0:0:0:0:0:1;会话ID:1CCAA9863B99B4E75D065F26D664ADE5;授予权限:ROLE_ANONYMOUS' 调试: org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的 10 位中的第 8 位;触发过滤器:'SessionManagementFilter' 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的 10 位置 9;触发过滤器:'ExceptionTranslationFilter' 调试:org.springframework.security.web.FilterChainProxy - /logout 在附加过滤器链中的第 10 个位置,共 10 个;触发过滤器:'FilterSecurityInterceptor' 调试:org.springframework.security.web.util.AntPathRequestMatcher - 检查请求的匹配:'/logout';反对“/仪表板” 调试:org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 公共对象 - 未尝试身份验证 调试:org.springframework.security.web.FilterChainProxy - /logout 到达附加过滤器链的末尾;继续原链 INFO : com.autoshipcart.admin.controller.AdminController - 注销功能被调用>>>>> 注销功能被调用 DEBUG: org.springframework.security.web.access.ExceptionTranslationFilter - 链处理正常 调试:org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext 为空或内容是匿名的 - 上下文不会存储在 HttpSession 中。 调试:org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder 现在清除,请求处理完成

【问题讨论】:

  • 没有为依赖找到类型为 [com.autoshipcart.framework.ConfigurationLoader] 的匹配 bean:预计至少有 1 个 bean 符合此依赖的自动装配候选条件...?你能在这里发布 ConfigurationLoader 类吗
  • 我查过了。它没有@Component。我添加了它。下面是更新后的 ConfigurationLoader 类和新的异常:由于字符限制,无法添加。
  • 由于字符限制,我无法粘贴它。我做了一些更改,现在我要启动服务器,但有任何例外。但是,我自定义的 UserServiceImpl 没有启动。 经理>。一旦我输入用户名/密码,它就会重定向到注销,甚至触摸 userserviceimpl。
  • 希望对您有所帮助java2practice.com/2013/07/22/…
  • 非常感谢您的链接。这是一篇很棒的文章。但是,即使根据文章调整了我的代码,它的行为也相似。看来,它没有识别我定制的 userserviceimpl。一旦我输入凭据,它就会直接重定向到注销。请查看日志: INFO: Server startup in 13626 ms INFO : com.autoshipcart.admin.controller.AdminController - logout function is called>>>>> logout function is called

标签: spring spring-security


【解决方案1】:

您在安全配置中的登录处理 url 是 login-processing-url="/static/j_spring_security_check" 为什么你在这个url后面加了static,spring默认是/j_spring_security_check,去掉static关键字后试试

【讨论】:

  • 我做到了。它没有帮助。请检查我更新的日志。 TransactionManager 似乎有问题。
猜你喜欢
  • 2013-12-06
  • 2019-04-03
  • 2013-08-23
  • 1970-01-01
  • 2014-02-05
  • 2013-07-07
  • 2015-11-18
相关资源
最近更新 更多