@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "userService")
private UserDetailsService userDetailsService;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationEventPublisher(authenticationEventPublisher())
.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.anonymous()
.disable()
.authorizeRequests()
.antMatchers("/api-docs/**")
.permitAll();
}
@Bean
public DefaultAuthenticationEventPublisher authenticationEventPublisher() {
return new DefaultAuthenticationEventPublisher();
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
共享Api实现类,添加preauthorize-admin,查看所有用户
@RestController
@RequestMapping("/api/userInfo")
public class UserController {
private final Logger LOG = Logger.getLogger(getClass());
private String serviceMsg = "serviceMsg";
@Autowired
private UserService userService;
@Autowired
private UserServiceUtil util;
@PreAuthorize("hasAnyRole('ADMIN')")
@RequestMapping(method = RequestMethod.GET, produces = "application/json" )
@ApiOperation(value = "Get details of all RA2 users in a paginated JSON format")
public Page<User> listUser(Pageable pageable) {
return userService.getUserSummary(pageable);
}
这是我的JUnit测试,我发送get请求并返回403错误。
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration
@AutoConfigureMockMvc(addFilters = false)
public class UserControllerTest {
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
protected static class TestConfiguration {
@Bean
@Primary
public UserService getUserService(){
return Mockito.mock(UserService.class);
}
@Bean
@Primary
public UserServiceUtil getUserServiceUtil(){
return Mockito.mock(UserServiceUtil.class);
}
}
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext ;
private String serviceMsg = "serviceMsg";
@Autowired
private UserService userService;
@Autowired
private UserServiceUtil util;
private User admin;
private User user;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext ).apply(springSecurity()).build();
}
@WithMockUser(username = "test",authorities ="ADMIN")
@Test
public void getuserList() throws Exception {
List<User> list = new ArrayList<User>();
list.add(new User());
Page<User> page = new PageImpl<User>(list, null, list.size());
Mockito.when(userService.getUserSummary(any(Pageable.class))).thenReturn(page);
this.mockMvc.perform(get("/api/userInfo?page=1&size=10").with(csrf()).contentType(MediaType.APPLICATION_JSON)).
andExpect(status().isOk()).andDo(MockMvcResultHandlers.print());
}
```
使用@WithMockUser
时,权限
和角色
之间存在差异:
/**
* <p>
* The roles to use. The default is "USER". A {@link GrantedAuthority} will be created
* for each value within roles. Each value in roles will automatically be prefixed
* with "ROLE_". For example, the default will result in "ROLE_USER" being used.
* </p>
* <p>
* If {@link #authorities()} is specified this property cannot be changed from the
* default.
* </p>
* @return
*/
String[] roles() default { "USER" };
/**
* <p>
* The authorities to use. A {@link GrantedAuthority} will be created for each value.
* </p>
*
* <p>
* If this property is specified then {@link #roles()} is not used. This differs from
* {@link #roles()} in that it does not prefix the values passed in automatically.
* </p>
* @return
*/
String[] authorities() default {};
使用Authorities
设置的任何内容都不会得到任何前缀。
由于控制器需要role_admin
,请尝试使用roles
。
问题内容: 我编写了一个测试UsersController的单元测试。UsersControllerTest.findUser工作正常,但不能正常运行UsersControllerTest.insertGetModifyDelete。 在测试日志中,我可以看到POST请求与UsersController的任何方法都不匹配,但是我不明白为什么。您能帮我这个吗? 这是我其余的Java类: 我有2种方法
我正在尝试为我的Spring项目运行集成测试,它是一个简单的get方法,用于从DB返回给定id的字符串输出。但是在Mockmvc中,我一直在Mockmvc上得到一个NullPointerException。在我的测试范围内执行。 以下是测试: 这里是控制器-输出控制器: 完全错误是:
我有一个spring boot应用程序,它有一个endpoint测试配置类和一个单元测试来测试我的http客户端。我正在尝试从应用程序中获取服务器地址和端口。位于我的src/测试中的属性。(所有类都在我的src/测试中。) 这是我的配置类代码: 我对我的中的值进行了注释。属性,然后创建一个方法,我用bean实例化该方法以返回我的服务器地址字符串。 然后,我在HttpClientTest类中使用该字
问题内容: 我正在尝试制作Sitecraper。我是在本地计算机上制作的,在那儿工作得很好。当我在服务器上执行相同操作时,它显示403禁止错误。我正在使用PHP简单HTML DOM解析器 。我在服务器上收到的错误是这样的: 警告:file_get_contents(http://example.com/viewProperty.html?id=7715888)[function.file- get
使用curl或postman,我得到403禁止: Lambda函数具有以下权限: S3桶具有以下CORS规则:
我使用textutils.join连接一个字符串列表,但它返回null。我是在一个简单的单元测试中这样做的。 下面是有问题的代码: