首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试Spring安全配置

测试Spring安全配置
EN

Stack Overflow用户
提问于 2015-05-04 17:20:46
回答 1查看 1.7K关注 0票数 0

我做了一个非常简单的演示应用程序来尝试测试Spring安全性。

这是我的应用程序配置

代码语言:javascript
复制
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringBootApplication
public class DemoApplication extends WebSecurityConfigurerAdapter {

  @Autowired
  private SecurityService securityService;

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

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests().anyRequest().fullyAuthenticated();
      http.httpBasic();
      http.csrf().disable();
  }

  public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
  }
}

我的UserDetailsService实现接受所有具有密码‘密码’的用户,将管理角色授予' admin‘用户。

代码语言:javascript
复制
@Service
public class SecurityService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities;
        if (username.equals("admin")) {
            authorities = Arrays.asList(() -> "ROLE_ADMIN", () -> "ROLE_BASIC");
        } else {
            authorities = Arrays.asList(() -> "ROLE_BASIC");
        }
        return new User(username, "password", authorities);
    }
}

最后,我创建了一个简单的测试来检查它:

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@WebAppConfiguration
public class DemoApplicationTests {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Test
    public void thatAuthManagerUsesMyService() {
        Authentication auth = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken("admin", "password")
        );

        assertTrue(auth.isAuthenticated());     
    }
}

我原以为考试会通过,但我得到了一个BadCredentialsException。调试之后,我意识到在测试中由Spring注入的AuthenticationManager不是我配置的那个。在eclipse调试器中挖掘对象时,我看到UserDetailsServer是一个InMemoryUserDetailsManager。

我还检查了DemoApplication中的配置()方法是否被调用。我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-04 22:26:09

authenticationManagerBean()的Per WebSecurityConfigurerAdapter api参考

重写此方法以将AuthenticationManager从配置程序(AuthenticationManagerBuilder)公开为Bean。

因此,只需在您的authenticationManagerBean()中重写WebSecurityConfigurerAdapter,并将其公开为@Bean的bean。

代码语言:javascript
复制
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30036065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档