手动设置Authenticated Spring用户

问题描述:

我在构建SpringBoot应用程序。手动设置Authenticated Spring用户

我使用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用户身份运行。我知道有,我记得使用其他的J2EE应用中一个@RunAs注释,但我不知道如何与Spring的应用程序界面,或者是在不同的上下文完全

+0

[Springboot Security hasRole not working]的可能重复(http://*.com/questions/41946473/springboot-security-hasrole-not-working) – dur

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

更多细节使用请参阅here