Search code examples
javaspring-securitydwr

Spring Security Login via DWR (Direct Web Remoting)


I am looking for a way to login/logout users with DWR, so that I could just create a DWR bean with methods login and logout.

public class AuthorizationHandler {

    @Autowired
    private UserRepository userRepository;


    public Map<String, String> loginUser(String userName, String password) {
        Map<String, String> map = new HashMap<>();
        if (userRepository.validate(userName, password)) {
            // login the user here       
            map.put("success", true);
            map.put("redirect", ...);
        } else {
            map.put("success", false);
        }
        return map;
    }


    public Map<String, String> logoutUser() {
        // logout the user here
        Map<String, String> map = new HashMap<>();
        map.put("success", "ok");
        return map;
    }
}

My problem is that I can't find a way to work with users and to log them in/out programmatically. All the tutorial uses xml based configuration, but what is behind is sort of hidden.


Solution

  • In one of my application I had a similar requirement, please find the steps I followed

    public void authenticateSession(HttpSession session, UserDetails user) {
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                user.getUsername(), user.getPassword());
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                user, authRequest.getCredentials(), user.getAuthorities());
        result.setDetails(authRequest.getDetails());
    
        SecurityContext ctx = SecurityContextHolder.createEmptyContext();
        ctx.setAuthentication(result);
    
        session.setAttribute(
                UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY,
                TextEscapeUtils.escapeEntities(user.getUsername()));
        session.setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                ctx);
    
        AuthenticationSuccessEvent event = new AuthenticationSuccessEvent(
                result);
        applicationContext.publishEvent(event);
    }
    

    This method authenticates the passed session with the passed user object.

    In your case you have to obtain the UserDetails object and pass it to this method along with the current session.

    You can use the UserDetailsService interface to load the UserDetails.