2013-02-28 3 views
2

как описано выше, у меня есть веб-приложение в Spring MVC, в котором следующие ARE рабочая:Spring MVC + Spring Security + JPA возвращает Null ModelAndView и не будет проверять подлинность

  • а 'игрушка' версия аутентификации на фиктивной странице без активов js/img/css/png
  • URL-адрес в контроллере. Итак: http://myhost/myapp/login и http://myhost/myapp/homepage/* все подавайте страницы
  • Hibernate/JPA интеграция
  • словом, все, кроме того, что, в странице входа в полном жира с активами, даже когда я ставлю в правильном имени пользователя/пасс комбинации, то аутентификация отклоняется & перенаправляет URL-адрес ошибки аутентификации.

(Spring 3.2, Spring Security 3.1.3 Я использую аутентификацию на основе XML на данный момент - см. Ниже - так что ничего общего с частью Hibernate/JPA, я думаю, что это исключительно проблема с тем, ве настроить Spring)

Мои вопросы, то есть два:

  • является .png файл запуска вызова аутентификации, как это обрабатывается сервлета? В каком случае, как его отфильтровать? (.jpg .js .css игнорируется по умолчанию, как «Public Object» и поэтому не безопасности экранированы?
  • Есть ли что-то странное с файлами конфигурации (воспроизводится ниже) Теперь безопасность была заперта?

Я подозреваю, следующие строки из журнала сервера являются релевантными:

debug.log

09:29:52,516 DEBUG DispatcherServlet:999 - Null ModelAndView returned to DispatcherServlet with name 'mvc-dispatcher': assuming HandlerAdapter completed request handling 
09:29:52,517 DEBUG DispatcherServlet:946 - Successfully completed request 
09:29:52,517 DEBUG ExceptionTranslationFilter:115 - Chain processed normally 
09:29:52,517 DEBUG HttpSessionSecurityContextRepository:269 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 
09:29:52,517 DEBUG SecurityContextPersistenceFilter:97 - SecurityContextHolder now cleared, as request processing completed 
09:29:52,983 DEBUG FilterChainProxy:337 - /resources/bootstrap/img/glyphicons-halflings.png at position 1 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 
09:29:52,983 DEBUG HttpSessionSecurityContextRepository:139 - HttpSession returned null object for SPRING_SECURITY_CONTEXT 
09:29:52,983 DEBUG HttpSessionSecurityContextRepository:85 - No SecurityContext was available from the HttpSession: [email protected] A new one will be created. 
09:29:52,983 DEBUG FilterChainProxy:337 - /resources/bootstrap/img/glyphicons-halflings.png at position 2 of 10 in additional filter chain; firing Filter: 'LogoutFilter' 
09:29:52,984 DEBUG FilterChainProxy:337 - /resources/bootstrap/img/glyphicons-halflings.png at position 3 of 10 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' 
09:29:52,984 DEBUG FilterChainProxy:337 - /resources/bootstrap/img/glyphicons-halflings.png at position 4 of 10 in additional filter chain; firing Filter: 'BasicAuthenticationFilter' 
09:29:52,984 DEBUG FilterChainProxy:337 - /resources/bootstrap/img/glyphicons-halflings.png at position 5 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 
09:29:52,984 DEBUG FilterChainProxy:337 - /resources/bootstrap/img/glyphicons-halflings.png at position 6 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 
09:29:52,984 DEBUG FilterChainProxy:337 - /resources/bootstrap/img/glyphicons-halflings.png at position 7 of 10 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 
09:29:52,985 DEBUG AnonymousAuthenticationFilter:102 - Populated SecurityContextHolder with anonymous token: 'org.sprin[email protected]905571d8: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]0: RemoteIpAddress: 127.0.0.1; SessionId: 2AE4A610A87DADA1FC2D3EC33BAC5176; Granted Authorities: ROLE_ANONYMOUS' 

09:29:52,990 DEBUG DispatcherServlet:999 - Null ModelAndView returned to DispatcherServlet with name 'mvc-dispatcher': assuming HandlerAdapter completed request handling 
09:29:52,991 DEBUG DispatcherServlet:946 - Successfully completed request 
09:29:52,991 DEBUG ExceptionTranslationFilter:115 - Chain processed normally 
09:29:52,991 DEBUG HttpSessionSecurityContextRepository:269 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 
09:29:52,991 DEBUG SecurityContextPersistenceFilter:97 - SecurityContextHolder now cleared, as request processing completed 

на данный момент я использую простые, аутентификации XML на основе следующим образом:

безопасности context.xml

<beans:beans xmlns="http://www.springframework.org/schema/security" 
xmlns:beans="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/security 
http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 

<http auto-config="true"> 
    <intercept-url pattern="/homepage*" access="ROLE_USER" /> 
    <!-- custom securiy URL mappings --> 
    <form-login login-page="/login" default-target-url="/homepage/main" 
     authentication-failure-url="/loginfailed" /> 
    <logout logout-success-url="/logout" />  
</http> 

<authentication-manager> 
    <authentication-provider> 
    <user-service> 
    <user name="user" password="pass" authorities="ROLE_USER" /> 
    </user-service> 
    </authentication-provider> 
</authentication-manager> 

</beans:beans> 

Другие соответствующие конфигурационные файлы:

MVC-диспетчерская-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 

<context:component-scan base-package="com.blah.blah.controller" /> 
<!-- URI mapping for static content --> 
<mvc:resources mapping="/resources/**" location="/resources/" /> 
<bean 
    class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver"> 
    <property name="prefix"> 
    <value>/WEB-INF/views/</value> 
    </property> 
    <property name="suffix"> 
    <value>.jsp</value> 
    </property> 
</bean> 

<!-- also add the following beans to get rid of some exceptions --> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> 
</beans> 

web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    id="yourpackagename.yourwebproject" version="2.5"> 
<display-name>my web project</display-name> 

<!-- Spring Framework Configuration --> 
<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>  
     classpath:application-context.xml, 
     /WEB-INF/spring-security.xml 
    </param-value> 
</context-param> 

<!-- Spring Security --> 
<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 Configurations --> 
<!-- Web App Dispatcher --> 
<!-- Spring MVC --> 
<servlet> 
    <servlet-name>mvc-dispatcher</servlet-name> 
    <servlet-class> 
       org.springframework.web.servlet.DispatcherServlet 
      </servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
    <servlet-name>mvc-dispatcher</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

<!-- Mentioning the Context Loader Listener class of Spring Framework as a listener --> 
<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<!-- Filter Configurations --> 
<!-- UTF-8 encoding filter --> 
<filter> 
    <filter-name>encodingFilter</filter-name> 
    <filter-class> 
     org.springframework.web.filter.CharacterEncodingFilter 
    </filter-class> 
    <init-param> 
     <param-name>encoding</param-name> 
     <param-value>UTF-8</param-value> 
    </init-param> 
</filter> 

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

<!-- logging --> 
<context-param> 
    <param-name>log4jConfigLocation</param-name> 
    <param-value>/WEB-INF/classes/log4j.properties</param-value> 
</context-param> 
<listener> 
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 
</listener> 

</web-app> 
+0

Каковы имена полей ввода? Являются ли они 'j_username' и' j_password'? – n1ckolas

+0

Да, они - все по умолчанию. Добавили HTML для справки. – tacticAl

+0

Боже, какой номер. Имя/идентификатор поля поля по-прежнему было задано как input_password от дизайнера пользовательского интерфейса, я его не переключил. @ n1ckolas - спасибо за ваше боковое мышление! – tacticAl

ответ

2

Поскольку пружинный фильтр применяется ко всем запросам, это также относится к изображениям png. Для первого вопроса можно фильтровать PNG с линией, как этого

<intercept-url pattern="/**/*.png" access="ROLE_ANONYMOUS" /> 

или, если вы решите использовать выражение доступа с

<intercept-url pattern="/**/*.png" access="true" /> 

Но из конфигурационных файлов, то это должно быть так или иначе.

Другой способ сделать это:

<http pattern="/**/*.png" security="none"/> 
0

Ответ Адриан хорош. С весны 4 и Spring Security 4 мы фильтрации изображений и других ресурсов, таких как, что теперь:

<http auto-config="true" use-expressions="true"> 
    <intercept-url pattern="/" access="permitAll" /> 
    <intercept-url pattern="/assets**" access="permitAll" /> 
    <intercept-url pattern="/images**" access="permitAll" /> 
... 
</http> 

Это муравьиный образец стиля обозначений позволяет не заботиться о папках иерархий для ваших ресурсов.

Конечно, вы должны использовать соответствующие права доступа с тегами, как что:

<intercept-url pattern="/private.do" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')" /> 
<intercept-url pattern="/admin.do" access="hasRole('ROLE_ADMIN')" /> 

И не забудьте активировать защиту от CSRF с:

<csrf/> 

Я нашел, что это очень удобно для настройки. Пять лет назад это было не так просто :)

Смежные вопросы