使用DaoAuthenticationProvider注册后自动登录

时间:2019-11-01 17:22:14

标签: java spring spring-boot spring-mvc spring-security

在spring-boot应用程序中成功注册后,我尝试实现自动登录。

要存储用户数据,我使用Hibernate,对于身份验证,我使用DaoAuthenticationProvider。已经存在于数据库中的用户的登录工作良好,并且也注册了新用户。只有注册后的自动登录无效。

作为用户名,我使用用户的电子邮件。我尝试了互联网推荐的几种不同方法。他们都没有工作。包括这些:

Auto login after successful registration How can I programmatically authenticate user with Spring Security using DaoAuthenticationProvider https://www.baeldung.com/spring-security-auto-login-user-after-registration

我的WebSecurityConifig类:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth               
                .userDetailsService(userService)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                authorizeRequests()

                .antMatchers("/login", "/console/**", "/registerNewUser/**", "/resources/**", "/css/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated().and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers("/console/**")
                // Request zum Aufruf der Login-Seite
                .and().formLogin().loginPage("/login").failureUrl("/login?error=true").permitAll()
                .defaultSuccessUrl("/")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout().permitAll()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout");

        http.headers().frameOptions().sameOrigin().disable();

        http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
    }

    @Override
    public void configure(WebSecurity web) {
        web
                .ignoring()
                .antMatchers("/resources/static/**", "/css/**", "/js/**", "/img/**");
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(userService);
        auth.setPasswordEncoder(bCryptPasswordEncoder);
        return auth;
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
    }

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

我的控制器注册新用户:

@Controller
public class AccRegistrationController {

@Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserValidator userValidator;

    @Autowired
    private AuthenticationManager authenticationManager;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(userValidator);
    }

    @GetMapping("registerNewUser")
    public String registerUser(Model model, HttpServletRequest request) {
        model.addAttribute("user", new User());
        request.getSession();
        return "accountRegistration/registration";
    }

    @PostMapping("registerNewUser")
    public String registerAccount(HttpServletRequest request, @Valid @ModelAttribute("user") User user, BindingResult bindingResult, Model model) {

        if (bindingResult.hasErrors()) {
            model.addAttribute("user", user);
            return "accountRegistration/registration";
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setActivated(false);
        user.setRoles(roleService.findAllByRolename("ROLE_USER"));
        userService.saveUser(user);


        UsernamePasswordAuthenticationToken token = new 
        UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
 request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return "redirect:registerNewUser?success";
    }
}

我的UserService类:

@Service
public class UserService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(Data.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private SessionRegistry sessionRegistry;

    /* creates new user object and returns it with an auto generated id */
    public User saveUser(User user) {
        return userRepository.save(user);
    }


    public List<User> getAllUsers() {
        return userRepository.findAll();
    }


    public Optional<User> findUser(Integer id) {
        return userRepository.findById(id);
    }

    public User getUserByEmail(String email) {
        return userRepository.findUserByEmail(email);
    }

    public User getOne(Integer id) {
        return userRepository.getOne(id);
    }



    public User getCurrentUser() {
        return getUserByEmail(((org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal()).getUsername());
    }


    public org.springframework.security.core.userdetails.User getCurrentUserDetails() {
        return (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
    }


    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findUserByEmail(email);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("Could not find the user for username " + email);
        }
        List<GrantedAuthority> grantedAuthorities = getUserAuthorities(user.getRoles());
        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
                user.isEnabled(), true, true, user.isEnabled(), grantedAuthorities);
    }

    private List<GrantedAuthority> getUserAuthorities(Set<Role> roleSet) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Role role : roleSet) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getRolename()));
        }
        return grantedAuthorities;
    }

    public Collection<String> getLoggedInUsers() {
        return sessionRegistry.getAllPrincipals().stream()
                .filter(u -> !sessionRegistry.getAllSessions(u, false).isEmpty())
                .map(Object::toString)
                .collect(Collectors.toList());
    }

}

我在我的代码中的AccRegistrationController中添加了一些println语句,以找出问题出在哪里,因为在注册过程中/之后没有发生错误。我发现问题一定在以下代码行中:

Authentication authentication = authenticationManager.authenticate(token);

但是我不能说错了。 authenticationManager可能存在某些错误。

无论我发现“ registerAccount”方法都没有执行到最后。重定向不起作用,我被重定向到登录页面。

希望您能帮助我找到我的错误。

1 个答案:

答案 0 :(得分:0)

用户最简单的登录方法是调用HttpServletRequest.login(String username, String password)方法。

来源:https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/servletapi.html#servletapi-login

AccRegistrationController.registerAccount中,您可以以此替换所有最后一部分

/*UsernamePasswordAuthenticationToken token = new 
        UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
 request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
*/
request.login(user.getEmail(), user.getPassword());

这将开始整个Spring身份验证流程。