Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Spring Security: Obtaining current username (i.e. SecurityContext) information in a bean?

    • 0
    • 4
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 984
    Comment on it

    Instead of calling static method inside the controller like below:

    @RequestMapping(value="/welcome", method = RequestMethod.GET)
    public String getUserDetails(ModelMap model) {
        Authentication authentication = SecurityContextHolder.getContext().
                getAuthentication();
        String name = authentication.getName();
        model.addAttribute("username", name);
        model.addAttribute("message", "Welcome to Spring");
        return "success";
    
    }
    

    We can configure the app to have the current SecurityContext, or current Authentication.

    We can use the below method instead:

    @RequestMapping(value="/welcome", method = RequestMethod.GET)
    public String printWelcome(ModelMap model, Principal principal ) {
    
        String name = principal.getName();
        model.addAttribute("username", name);
        model.addAttribute("message", "Spring Security Hello World");
        return "hello";
    }
    

    From the below example you can see how we can retrieve logged in user's user-details:

    spring-dispatcher-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"
        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">
        <context:component-scan base-package="com.spring.controller" />
        <bean
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix">
            <value>/WEB-INF/pages/</value>
          </property>
          <property name="suffix">
            <value>.jsp</value>
          </property>
        </bean>
    
    </beans>
    

    Define the below configuration in your applicationContext-security.xml file

    <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.0.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="/welcome*" access="ROLE_USER" />
    
            <form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/loginfailed"/>
        </http>
        <authentication-manager>
          <authentication-provider>
            <user-service>
                <user name="Spring" password="123456" authorities="ROLE_USER" />
            </user-service>
          </authentication-provider>
        </authentication-manager>
    </beans:beans>
    

    Now define web.xml

    <web-app id="WebApp&#95;ID" version="2.4"
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
        <display-name>Spring MVC Application</display-name>
    
        <!-- Spring MVC -->
        <servlet>
            <servlet-name>spring-dispatcher</servlet-name>
            <servlet-class>
               org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring-dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <listener>
            <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/spring-dispatcher-servlet.xml,
                /WEB-INF/applicationContext-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>
    </web-app>
    

    Now write your controller as below:

    LoginController.java

    package com.evon.controller;
    
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    @Controller
    public class LoginController {
    
        @RequestMapping(value="/welcome", method = RequestMethod.GET)
        public String printWelcome(ModelMap model, Principal principal ) {
    
            String name = principal.getName();
            model.addAttribute("username", name);
            model.addAttribute("message", "Spring Security Hello World");
            return "hello";
    
        }
    
        @RequestMapping(value="/login", method = RequestMethod.GET)
        public String login(ModelMap model) {
    
            return "login";
    
        }
    
    }
    

    success.jsp

    <html>
    <body>
        <h3>${message}</h3>    
        <br />
        <h3>Username : ${username}</h3>    
    </body>
    </html>
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: