Как добавить значения в Spring SecurityContextHolder

у меня там параметры входа

1.userName

2.password

3.companyId

У меня есть имя пользователя и пароль, используя следующий код

 Authentication auth = SecurityContextHolder.getContext().getAuthentication();

 String name = auth.getName();

 String pwd = auth.getCredentials();

 String companyId= ???//How can i set and then get company Id here.

Мой вопрос: как я могу получить дополнительный параметр входа (companyId) с помощью SecurityContextHolder?

Класс извлечения может не быть контроллером Spring. Вот почему я использую SecurityContextHolder вместо HttpSession.

Спасибо,


person edaklij    schedule 24.12.2013    source источник


Ответы (1)


Создайте простой фильтр SpringSecurityFilter. Используйте метод setDetails, чтобы указать дополнительные сведения о пользователе.

package org.example;  
public class CustomDeatilsSecurityFilter extends SpringSecurityFilter {

   protected void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
      SecurityContext sec = SecurityContextHolder.getContent();
      AbstractAuthenticationToken auth = (AbstractAuthenticationToken)sec.getAuthentication();
      HashMap<String, Object> info = new HashMap<String, Object>();
      info.put("companyId", 42);
      auth.setDetails(info);
   }

}

Добавьте его в Spring Security Filter Chain следующим образом (это НЕ web.xml, а что-то вроде applicationContext-security.xml):

<bean id="customDeatilsSecurityFilter" class="org.example.CustomDeatilsSecurityFilter">
   <custom-filter position="LAST" />
</bean>

Затем где-то в коде вы можете сделать что-то вроде этого:

Map<String, Object> info = (Map<String, Object>)SecurityContextHolder.getContext().getAuthentication.getDetails();  
int companyId = info.get("companyId");  

Базовая установка Spring Security в web.xml

<context-param>
    <param-name>patchConfigLocation</param-name>
    <param-value>
        classpath:/applicationContext.xml
       /WEB-INF/applicationContext-datasource.xml
       /WEB-INF/applicationContext-security.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>

в applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:sec="http://www.springframework.org/schema/security"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    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/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.1.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.2.xsd">  
...
    <bean id="customDeatilsSecurityFilter" class="org.example.CustomDeatilsSecurityFilter">
       <custom-filter position="LAST" />
    </bean>
...

в pom.xml проекта

    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-acl</artifactId>
        <version>3.1.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>3.1.3.RELEASE</version>
    </dependency>
    <!-- !Spring Security -->
person Anton Shchastnyi    schedule 24.12.2013
comment
Спасибо Антон Щастный.. Что такое авторизация? не могли бы вы привести полный пример? Весной я совсем новичок. - person edaklij; 26.12.2013
comment
унаследованный класс SpringSecurityFilter не существует.?? Как мы можем указать custom-filte внутри обычного bean-компонента? - person edaklij; 26.12.2013
comment
Хорошо, рассмотрите возможность обновления pom.xml, web.xml и security.xml вашего проекта. Убедитесь, что вы правильно включили Spring applicationContext.xml, applicationContext-security.xml - person Anton Shchastnyi; 26.12.2013
comment
Спасибо Антон Щастный..Но как нам расширить SpringSecurityFilter..нет такого класса... - person edaklij; 26.12.2013
comment
О, мне жаль, похоже, что этот класс есть в более старых версиях Spring Security docs.spring.io/autorepo/docs/spring-security/2.0.x/apidocs/org/. Таким образом, вы можете перейти с 3.1.3.RELEASE на 2.0.x, чтобы запустить приведенный выше код, или вы можете обновить объект аутентификации в другом месте. Рассмотрите возможность просмотра stackoverflow.com/questions/18220556/ - person Anton Shchastnyi; 26.12.2013
comment
не могли бы вы обновить свой код как 3.1.3.RELEASE, тогда я приму ваш ответ .. - person edaklij; 26.12.2013