手动设置Authenticated Spring User

时间:2017-04-22 19:07:56

标签: java spring spring-boot spring-security

我正在构建一个SpringBoot应用程序。

我使用的是Spring Security,并设置了UserDetailsS​​ervice实现:

public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        org.springframework.security.core.userdetails.User springUser = null;
        User user = userService.loadUserByUsername(username);
        if(user != null){
            List<SimpleGrantedAuthority> authorities = null;
            List<Role> roles = user.getRoles();
            if(roles != null){
                authorities = new ArrayList<>();
                for(Role currentRole: roles){
                    authorities.add(new SimpleGrantedAuthority(currentRole.name()));
                }
            }
            springUser = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
        }
        return springUser;
    }

}

我有一个服务层,其中包含将用户添加到数据库的方法:

public interface UserService {

    public Long addStandardUser(String firstName, String lastName, String username, String password);

    @PreAuthorize("hasRole('ADMIN')")
    public Long addAdministratorUser(String firstName, String lastName, String username, String password);

    @PreAuthorize("hasRole('ADMIN')")
    public User loadUserByUsername(String username);

    public Iterable<User> getUsers(int pageNumber, int pageSize, Direction direction, String sort);

}

我还有一个CommandLineRunner实现,我使用它(在开发模式下)用示例用户初始化数据库:

@Component
@Profile("dev")
public class DBInitializer implements CommandLineRunner {

    @Autowired
    private UserService userService;

    @Override
    public void run(String... args) throws Exception {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ADMIN"));
        Authentication authentication =  new UsernamePasswordAuthenticationToken("foo", null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        userService.addAdministratorUser("John", "Doe", "jdoe", "1234");
        System.out.println("done!");
    }
}

问题是当我尝试添加用户时,我在CommandLineRunner中从Spring获得了一个Access Denied异常。我假设问题是我手动“注入”Spring用户错误。 addAdminUser()方法必须由ADMIN角色的用户运行,因此我需要暂时以ADMIN用户身份运行。我知道有一个@RunAs注释,我记得在其他J2EE应用程序中使用,但我不确定如何与Spring应用程序接口,或者如果它完全在不同的上下文中使用

1 个答案:

答案 0 :(得分:1)

...
// The default role prefix starts with `ROLE_`
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
...

更多详细信息,请参阅here