AdminUserInfoInterceptor extends UserInfoInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); if (!CollectionUtils.isEmpty(authorities)) { for (GrantedAuthority authority : authorities) { if ("ROLE_ADMIN".equals(authority.getAuthority())) { return super.preHandle(request, response, handler); } } } } return true; }  @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler);  }
@Test public void testPreHandleWithAdminUser() throws Exception { String role = "ROLE_ADMIN"; MockHttpServletRequest request = getMockHttpServletRequest(role); DefaultUserInfo defaultUserInfo = new DefaultUserInfo(); when(userInfoService.getByUsername(NAME)).thenReturn(defaultUserInfo); subject.preHandle(request, response, null); DefaultUserInfo userInfo = (DefaultUserInfo) request.getAttribute("userInfo"); assertEquals(defaultUserInfo, userInfo); }
@Test public void testPreHandleWithOAuthUser() throws Exception { MockHttpServletRequest request = getMockHttpServletRequest("ROLE_USER"); subject.preHandle(request, response, null); DefaultUserInfo userInfo = (DefaultUserInfo) request.getAttribute("userInfo"); assertNull(userInfo); }
@Test public void testPreHandleWithNoUser() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); subject.preHandle(request, response, null); DefaultUserInfo userInfo = (DefaultUserInfo) request.getAttribute("userInfo"); assertNull(userInfo); }