Categories
discuss

Setting session scoped objects in AuthenticationSuccessHandler

(Edited to clarify) I have a POJO (SessionStorage) to store session specific data, which I want to populate after a successful authentication. Since I’m setting the Scope to “session”, I’m expecting …

(Edited to clarify) I have a POJO (SessionStorage) to store session specific data, which I want to populate after a successful authentication. Since I’m setting the Scope to “session”, I’m expecting for the MainController and the AuthenticationSuccesshandler to use the same instance of the object.

When I run the WebApp, the Main Controller initiates an instance (as expected), but when I log in, the AuthenticationSuccesshandler seems not to have autowired the SessionStorage object, since it throws a NullPointerException.

How do I get it to do what I want? Here are the excerpts of my code:

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionStorage implements Serializable{
    long id;
    public int getId() {
    return id;
    }

    public SessionStorage() {
        System.out.println("New Session Storage");
        id = System.currentTimeMillis();
    }
}

The main controller looks as follows:

@Controller
@Scope("request")
@RequestMapping("/")
public class MainController {
    @Autowired
    private SessionStorage sessionStorage;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout) {

        System.out.println(sessionStorage.getId()); //Works fine

        ModelAndView model = new ModelAndView();
        if (error != null) {
            model.addObject("error", "Invalid username and     password!");
        }

        if (logout != null) {
            model.addObject("msg", "You've been logged out successfully.");
        }
        model.setViewName("login");
        return model;
    }
}

The AuthentificationSuccesshandler (where the error gets thrown):

public class AuthentificationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SessionStorage sessionStorage;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest hsr, HttpServletResponse hsr1, Authentication a) throws IOException, ServletException {
        System.out.println("Authentication successful: " + a.getName());
        System.out.println(sessionStorage.getId()); //NullPointerException
    }
}

The relevant part of spring-security.xml:

<beans:bean id="authentificationFailureHandler" class="service.AuthentificationFailureHandler" />
    <beans:bean id="authentificationSuccessHandler" class="service.AuthentificationSuccessHandler" />
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/secure/**" access="hasRole('USER')" />


        <form-login 
            login-page="/login" 
            default-target-url="/index"
            authentication-failure-handler-ref="authentificationFailureHandler"
            authentication-failure-url="/login?error" 
            authentication-success-handler-ref="authentificationSuccessHandler"
            username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/login?logout" />
        <!-- enable csrf protection -->
        <csrf/>
    </http>

web-xml:

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Answer

This question is old but showed up as one of the first links to my question in Google.

The fix that I found worked best was to set the Scope on the custom AuthenticationSuccessHandler.

@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)

Further details can be found here: https://tuhrig.de/making-a-spring-bean-session-scoped/

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..