My code is based on Springboot, and I use shiro to implement login and permission manage.
I have a method to get user info, the data will be returned as json format.
@GetMapping("/info")
@RequiresAuthentication
public User info(HttpSession session) {
return userService.info(session);
}
There is my shiro config. When I logout and call the info method, shiro will redirect the request to loginUrl eg '/user/unauthc'.
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
factoryBean.setSecurityManager(securityManager);
factoryBean.setLoginUrl("/user/unauthc");
factoryBean.setSuccessUrl("/");
Map<String, String> map = new LinkedHashMap<>();
map.put("/user/login", "anon");
map.put("/**", "authc");
factoryBean.setFilterChainDefinitionMap(map);
return factoryBean;
}
There is my '/user/unauthc' method. It will be throw an UnauthenticatedException. And I have a handler to catch this exception and return a 403 response.
@GetMapping("/unauthc")
public void unauthc() {
throw new UnauthenticatedException();
}
@ExceptionHandler(UnauthenticatedException.class)
ResponseEntity<String> handleUnauthenticatedException(UnauthenticatedException e) {
log.info(e.getMessage());
return new ResponseEntity<>("User not login", HttpStatus.FORBIDDEN);
}
Here is my question: when I test info method with logout status in unit test, I excepted a 403 code. However, I got a 302 code. Even having the same problem in axios request. So how can I solve this problem.
There is my unit test code and the log.
@Test
public void testInfo() throws Exception {
MockHttpSession session = new MockHttpSession();
mockMvc.perform(MockMvcRequestBuilders.get("/user/info").session(session))
.andExpect(MockMvcResultMatchers.status().isUnauthorized());
}
MockHttpServletRequest:
HTTP Method = GET
Request URI = /user/info
Parameters = {}
Headers = []
Body = null
Session Attrs = {shiroSavedRequest=org.apache.shiro.web.util.SavedRequest@6af310c7, org.apache.shiro.web.session.HttpServletSession.HOST_SESSION_KEY=localhost}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 302
Error message = null
Headers = [Location:"/user/unauthc"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = /user/unauthc
Cookies = []
java.lang.AssertionError: Status expected:<401> but was:<302>
Expected :401
Actual :302
I try to search this problem but the result I got is to modify FormAuthenticationFilter.