Spring 4.3.0 RELEASE - 自动登录不重定向到主页aftre regestration

时间:2016-07-19 12:06:35

标签: java spring spring-mvc spring-security

我使用登录和&amp ;;构建Web应用程序来自:

的再版
  1. 登录后(用户名和密码) - 指导工作
  2. 但是在注册后#34;自动登录"并重定向到用户主页不起作用。
  3. 为什么会这样?

    UserController中:

    @Controller
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @Autowired
        private SecurityService securityService;
    
        @Autowired
        private UserValidator userValidator;
    
        @RequestMapping(value = "/registration", method = RequestMethod.GET)
        public String registration(Model model) {
            model.addAttribute("userForm", new UserEntity());
    
            return "registration";
        }
    
        @RequestMapping(value = "/registration", method = RequestMethod.POST)
        public String registration(@ModelAttribute("userForm") UserEntity userForm, BindingResult bindingResult, Model model) {
            userValidator.validate(userForm, bindingResult);
    
            if (bindingResult.hasErrors()) {
                return "registration";
            }
    
            userService.save(userForm);
    
            securityService.autologin(userForm.getName(), userForm.getPasswordConfirm());
    
            //model.addAttribute("user", getPrincipal());
    
            return "home";
        }
    
        @RequestMapping(value = "/login", method = RequestMethod.GET)
        public String login(Model model, String error, String logout) {
            if (error != null)
                model.addAttribute("error", "Your username and password is invalid.");
    
            if (logout != null)
                model.addAttribute("message", "You have been logged out successfully.");
    
            return "login";
        }
    
        @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
        public String homePage(ModelMap model) {
            model.addAttribute("user", getPrincipal());
            return "home";
        }
    
        @RequestMapping(value = "/admin", method = RequestMethod.GET)
        public String adminPage(ModelMap model) {
            model.addAttribute("user", getPrincipal());
            return "admin";
        }
    
        private String getPrincipal(){
            String userName = null;
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
            if (principal instanceof UserDetails) {
                userName = ((UserDetails)principal).getUsername();
            } else {
                userName = principal.toString();
            }
            return userName;
        }
    }
    

    CustomSuccessHandler:

    @Component
    public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    
        private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
        @Override
        protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
                throws IOException {
            String targetUrl = determineTargetUrl(authentication);
    
            if (response.isCommitted()) {
                System.out.println("Can't redirect");
                return;
            }
    
            redirectStrategy.sendRedirect(request, response, targetUrl);
        }
    
        /*
         * This method extracts the roles of currently logged-in user and returns
         * appropriate URL according to his/her role.
         */
        protected String determineTargetUrl(Authentication authentication) {
            String url = "";
    
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    
            List<String> roles = new ArrayList<String>();
    
            for (GrantedAuthority a : authorities) {
                roles.add(a.getAuthority());
            }
    
            if (isDba(roles)) {
                url = "/db";
            } else if (isAdmin(roles)) {
                url = "/admin";
            } else if (isUser(roles)) {
                url = "/home";
            } else {
                url = "/accessDenied";
            }
    
            return url;
        }
    
        private boolean isUser(List<String> roles) {
            if (roles.contains("ROLE_USER")) {
                return true;
            }
            return false;
        }
    
        private boolean isAdmin(List<String> roles) {
            if (roles.contains("ROLE_ADMIN")) {
                return true;
            }
            return false;
        }
    
        private boolean isDba(List<String> roles) {
            if (roles.contains("ROLE_DBA")) {
                return true;
            }
            return false;
        }
    
        public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
            this.redirectStrategy = redirectStrategy;
        }
    
        protected RedirectStrategy getRedirectStrategy() {
            return redirectStrategy;
        }
    
    }
    

    SecurityServiceImp:

    @Service("securityService")
    public class SecurityServiceImpl implements SecurityService {
    
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @Autowired
        private UserDetailsService userDetailsService;
    
        private static final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);
    
        @Override
        public String findLoggedInUsername() {
            Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
            if (userDetails instanceof UserDetails) {
                return ((UserDetails)userDetails).getUsername();
            }
    
            return null;
        }
    
        @Override
        public void autologin(String name, String password) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(name);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
    
            authenticationManager.authenticate(usernamePasswordAuthenticationToken);
    
            if (usernamePasswordAuthenticationToken.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                logger.debug(String.format("Auto login %s successfully!", name));
            }
        }
    
    }
    

    UserDetailServiceImp:

    @Service("userDetailsService")
    public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        @Transactional(readOnly = true)
        public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
            UserEntity user = userRepository.findByName(name);
    
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            for (RoleEntity role : user.getRoles()){
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            }
    
            return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(), grantedAuthorities);
        }
    }
    

    的AppConfig-security.xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <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.xsd
                                    http://www.springframework.org/schema/security
                                    http://www.springframework.org/schema/security/spring-security-4.1.xsd">
    
        <http auto-config="true">
            <intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
            <intercept-url pattern="/home" access="hasRole('ROLE_USER')"/>
             <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')"/>
            <form-login login-page="/login" 
                        default-target-url="/welcome" 
                        authentication-failure-url="/login?error" 
                        username-parameter="name" 
                        password-parameter="password"
                        authentication-success-handler-ref="customSuccessHandler"/>
            <logout logout-success-url="/login?logout" />
        </http>
    
        <authentication-manager alias="authenticationManager">
            <authentication-provider user-service-ref="userDetailsServiceImpl">
                <password-encoder ref="encoder"></password-encoder>
            </authentication-provider>
        </authentication-manager>
    
        <beans:bean id="userDetailsServiceImpl" class="com.searcher.service.UserDetailsServiceImpl"></beans:bean>
    
        <beans:bean id="customSuccessHandler" class="com.searcher.configuration.CustomSuccessHandler" />
    
        <beans:bean id="encoder"
              class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
            <beans:constructor-arg name="strength" value="11"/>
        </beans:bean>
    </beans:beans>
    

0 个答案:

没有答案