Esempio n. 1
0
  @ResponseBody
  @RequestMapping("noLogin")
  public String noLogin(@RequestParam("uname") String uname) {

    if (ValidateUtil.isValid(uname)) {
      AdminUser result = adminUserService.noLogin(uname);
      // 用户不存在
      if (!ValidateUtil.isValid(result.getId())) {
        adminUserService.saveOrUpdateEntiry(result);
      }

      UserDetailsService detail = (UserDetailsService) SpringContextUtil.getBean("myUserDetail");
      UserDetails details = null;
      try {

        details = detail.loadUserByUsername(result.getName());
      } catch (Exception e) {
        return "用户未找到";
      }

      UsernamePasswordAuthenticationToken authenticationToken =
          new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());

      SecurityContextHolder.getContext().setAuthentication(authenticationToken);

      HttpSession session = getRequest().getSession(true); //
      session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
    }
    return "redirect:/user";
  }
  @RunAsSystem
  public FileIngestJob createJob(FileIngestJobExecution fileIngestJobExecution) {
    dataService.add(FileIngestJobExecutionMetaData.ENTITY_NAME, fileIngestJobExecution);
    String username = fileIngestJobExecution.getUser();
    Progress progress = new ProgressImpl(fileIngestJobExecution, jobExecutionUpdater, mailSender);
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    RunAsUserToken runAsAuthentication =
        new RunAsUserToken(
            "Job Execution",
            username,
            null,
            userDetailsService.loadUserByUsername(username).getAuthorities(),
            null);
    Entity fileIngestEntity = fileIngestJobExecution.getFileIngest();
    Entity targetEntityEntity = fileIngestEntity.getEntity(FileIngestMetaData.ENTITY_META_DATA);
    String targetEntityName = targetEntityEntity.getString(EntityMetaDataMetaData.FULL_NAME);
    String url = fileIngestEntity.getString(FileIngestMetaData.URL);
    String loader = fileIngestEntity.getString(FileIngestMetaData.LOADER);
    String failureEmail = fileIngestEntity.getString(FileIngestMetaData.FAILURE_EMAIL);

    return new FileIngestJob(
        progress,
        transactionTemplate,
        runAsAuthentication,
        fileIngester,
        targetEntityName,
        url,
        loader,
        failureEmail,
        fileIngestJobExecution.getIdentifier());
  }
  /**
   * Handles the creation of the final <tt>Authentication</tt> object which will be returned by the
   * provider.
   *
   * <p>The default implementation just creates a new OutOfBandAuthenticationToken from the
   * original, but with the UserDetails as the principal and including the authorities loaded by the
   * UserDetailsService.
   *
   * @param userDetails the loaded UserDetails object
   * @param auth the token passed to the authenticate method, containing
   * @return the token which will represent the authenticated user.
   */
  protected Authentication createSuccessfulAuthentication(
      UserDetails rawUserDetails, OutOfBandAuthenticationToken auth) {
    String eMail = auth.getEmail();
    if (eMail == null) {
      logger.warn("OutOfBand attributes did not include an e-mail address! ");
      throw new UsernameNotFoundException("email address not supplied in OutOfBand attributes");
    }
    eMail = OutOfBandAuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = OutOfBandAuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_OUT_OF_BAND granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_OUT_OF_BAND.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
      partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
      // found the user in the table -- fold in authorizations and get uriUser.
      authorities.addAll(partialDetails.getAuthorities());
      // users are blacklisted by registering them and giving them no rights.
      noRights = partialDetails.getAuthorities().isEmpty();
      username = partialDetails.getUsername();
    } catch (Exception e) {
      logger.warn(
          "OutOfBand attribute e-mail: "
              + eMail
              + " did not match any known e-mail addresses! "
              + e.getMessage());
      throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser =
        new AggregateUser(
            username,
            partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain,
            partialDetails.isEnabled(),
            partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(),
            partialDetails.isAccountNonLocked(),
            authorities);
    if (noRights
        || !(trueUser.isEnabled()
            && trueUser.isAccountNonExpired()
            && trueUser.isAccountNonLocked())) {
      logger.warn("OutOfBand attribute e-mail: " + eMail + " account is blocked! ");
      throw new UsernameNotFoundException("account is blocked");
    }

    return new OutOfBandAuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getEmail());
  }
 @Override
 public void setCurrentUser(SiteUser user) {
   UserDetails userDetails = userDetailsService.loadUserByUsername(user.getName());
   Authentication authentication =
       new UsernamePasswordAuthenticationToken(
           userDetails, user.getPassword(), userDetails.getAuthorities());
   SecurityContextHolder.getContext().setAuthentication(authentication);
 }
  @Test
  public void userDetailsService() throws Throwable {

    this.applicationContext = new AnnotationConfigApplicationContext();
    this.applicationContext.register(SecurityConfiguration.class);
    this.applicationContext.refresh();
    UserDetailsService userDetailsService =
        this.applicationContext.getBean(UserDetailsService.class);
    Assert.assertNotNull("the userDetailsService should not be null", userDetailsService);
    Assert.assertEquals(
        "there should only be 1 authority",
        1,
        userDetailsService.loadUserByUsername("jlong").getAuthorities().size());
    Assert.assertEquals(
        "there should be 2 authorities",
        2,
        userDetailsService.loadUserByUsername("jbarrez").getAuthorities().size());
  }
 Authentication getAuthentication() {
   if (adminAuthentication == null) {
     UserDetails user = userDetailsService.loadUserByUsername("user");
     adminAuthentication =
         new TestingAuthenticationToken(
             user, user.getPassword(), (List<GrantedAuthority>) user.getAuthorities());
   }
   return adminAuthentication;
 }
 @Test
 public void inetOrgContextMapperIsSupported() {
   setContext(
       "<ldap-server id='someServer' ldif='classpath:test-server.ldif'/>"
           + "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-details-class='inetOrgPerson'/>");
   UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
   UserDetails ben = uds.loadUserByUsername("ben");
   assertTrue(ben instanceof InetOrgPerson);
 }
  @Override
  public ItemDetails getItem(int itemNumber) throws RegistryException, LoginException {
    UsernamePasswordAuthenticationToken token =
        (UsernamePasswordAuthenticationToken) webServiceContext.getUserPrincipal();
    UserDetails user = userDetailsService.loadUserByUsername(token.getName());

    terminalSession.getModule(Login.class).login(user.getUsername(), user.getPassword());
    return terminalSession.getEntity(ItemDetails.class, itemNumber);
  }
 public Collection<GrantedAuthority> getGrantedAuthorities(
     DirContextOperations context, String username) {
   log.debug("ALL AUTHORITY ");
   Collection<GrantedAuthority> auth =
       userDetailsService.loadUserByUsername(username).getAuthorities();
   for (GrantedAuthority a : auth) {
     log.debug("authority = " + a.toString());
   }
   return auth;
 }
  @Test
  public void rolePrefixIsSupported() throws Exception {
    setContext(
        "<ldap-user-service id='ldapUDS' "
            + "     user-search-filter='(uid={0})' "
            + "     group-search-filter='member={0}' role-prefix='PREFIX_'/>"
            + "<ldap-user-service id='ldapUDSNoPrefix' "
            + "     user-search-filter='(uid={0})' "
            + "     group-search-filter='member={0}' role-prefix='none'/><ldap-server ldif='classpath:test-server.ldif'/>");

    UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
    UserDetails ben = uds.loadUserByUsername("ben");
    assertTrue(
        AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("PREFIX_DEVELOPERS"));

    uds = (UserDetailsService) appCtx.getBean("ldapUDSNoPrefix");
    ben = uds.loadUserByUsername("ben");
    assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("DEVELOPERS"));
  }
  /**
   * Loads the username by using the account ID of the user.
   *
   * @param userId The account ID of the requested user.
   * @return The information of the requested user.
   * @throws UsernameNotFoundException Thrown if no user is found.
   * @throws DataAccessException
   */
  @Override
  public SocialUserDetails loadUserByUserId(String userId)
      throws UsernameNotFoundException, DataAccessException {
    LOGGER.debug("Loading user by user id: {}", userId);

    UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
    LOGGER.debug("Found user details: {}", userDetails);

    return (SocialUserDetails) userDetails;
  }
 @Override
 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
   UserDetails user = null;
   try {
     user = users_.loadUserByUsername(username);
   } catch (UsernameNotFoundException e) {
     user = clientDetailsWrapper_.loadUserByUsername(username);
   }
   return user;
 }
  @Test
  public void userServiceReturnsExpectedData() throws Exception {
    setContext(
        "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>");

    UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
    UserDetails ben = uds.loadUserByUsername("ben");

    Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
    assertEquals(3, authorities.size());
    assertTrue(authorities.contains("ROLE_DEVELOPERS"));
  }
  @Test
  public void differentUserSearchBaseWorksAsExpected() throws Exception {
    setContext(
        "<ldap-user-service id='ldapUDS' "
            + "       user-search-base='ou=otherpeople' "
            + "       user-search-filter='(cn={0})' "
            + "       group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>");

    UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
    UserDetails joe = uds.loadUserByUsername("Joe Smeth");

    assertEquals("Joe Smeth", joe.getUsername());
  }
  @Before
  public void setUp() throws Exception {
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    roleHierarchy.setHierarchy("ROLE_A > ROLE_B");
    final UserDetails user =
        new User(
            "EXISTING_USER",
            "PASSWORD",
            true,
            true,
            true,
            true,
            AuthorityUtils.createAuthorityList("ROLE_A"));
    final UserDetailsService wrappedUserDetailsService = mock(UserDetailsService.class);
    when(wrappedUserDetailsService.loadUserByUsername("EXISTING_USER")).thenReturn(user);
    when(wrappedUserDetailsService.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION"))
        .thenThrow(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION"));

    this.wrappedUserDetailsService = wrappedUserDetailsService;
    userDetailsServiceWrapper = new UserDetailsServiceWrapper();
    userDetailsServiceWrapper.setRoleHierarchy(roleHierarchy);
    userDetailsServiceWrapper.setUserDetailsService(wrappedUserDetailsService);
  }
  @Test(expectedExceptions = UsernameNotFoundException.class)
  void testProviderAuthenticateValidTokenButNonExistentUserThrowsException() throws Exception {
    String token =
        Jwts.builder()
            .setSubject("hacker")
            .signWith(SignatureAlgorithm.HS512, signingKeyProvider.getSigningKey())
            .compact();

    when(userDetailsService.loadUserByUsername(eq("hacker")))
        .thenThrow(UsernameNotFoundException.class);

    JwtTokenAuthenticationProvider provider =
        new JwtTokenAuthenticationProvider(signingKeyProvider, userDetailsService);
    JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token);
    provider.authenticate(authRequest);
  }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    KeycloakAuthenticationToken token =
        (KeycloakAuthenticationToken) super.authenticate(authentication);
    String username;
    UserDetails userDetails;

    if (token == null) {
      return null;
    }

    username = this.resolveUsername(token);
    userDetails = userDetailsService.loadUserByUsername(username);

    return new KeycloakUserDetailsAuthenticationToken(
        userDetails, token.getAccount(), token.getAuthorities());
  }
  @Test
  public void findUserByToken() {
    MolgenisToken molgenisToken = new MolgenisToken();
    molgenisToken.setToken("token");
    MolgenisUser user = new MolgenisUser();
    user.setUsername("admin");
    molgenisToken.setMolgenisUser(user);

    when(dataService.findOne(
            MolgenisToken.ENTITY_NAME,
            new QueryImpl().eq(MolgenisToken.TOKEN, "token"),
            MolgenisToken.class))
        .thenReturn(molgenisToken);

    UserDetails userDetails =
        new User("admin", "admin", Arrays.asList(new SimpleGrantedAuthority("admin")));
    when(userDetailsService.loadUserByUsername("admin")).thenReturn(userDetails);

    assertEquals(tokenService.findUserByToken("token"), userDetails);
  }
  @Test
  void testProviderAuthenticatesOk() throws Exception {
    String token =
        Jwts.builder()
            .setSubject("admin")
            .signWith(SignatureAlgorithm.HS512, signingKeyProvider.getSigningKey())
            .compact();

    UserEntity user = new UserEntity("admin", "pw", Role.QUIZMASTER, true);
    user.setRoleType(Role.SUPERUSER);
    when(userDetailsService.loadUserByUsername(eq("admin"))).thenReturn(user);

    JwtTokenAuthenticationProvider provider =
        new JwtTokenAuthenticationProvider(signingKeyProvider, userDetailsService);
    JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token);

    Authentication authResult = provider.authenticate(authRequest);
    assertNotNull(authResult);
    assertEquals(authResult.getPrincipal(), user);
    assertEquals(authResult.getCredentials(), token);
    assertTrue(authResult.isAuthenticated());
  }