本文整理了Java中org.springframework.security.core.userdetails.UserDetailsService.loadUserByUsername()
方法的一些代码示例,展示了UserDetailsService.loadUserByUsername()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。UserDetailsService.loadUserByUsername()
方法的具体详情如下:
包路径:org.springframework.security.core.userdetails.UserDetailsService
类名称:UserDetailsService
方法名:loadUserByUsername
[英]Locates the user based on the username. In the actual implementation, the search may possibly be case sensitive, or case insensitive depending on how the implementation instance is configured. In this case, the UserDetails
object that comes back may have a username that is of a different case than what was actually requested..
[中]根据用户名查找用户。在实际实现中,搜索可能区分大小写,也可能不区分大小写,具体取决于实现实例的配置方式。在这种情况下,返回的UserDetails
对象的用户名可能与实际请求的用户名不同。。
代码示例来源:origin: spring-projects/spring-security
/**
* Get the UserDetails object from the wrapped UserDetailsService implementation
*/
public UserDetails loadUserDetails(T authentication) throws UsernameNotFoundException {
return this.userDetailsService.loadUserByUsername(authentication.getName());
}
代码示例来源:origin: spring-projects/spring-security
public Collection<? extends GrantedAuthority> getGrantedAuthorities(
DirContextOperations userData, String username) {
return userDetailsService.loadUserByUsername(username).getAuthorities();
}
}
代码示例来源:origin: weibocom/motan
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public TokenTransfer authenticate(@RequestParam("username") String username, @RequestParam("password") String password) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
return new TokenTransfer(TokenUtils.createToken(userDetails));
}
代码示例来源:origin: szerhusenBC/jwt-spring-security-demo
@RequestMapping(value = "user", method = RequestMethod.GET)
public JwtUser getAuthenticatedUser(HttpServletRequest request) {
String token = request.getHeader(tokenHeader).substring(7);
String username = jwtTokenUtil.getUsernameFromToken(token);
JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);
return user;
}
代码示例来源:origin: spring-projects/spring-security-oauth
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey(USERNAME)) {
Object principal = map.get(USERNAME);
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
if (userDetailsService != null) {
UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME));
authorities = user.getAuthorities();
principal = user;
}
return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
}
return null;
}
代码示例来源:origin: spring-projects/spring-security
public UserDetails loadUserByUsername(String username) {
UserDetails user = userCache.getUserFromCache(username);
if (user == null) {
user = delegate.loadUserByUsername(username);
}
Assert.notNull(user, () -> "UserDetailsService " + delegate
+ " returned null for username " + username + ". "
+ "This is an interface contract violation");
userCache.putUserInCache(user);
return user;
}
}
代码示例来源:origin: macrozheng/mall
@Override
public String login(String username, String password) {
String token = null;
//密码需要客户端加密后传递
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, passwordEncoder.encodePassword(password, null));
try {
Authentication authentication = authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
token = jwtTokenUtil.generateToken(userDetails);
updateLoginTimeByUsername(username);
insertLoginLog(username);
} catch (AuthenticationException e) {
LOGGER.warn("登录异常:{}", e.getMessage());
}
return token;
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void delegateUsesExisitingAuthentication() {
String username = "user";
String password = "password";
when(this.uds.loadUserByUsername(username)).thenReturn(PasswordEncodedUser.user());
AuthenticationManager authenticationManager = this.adapter.authenticationManager;
assertThat(authenticationManager).isNotNull();
Authentication auth = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password));
verify(this.uds).loadUserByUsername(username);
assertThat(auth.getPrincipal()).isEqualTo(PasswordEncodedUser.user());
}
代码示例来源:origin: weibocom/motan
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = getAsHttpRequest(request);
String authToken = extractAuthTokenFromRequest(httpServletRequest);
String username = TokenUtils.getUserNameFromToken(authToken);
if (username != null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (TokenUtils.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
chain.doFilter(request, response);
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void userServiceWithValidPropertiesFileWorksSuccessfully() {
setContext("<user-service id='service' "
+ "properties='classpath:org/springframework/security/config/users.properties'/>");
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
userService.loadUserByUsername("bob");
userService.loadUserByUsername("joe");
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void disabledAndEmbeddedFlagsAreSupported() {
setContext("<user-service id='service'>"
+ " <user name='joe' password='joespassword' authorities='ROLE_A' locked='true'/>"
+ " <user name='Bob' password='bobspassword' authorities='ROLE_A' disabled='true'/>"
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertThat(joe.isAccountNonLocked()).isFalse();
// Check case-sensitive lookup SEC-1432
UserDetails bob = userService.loadUserByUsername("Bob");
assertThat(bob.isEnabled()).isFalse();
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void getAuthenticationWhenUserDetailsServiceBeanThenAuthenticationManagerUsesUserDetailsServiceBean() throws Exception {
this.spring.register(UserDetailsServiceBeanConfig.class).autowire();
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
when(uds.loadUserByUsername("user")).thenReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() throws Exception {
this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
Throwable thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("user") );
assertThat(thrown).isNull();
thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("admin") );
assertThat(thrown).isInstanceOf(UsernameNotFoundException.class);
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void embeddedUsersWithNoPasswordIsGivenGeneratedValue() {
setContext("<user-service id='service'>"
+ " <user name='joe' authorities='ROLE_A'/>" + "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertThat(joe.getPassword().length() > 0).isTrue();
Long.parseLong(joe.getPassword());
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void getAuthenticationWhenUserDetailsServiceAndPasswordEncoderBeanThenEncoderUsed() throws Exception {
UserDetails user = new User("user", "$2a$10$FBAKClV1zBIOOC9XMXf3AO8RoGXYVYsfvUdoLxGkd/BnXEn4tqT3u",
AuthorityUtils.createAuthorityList("ROLE_USER"));
this.spring.register(UserDetailsServiceBeanWithPasswordEncoderConfig.class).autowire();
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
when(uds.loadUserByUsername("user")).thenReturn(User.withUserDetails(user).build(), User.withUserDetails(user).build());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void userServiceWithEmbeddedUsersWorksSuccessfully() {
setContext("<user-service id='service'>"
+ " <user name='joe' password='joespassword' authorities='ROLE_A'/>"
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
userService.loadUserByUsername("joe");
}
代码示例来源:origin: spring-projects/spring-security
@Test(expected = FatalBeanException.class)
public void userWithBothPropertiesAndEmbeddedUsersThrowsException() {
setContext("<user-service id='service' properties='doesntmatter.props'>"
+ " <user name='joe' password='joespassword' authorities='ROLE_A'/>"
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
userService.loadUserByUsername("Joe");
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void requestWithRememberMeWhenUsingCustomUserDetailsServiceThenInvokesThisUserDetailsService()
throws Exception {
this.spring.configLocations(this.xml("WithUserDetailsService")).autowire();
UserDetailsService userDetailsService = this.spring.getContext().getBean(UserDetailsService.class);
when(userDetailsService.loadUserByUsername("user")).thenAnswer((invocation) ->
new User("user", "{noop}password", Collections.emptyList()));
MvcResult result = this.rememberAuthentication("user", "password").andReturn();
Cookie cookie = rememberMeCookie(result);
this.mvc.perform(get("/authenticated")
.cookie(cookie))
.andExpect(status().isOk());
verify(userDetailsService, atLeastOnce()).loadUserByUsername("user");
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void loadConfigWhenInMemoryConfigureProtectedThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureProtectedConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext()
.getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
代码示例来源:origin: spring-projects/spring-security
@Test
public void loadConfigWhenInMemoryConfigureGlobalThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureGlobalConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext()
.getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
内容来源于网络,如有侵权,请联系作者删除!