Как получить доступ к объекту HttpServletRequest во время аутентификации пользователя в Spring Security? - PullRequest
8 голосов
/ 08 марта 2012

Мои требования к приложению состоят в том, что мне необходимо проанализировать некоторую информацию из URL-адреса http-запроса для аутентификации пользователя. Очевидно, я просто не могу использовать реализацию UserDetailsService.

Мой вопрос: как реализовать UserDetailsService (или эквивалентную схему аутентификации), которому требуется доступ к HttpServletRequest?

Версия My Spring Security - 3.0.7. RELEASE

Ответы [ 3 ]

6 голосов
/ 09 марта 2012

Очень похожий вопрос есть в Spring Security FAQ .

Вы можете добавить пользовательский AuthenticationDetailsSource в фильтр аутентификации, чтобы извлечь дополнительную релевантную информацию из входящего запроса. Эту информацию затем можно получить из предоставленного объекта Authentication в пользовательском AuthenticationProvider.

3 голосов
/ 13 сентября 2013

Одним из возможных решений является использование RequestContextFilter. Вы можете определить его в web.xml как в следующем фрагменте:

<filter>
  <filter-name>requestContextFilter</filter-name>
  <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>

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

<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>

или если вам просто нужно это из-за проблем с безопасностью, лучше всего поместить его в конфигурационный файл Spring Security, как в следующем примере:

<?xml version="1.0" encoding="UTF-8"?>
<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.1.xsd
                      http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <http>
    <custom-filter ref="requestContextFilter" before="FORM_LOGIN_FILTER"/>
    <form-login login-page="/login" authentication-failure-url="/login?error=failed" />
  </http>
  <beans:bean id="requestContextFilter" class="org.springframework.web.filter.RequestContextFilter"/>

  <authentication-manager alias="authManager">
    <authentication-provider ref="authProvider" />
  </authentication-manager>
  <beans:bean id="authProvider" class="my.company.CustomAuthProvider" />
</beans:beans>

Затем вы можете использовать метод RequestContextHolder.currentRequestAttributes() в классах Spring Security. Например, следующим образом:

public class CustomAuthProvider extends DaoAuthenticationProvider {
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    System.err.println(attr.getRequest().getParameter("myParameterName"));
    return super.authenticate(authentication);
  }
}
0 голосов
/ 08 марта 2012

Вам нужно будет сделать сервлет бобом Spring, как описано здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...