========================
我在控制器上使用Spring security @Secured,当我在浏览器中测试它时工作正常,使用不同角色的不同用户登录可以看到/看不到不同的URL(200 vs 403)。但它在junit失败了。无论角色是什么,它都已经返回200。这是我的设置。
@RestController
@RequestMapping(value = "/users")
class UserController {
@GetMapping("/admin")
@Secured({"ROLE_ADMIN"})
ResponseEntity<User> adminOnly() {
return new ResponseEntity<>(
User.builder().data("admin only page").build(),
HttpStatus.OK);
}
@GetMapping("/role")
@Secured({"ROLE_USER"})
ResponseEntity<User> user() {
return new ResponseEntity<>(
User.builder().data("Hello World! I am role user.").build(),
HttpStatus.OK);
}
在junit。
@Test
public void test() throws Exception {
this.mockMvc.perform(get("/users").with(user("u1").password("p1").roles("USER")))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
this.mockMvc.perform(get("/users/admin").with(user("u1").password("p1").roles("USER")))
.andDo(print()).andExpect(status().isForbidden());
}
我希望第二次测试为403但是返回200.
MockHttpServletRequest:
HTTP Method = GET
Request URI = /users/admin
Parameters = {}
Headers = {}
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains], Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"data":"admin only page"}
Forwarded URL = null
Redirected URL = null
Cookies = []
我错过了什么?
我还尝试删除所有@Secured并用以下内容替换它们。在junit仍然无法获得403。
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/users/user").hasAnyRole("ROLE_USER")
.antMatchers("/users/admin").hasAnyRole("ROLE_ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.logout()
.permitAll();
使用权限也不起作用。现在它总是返回403。
在config。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/users/user").hasAuthority("USER")
.antMatchers("/users/admin").hasAnyAuthority("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("u1").password("p1").authorities("USER").and()
.withUser("u2").password("p2").authorities("ADMIN", "ACTUATOR");
}
}
在junit。
this.mockMvc.perform(get("/users/admin").with(user("u1").password("p1")
.authorities(Collections.singletonList(new SimpleGrantedAuthority("USER")))))
.andDo(print()).andExpect(status().isForbidden());