Auto login after successful registration

前端 未结 10 2416
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 23:44

hey all i want to make an auto login after successful registration in spring meaning: i have a protected page which requires login to access them and i want after registrati

相关标签:
10条回答
  • 2020-11-29 00:35

    This is answer to above question In Controller:

    @RequestMapping(value = "/registerHere", method = RequestMethod.POST)
        public ModelAndView registerUser(@ModelAttribute("user") Users user, BindingResult result,
                HttpServletRequest request, HttpServletResponse response) {
            System.out.println("register 3");
    
            ModelAndView mv = new ModelAndView("/home");
            mv.addObject("homePagee", "true");
    
            String uname = user.getUsername();
    
            if (userDAO.getUserByName(uname) == null) {
    
                String passwordFromForm = user.getPassword();
                userDAO.saveOrUpdate(user);
    
                try {
                    authenticateUserAndSetSession(user, passwordFromForm, request);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
    
            }
    
            System.out.println("register 4");
    
            log.debug("Ending of the method registerUser");
            return mv;
        }
    

    Further above method in controller is defined as:

    `private void authenticateUserAndSetSession(Users user, String passwor`dFromForm, HttpServletRequest request){
    
            String username = user.getUsername();
            System.out.println("username:  " + username + " password: " + passwordFromForm);                        
    
            UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
    
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, passwordFromForm, userDetails.getAuthorities());
            request.getSession();
    
            System.out.println("Line Authentication 1");
    
            usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(request));
    
            System.out.println("Line Authentication 2");
    
            Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
    
            System.out.println("Line Authentication 3");
    
    
            if (usernamePasswordAuthenticationToken.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
                System.out.println("Line Authentication 4");
    
            }
    
         request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.
    
            System.out.println("Line Authentication 5");
    
            session.setAttribute("username", user.getUsername());
    
            System.out.println("Line Authentication 6");
    
            session.setAttribute("authorities", usernamePasswordAuthenticationToken.getAuthorities());
    
            System.out.println("username:  " + user.getUsername() + "password: " + user.getPassword()+"authorities: "+ usernamePasswordAuthenticationToken.getAuthorities());
    
            user = userDAO.validate(user.getUsername(), user.getPassword());
            log.debug("You are successfully register");
    
        }
    

    Other answers didnt suggest to put it in try/catch so one does not realize why logic is not working as code runs...and nothing is there neither error or exception on console. So if you wont put it in try catch you wont get exception of bad credentials.

    0 讨论(0)
  • 2020-11-29 00:35

    This is an alternative to the Servlet 3+ integration. If you're using Spring Security's form login, then you can simply delegate to your login page. For example:

    @PostMapping("/signup")
    public String signUp(User user) {
        // encode the password and save the user
        return "forward:/login";
    }
    

    Assuming you have username and password fields in your form, then the 'forward' will send those parameters and Spring Security will use those to authenticate.

    The benefit I found with this approach is that you don't duplicate your formLogin's defaultSuccessUrl (example security setup below). It also cleans up your controller by not requiring a HttpServletRequest parameter.

    @Override
    public void configure(HttpSecurity http) {
        http.authorizeRequests()
                .antMatchers("/", "/signup").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/home", true)
                .permitAll();
    }
    
    0 讨论(0)
  • 2020-11-29 00:36

    I incorporated the same scenario, below is the code snippet. To get the instance of AuthenticationManager, you will need to override the authenticationManagerBean() method of WebSecurityConfigurerAdapter class

    SecurityConfiguration(extends WebSecurityConfigurerAdapter)

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    

    Controller

        @Autowired
        protected AuthenticationManager authenticationManager;
    
        @PostMapping("/register")
        public ModelAndView registerNewUser(@Valid User user,BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response) {
            ModelAndView modelAndView = new ModelAndView();
            User userObj = userService.findUserByEmail(user.getEmail());
            if(userObj != null){
                bindingResult.rejectValue("email", "error.user", "This email id is already registered.");
            }
            if(bindingResult.hasErrors()){
                modelAndView.setViewName("register");
                return modelAndView;
            }else{
                String unEncodedPwd = user.getPassword();
                userService.saveUser(user);
                modelAndView.setViewName("view_name");
                authWithAuthManager(request,user.getEmail(),unEncodedPwd);
            }   
            return modelAndView;
        }
    
    
        public void authWithAuthManager(HttpServletRequest request, String email, String password) {
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(email, password);
            authToken.setDetails(new WebAuthenticationDetails(request));
            Authentication authentication = authenticationManager.authenticate(authToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    
    0 讨论(0)
  • 2020-11-29 00:36

    I'm not sure if you are asking for this, but in your Spring Security configuration you can add a "remember-me" tag. This will manage a cookie in your client, so next time (if the cookie hasn't expired) you'll be logged automatically.

    <http>
        ...
        <remember-me />
    </http>
    
    0 讨论(0)
提交回复
热议问题