org.springframework.security.core.userdetails.UserDetailsService类的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(11.0k)|赞(0)|评价(0)|浏览(342)

本文整理了Java中org.springframework.security.core.userdetails.UserDetailsService类的一些代码示例,展示了UserDetailsService类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。UserDetailsService类的具体详情如下:
包路径:org.springframework.security.core.userdetails.UserDetailsService
类名称:UserDetailsService

UserDetailsService介绍

[英]Core interface which loads user-specific data.

It is used throughout the framework as a user DAO and is the strategy used by the org.springframework.security.authentication.dao.DaoAuthenticationProvider.

The interface requires only one read-only method, which simplifies support for new data-access strategies.
[中]加载用户特定数据的核心接口。
它作为用户DAO在整个框架中使用,是组织使用的策略。springframework。安全认证。刀。DaoAuthenticationProvider。
该接口只需要一种只读方法,从而简化了对新数据访问策略的支持。

代码示例

代码示例来源:origin: spring-projects/spring-security

public Collection<? extends GrantedAuthority> getGrantedAuthorities(
      DirContextOperations userData, String username) {
    return userDetailsService.loadUserByUsername(username).getAuthorities();
  }
}

代码示例来源: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: socialsignin/spring-social-security

@Override
  public SocialUserDetails loadUserByUserId(String userId)
      throws UsernameNotFoundException, DataAccessException {
    UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
    return new SocialUser(userDetails.getUsername(),
        userDetails.getPassword(), userDetails.getAuthorities());
  }
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void namePasswordAndAuthoritiesSupportPlaceholders() {
  System.setProperty("principal.name", "joe");
  System.setProperty("principal.pass", "joespassword");
  System.setProperty("principal.authorities", "ROLE_A,ROLE_B");
  setContext("<b:bean class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer'/>"
      + "<user-service id='service'>"
      + "    <user name='${principal.name}' password='${principal.pass}' authorities='${principal.authorities}'/>"
      + "</user-service>");
  UserDetailsService userService = (UserDetailsService) appContext
      .getBean("service");
  UserDetails joe = userService.loadUserByUsername("joe");
  assertThat(joe.getPassword()).isEqualTo("joespassword");
  assertThat(joe.getAuthorities()).hasSize(2);
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void worksWithOpenIDUrlsAsNames() {
  setContext("<user-service id='service'>"
      + "    <user name='http://joe.myopenid.com/' authorities='ROLE_A'/>"
      + "    <user name='https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9' authorities='ROLE_A'/>"
      + "</user-service>");
  UserDetailsService userService = (UserDetailsService) appContext
      .getBean("service");
  assertThat(
      userService.loadUserByUsername("http://joe.myopenid.com/").getUsername())
      .isEqualTo("http://joe.myopenid.com/");
  assertThat(
      userService.loadUserByUsername(
          "https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9")
          .getUsername())
      .isEqualTo("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9");
}

代码示例来源: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: ghillert/botanic-ng

@RequestMapping(value = "/api/info", method = { RequestMethod.GET })
public AuthenticationToken info() {
  final String username = SecurityContextHolder.getContext().getAuthentication().getName();
  final UserDetails details = this.userDetailsService.loadUserByUsername(username);
  final List<String> roles = new ArrayList<>();
  for (GrantedAuthority authority : details.getAuthorities()) {
    roles.add(authority.toString());
  }
  return new AuthenticationToken(details.getUsername(), roles);
}

代码示例来源: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: org.springframework.security/spring-security-core

/**
 * Get the UserDetails object from the wrapped UserDetailsService implementation
 */
public UserDetails loadUserDetails(T authentication) throws UsernameNotFoundException {
  return this.userDetailsService.loadUserByUsername(authentication.getName());
}

代码示例来源:origin: org.siggi-ci/siggi-ci-security

@Override
  public SocialUserDetails loadUserByUserId(final String username) throws UsernameNotFoundException,
      DataAccessException {

    try {
      log.debug("LOAD USER : {}", username);

      UserDetails userDetails = userDetailsService.loadUserByUsername(username);
      return new SocialUser(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
}

代码示例来源:origin: stackoverflow.com

import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

...

public static void reauthenticate(final String username, final String password) {
  UserDetailsService userDetailsService = getBean("userDetailsService");
  UserCache userCache = getBean("userCache");

  UserDetails userDetails = userDetailsService.loadUserByUsername(username);
  SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
      userDetails, password == null ? userDetails.getPassword() : password, userDetails.getAuthorities()));
  userCache.removeUserFromCache(username);
}

代码示例来源:origin: elunez/eladmin

/**
   * 获取用户信息
   * @return
   */
  @GetMapping(value = "${jwt.auth.account}")
  public ResponseEntity getUserInfo(){
    UserDetails userDetails = SecurityContextHolder.getUserDetails();
    JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(userDetails.getUsername());
    return ResponseEntity.ok(jwtUser);
  }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

UserDetails principal = userDetailsService.loadUserByUsername(customer.getUsername());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), auth.getAuthorities());

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

@Override
public String signIn(String username, Connection<?> connection, NativeWebRequest request) {
  UserDetails principal = userDetailsService.loadUserByUsername(username);
  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities());
  SecurityContextHolder.getContext().setAuthentication(token);
  return null;
}

代码示例来源: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: org.springframework.security/spring-security-test

public SecurityContext createSecurityContext(WithUserDetails withUser) {
  String beanName = withUser.userDetailsServiceBeanName();
  UserDetailsService userDetailsService = findUserDetailsService(beanName);
  String username = withUser.value();
  Assert.hasLength(username, "value() must be non empty String");
  UserDetails principal = userDetailsService.loadUserByUsername(username);
  Authentication authentication = new UsernamePasswordAuthenticationToken(
      principal, principal.getPassword(), principal.getAuthorities());
  SecurityContext context = SecurityContextHolder.createEmptyContext();
  context.setAuthentication(authentication);
  return context;
}

代码示例来源:origin: elunez/eladmin

/**
 * 验证密码
 * @param pass
 * @return
 */
@GetMapping(value = "/users/validPass/{pass}")
public ResponseEntity validPass(@PathVariable String pass){
  UserDetails userDetails = SecurityContextHolder.getUserDetails();
  JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(userDetails.getUsername());
  Map map = new HashMap();
  map.put("status",200);
  if(!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(pass))){
    map.put("status",400);
  }
  return new ResponseEntity(map,HttpStatus.OK);
}

代码示例来源: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-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)
      throws UsernameNotFoundException {
    if (delegate != null) {
      return delegate.loadUserByUsername(username);
    }
    synchronized (delegateMonitor) {
      if (delegate == null) {
        for (AuthenticationManagerBuilder delegateBuilder : delegateBuilders) {
          delegate = delegateBuilder.getDefaultUserDetailsService();
          if (delegate != null) {
            break;
          }
        }
        if (delegate == null) {
          throw new IllegalStateException("UserDetailsService is required.");
        }
        this.delegateBuilders = null;
      }
    }
    return delegate.loadUserByUsername(username);
  }
}

相关文章

UserDetailsService类方法