How to add values into Spring SecurityContextHolder
Asked Answered
F

2

7

I have there login parameters

1.userName

2.password

3.companyId

I have got user name and password using following code

 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.

My Question is how can i get an extra login parameter(companyId) using SecurityContextHolder?

The extracting class may not be a spring controller.That is why i am using SecurityContextHolder instead of HttpSession.

Thanks,

Flake answered 24/12, 2013 at 5:55 Comment(0)
F
10

Create a simple SpringSecurityFilter filter. Use setDetails() method to put extra details for the user.

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);
   }

}

Add it to the Spring Security Filter Chain like this (this is NOT web.xml, but something like applicationContext-security.xml):

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

Then somewhere in the code you may do something like this:

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

Basic installation of Spring Security in 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>

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

in project's 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 -->
Fahlband answered 24/12, 2013 at 9:0 Comment(6)
Thanks Anton Shchastnyi.. What is auth? can you please give me a full example?.I Am quite new in spring.Flake
inherited class "SpringSecurityFilter " does not exist.?? How can we specify "custom-filte" inside a normal bean?Flake
Ok, consider updating your project's pom.xml, web.xml, and security.xml. Make sure you properly included Spring's applicationContext.xml, applicationContext-security.xmlFahlband
Thanks Anton Shchastnyi..But how can we extend "SpringSecurityFilter"..there is no such class...Flake
Oh, I am sorry it looks like this class is in older versions of Spring Security docs.spring.io/autorepo/docs/spring-security/2.0.x/apidocs/org/…. So you may downgrade from 3.1.3.RELEASE to 2.0.x in order to launch the code above, or you may update Authentication object in some other place. Consider looking at #18221056Fahlband
could you please update your code as 3.1.3.RELEASE,Then i shall accept your answer..Flake
T
0

There are two methods to set or retrieve companyId from SecurityContextHolder in Spring Security. Created a method to set companyId

public void setcompanyIdToAbstractAuthenticationToken(Integer companyId) {
        Map<String, Integer> map= new HashMap<>();
        map.put("companyId", companyId);

        AbstractAuthenticationToken authentication = (AbstractAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        authentication.setDetails(map);
    }
}

Created a method to get or retrieve companyId as Integer type

public Integer getCompanyId() {
       Map<String, Integer> authenticationDetails = (Map<String, Integer>) Optional.ofNullable(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getDetails)
                .orElseGet(HashMap::new);
       return authenticationDetails.get("companyId");
} 
Twinberry answered 3/9, 2023 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.