角色存储库findAll方法在Spring Boot中创建用户时返回null

时间:2018-10-15 15:09:26

标签: java spring-boot spring-security spring-data spring-boot-actuator

我只是想创建一个用户并向该用户添加一个角色,但是我不断在

上收到空指针异常
 user.setRoles(new HashSet<>(roleRepository.findAll()));

这是我的代码

//add new User
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public String addUser(@RequestParam("firstName") String firstName,
                          @RequestParam("lastName") String lastName,
                          @RequestParam("email") String email ,
                          @RequestParam("password") String password,
                          @RequestParam("role") String role, Model model) {


        System.out.println(firstName);
        User user = new User();


        if (emailExist(email)) {
            System.out.println("user already exists");

        } else {
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setEmail(email);
            user.setPassword(passwordEncoder.encode(password));
            user.setRoles(new HashSet<>(roleRepository.findAll()));
            user.setRole(role.toUpperCase());
            userRepository.save(user);

            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);

            try {
                helper.setTo(email);
                System.out.println(email);
                helper.setText("This is to inform you that you have been created as a " + role + " on the EREVNA app " + "your password is "+ password);
                helper.setSubject("Erevna Account Creation");
            } catch (MessagingException e) {
                e.printStackTrace();
                return "Error while sending mail ..";
            }
            sender.send(message);




        }
        model.addAttribute("message", "User Created Successfully");
        return "dashboard/users";
    }

RoleRepository.java

package com.scanapp.repositories;

import com.scanapp.models.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository("roleRepository")
public interface RoleRepository extends JpaRepository<Role, Integer> {
//    Role findByRole(String role);
}

SecurityServiceImpl.java

package com.scanapp.services.impl;

import com.scanapp.config.MyUserPrincipal;
import com.scanapp.services.CustomUserDetailsService;
import com.scanapp.services.SecurityService;
import org.apache.camel.language.Bean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

@Service
public class SecurityServiceImpl implements SecurityService {


    private AuthenticationManager authenticationManager;

    @Autowired
    private CustomUserDetailsService userDetailsService;

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

    @Override
    public String findLoggedInUsername() {
        Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
        if (userDetails instanceof MyUserPrincipal) {
            return ((MyUserPrincipal)userDetails).getUsername();
        }

        return null;
    }

    @Override
    public void autologin(String username, String password) {
        MyUserPrincipal userDetails = (MyUserPrincipal) userDetailsService.loadUserByUsername(username);
        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!", username));
        }
    }
}

CustomUserDetailsS​​ervice.java

package com.scanapp.services;

import com.drew.metadata.StringValue;
import com.scanapp.config.MyUserPrincipal;
import com.scanapp.config.SecSecurityConfig;
import com.scanapp.models.Role;
import com.scanapp.models.User;
import com.scanapp.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;


@Service
public class CustomUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    @Autowired
    private UserRepository userRepository;
//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//
//
//        User user = userRepository.findByEmail(username);
//
//
//
//
//
//        if (Objects.nonNull(user)) {
//            MyUserPrincipal principal = new MyUserPrincipal(user);
//            System.out.println(String.valueOf(principal));
//            System.out.println("User Found");
//            System.out.println(principal.getPassword());
//            System.out.println(principal.getUsername());
//            return principal;
//        }else {
//            throw new BadCredentialsException("User Not found");
//        }
//
//    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(username);

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Role role : user.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
    }
}

MyUserPrincipal.java

package com.scanapp.config;

import com.scanapp.models.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

public class MyUserPrincipal implements UserDetails {



        private User user;

        public MyUserPrincipal(User user) {
            this.user = user;
        }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

            return AuthorityUtils.NO_AUTHORITIES;
    }

    @Override
    public String getPassword()
    {
        return user.getPassword();
    }

    @Override
    public String getUsername()
    {
        return user.getEmail();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

我在哪里弄错了或混淆了?

1 个答案:

答案 0 :(得分:0)

问题是在我的控制器类中没有自动装配roleRepository。

(function($) {
    $.each(['show', 'hide'], function(i, ev) {
        var el = $.fn[ev];
        $.fn[ev] = function() {
            this.trigger(ev);
            return el.apply(this, arguments);
        };
    });
})(jQuery);