@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); logger.info("username:" + username); logger.info("password:" + password); // Don't log passwords in real app // 1. Use the username to load the data for the user, including authorities and password. YourUser user = .... // 2. Check the passwords match. if (!user.getPassword().equals(password)) { throw new BadCredentialsException("Bad Credentials"); } // 3. Preferably clear the password in the user object before storing in authentication object user.clearPassword(); // 4. Return an authenticated token, containing user data and authorities return UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()) ; }
/** * 查看分类的所有子项,仅作者本人可查看 */ @GetMapping("/user/hub/{id}") public String list(@AuthenticationPrincipal UsernamePasswordAuthenticationToken userAuthentication, @PathVariable("id") Long id, Model model) { User user = (User) userAuthentication.getPrincipal(); List<HubItem> items = hubItemService.list(id, user.getId()); Hub hub = hubService.getById(id, user.getId()); model.addAttribute("user", user); model.addAttribute("hub", hub); model.addAttribute("items", items); return "item"; }
/** * 获取所有分类信息 */ @GetMapping("/user/hub/list") public List<Hub> list(@AuthenticationPrincipal UsernamePasswordAuthenticationToken authenticationToken) { User user = (User) authenticationToken.getPrincipal(); return hubService.getByUserId(user.getId()); }
/** * 删除分类 */ @GetMapping("/user/hub/delete/{hubId}") public ResponseBean deleteCategory(@AuthenticationPrincipal UsernamePasswordAuthenticationToken authenticationToken, @PathVariable("hubId") Long hubId) { User user = (User) authenticationToken.getPrincipal(); hubService.deleteByUserIdAndId(user.getId(), hubId); return ResponseBean.ok(); }
/** * 删除分类下的指定资源 */ @GetMapping("/user/hub/item/delete/{id}") public ResponseBean delete(@AuthenticationPrincipal UsernamePasswordAuthenticationToken authenticationToken, @PathVariable("id") Long id) { User user = (User) authenticationToken.getPrincipal(); itemService.delete(id, user.getId()); return ResponseBean.ok(); }
/** * 关注/取消关注 对方 */ @GetMapping("/user/attention/{otherId}") public ResponseBean payAttention(@AuthenticationPrincipal UsernamePasswordAuthenticationToken principal, @PathVariable("otherId") Long otherId){ User user = (User) principal.getPrincipal(); Long userId = user.getId(); Boolean flag = attentionService.attention(userId, otherId); return ResponseBean.ok(flag); }
@Test public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithNonUserPrincipalTest() throws IOException { UsernamePasswordAuthenticationToken token = mapper .readValue(AUTHENTICATED_NON_USER_PRINCIPAL_JSON, UsernamePasswordAuthenticationToken.class); assertThat(token).isNotNull(); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(NonUserPrincipal.class); }
/** * 查看他人资料 */ @GetMapping("/info/{id}") public String user(@AuthenticationPrincipal UsernamePasswordAuthenticationToken authenticationToken, @PathVariable("id") Long userId, Model model) { if (authenticationToken != null){ User user = (User) authenticationToken.getPrincipal(); if (userId.equals(user.getId())){ return "redirect:/user"; } boolean isAttention = attentionService.isAttention(user.getId(), userId); model.addAttribute("isAttention", isAttention); } User other = userService.getUserInfo(userId); model.addAttribute("user", other); List<Hub> hubs = hubService.getByUserId(userId); model.addAttribute("hubs", hubs); return "info"; }
/** * 个人中心 */ @GetMapping("/user") public String user(@AuthenticationPrincipal UsernamePasswordAuthenticationToken authenticationToken, Model model) { User user = (User) authenticationToken.getPrincipal(); model.addAttribute("user", user); List<Hub> hubs = hubService.getByUserId(user.getId()); model.addAttribute("hubs", hubs); List<User> idols = userService.getIdols(user.getId(), 1); model.addAttribute("idols", idols); List<User> fans = userService.getFans(user.getId(), 1); model.addAttribute("fans", fans); return "user"; }
@Test public void authenticateSuccess() throws Exception { Authentication auth = provider.authenticate(token); assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal()); assertThat(auth.getCredentials()).isEqualTo(token.getCredentials()); assertThat(auth.isAuthenticated()).isEqualTo(true); assertThat(auth.getAuthorities().isEmpty()).isEqualTo(false); verify(publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class)); verifyNoMoreInteractions(publisher); }
/** * 私藏资源到指定分类 */ @PostMapping("/user/hub/item/insert") public ResponseBean add(@AuthenticationPrincipal UsernamePasswordAuthenticationToken authenticationToken, HttpServletRequest request) { User user = (User) authenticationToken.getPrincipal(); HubItem item = createItem(user.getId(), request); itemService.insert(item); return ResponseBean.ok(); }
@Override public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException { if (provider == null) { throw new IdentityAccessException("The Kerberos authentication provider is not initialized."); } try { // Perform the authentication final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword()); logger.debug("Created authentication token for principal {} with name {} and is authenticated {}", token.getPrincipal(), token.getName(), token.isAuthenticated()); final Authentication authentication = provider.authenticate(token); logger.debug("Ran provider.authenticate() and returned authentication for " + "principal {} with name {} and is authenticated {}", authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated()); return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer); } catch (final AuthenticationException e) { throw new InvalidLoginCredentialsException(e.getMessage(), e); } }
@Test public void javadocExample() { String resName = "/" + getClass().getName().replace('.', '/') + ".xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( resName); context.registerShutdownHook(); try { provider = context.getBean(DefaultJaasAuthenticationProvider.class); Authentication auth = provider.authenticate(token); assertThat(auth.isAuthenticated()).isEqualTo(true); assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal()); } finally { context.close(); } }
@Test public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException { UsernamePasswordAuthenticationToken token = mapper .readValue(AUTHENTICATED_JSON, UsernamePasswordAuthenticationToken.class); assertThat(token).isNotNull(); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(((User) token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); assertThat(token.isAuthenticated()).isEqualTo(true); assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); }
@Test public void testReturnsAdditionalGrantedAuthorities() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); Authentication result = runAs.buildRunAs(inputToken, new Object(), SecurityConfig.createList("RUN_AS_SOMETHING")); if (!(result instanceof RunAsUserToken)) { fail("Should have returned a RunAsUserToken"); } assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); Set<String> authorities = AuthorityUtils.authorityListToSet( result.getAuthorities()); assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities.contains("ROLE_ONE")).isTrue(); assertThat(authorities.contains("ROLE_TWO")).isTrue(); RunAsUserToken resultCast = (RunAsUserToken) result; assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); }
@Test public void testRespectsRolePrefix() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ONE", "TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); runAs.setRolePrefix("FOOBAR_"); Authentication result = runAs.buildRunAs(inputToken, new Object(), SecurityConfig.createList("RUN_AS_SOMETHING")); assertThat(result instanceof RunAsUserToken).withFailMessage( "Should have returned a RunAsUserToken").isTrue(); assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); Set<String> authorities = AuthorityUtils.authorityListToSet( result.getAuthorities()); assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities.contains("ONE")).isTrue(); assertThat(authorities.contains("TWO")).isTrue(); RunAsUserToken resultCast = (RunAsUserToken) result; assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); }
@Test public void gettersReturnCorrectData() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); assertThat(token.getPrincipal()).isEqualTo("Test"); assertThat(token.getCredentials()).isEqualTo("Password"); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_ONE"); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_TWO"); }
/** * 添加分类 */ @PostMapping(value = "/user/hub/create") public ResponseBean addCategory(@AuthenticationPrincipal UsernamePasswordAuthenticationToken authenticationToken, HttpServletRequest request) { Hub hub = requestToHub(request); User user = (User) authenticationToken.getPrincipal(); hub.setUserId(user.getId()); hub.setAvatar(user.getAvatar()); hubService.insert(hub); return ResponseBean.ok(); }
@Test public void testAuthenticatesWithForcePrincipalAsString() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); provider.setForcePrincipalAsString(true); Authentication result = provider.authenticate(token); if (!(result instanceof UsernamePasswordAuthenticationToken)) { fail("Should have returned instance of UsernamePasswordAuthenticationToken"); } UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result; assertThat(castResult.getPrincipal().getClass()).isEqualTo(String.class); assertThat(castResult.getPrincipal()).isEqualTo("rod"); }
@Test public void testAuthenticates() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); token.setDetails("192.168.0.1"); DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); Authentication result = provider.authenticate(token); if (!(result instanceof UsernamePasswordAuthenticationToken)) { fail("Should have returned instance of UsernamePasswordAuthenticationToken"); } UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result; assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class); assertThat(castResult.getCredentials()).isEqualTo("koala"); assertThat( AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains( "ROLE_ONE", "ROLE_TWO"); assertThat(castResult.getDetails()).isEqualTo("192.168.0.1"); }