Search in sources :

Example 76 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project ORCID-Source by ORCID.

the class OrcidUserDetailsService method loadUserByUsername.

/**
     * Locates the user based on the username. In the actual implementation, the
     * search may possibly be case insensitive, or case insensitive depending on
     * how the implementation instance is configured. In this case, the
     * <code>UserDetails</code> object that comes back may have a username that
     * is of a different case than what was actually requested..
     * 
     * @param username
     *            the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws org.springframework.security.core.userdetails.UsernameNotFoundException
     *             if the user could not be found or the user has no
     *             GrantedAuthority
     */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    LOGGER.info("About to load user by username = {}", username);
    ProfileEntity profile = obtainEntity(username);
    if (profile == null) {
        throw new UsernameNotFoundException("Bad username or password");
    }
    if (profile.getPrimaryRecord() != null) {
        throw new DeprecatedProfileException("orcid.frontend.security.deprecated_with_primary", profile.getPrimaryRecord().getId(), profile.getId());
    }
    if (profile.getDeactivationDate() != null && !securityMgr.isAdmin()) {
        throw new DisabledException("Account not active, please call helpdesk");
    }
    if (!profile.getClaimed() && !securityMgr.isAdmin()) {
        throw new UnclaimedProfileExistsException("orcid.frontend.security.unclaimed_exists");
    }
    String primaryEmail = null;
    // Clients doesnt have primary email, so, we need to cover that case.
    if (profile.getPrimaryEmail() != null)
        primaryEmail = profile.getPrimaryEmail().getId();
    OrcidProfileUserDetails userDetails = null;
    if (profile.getOrcidType() != null) {
        OrcidType orcidType = OrcidType.fromValue(profile.getOrcidType().value());
        userDetails = new OrcidProfileUserDetails(profile.getId(), primaryEmail, profile.getEncryptedPassword(), orcidType, profile.getGroupType());
    } else {
        userDetails = new OrcidProfileUserDetails(profile.getId(), primaryEmail, profile.getEncryptedPassword());
    }
    return userDetails;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) OrcidType(org.orcid.jaxb.model.message.OrcidType) DisabledException(org.springframework.security.authentication.DisabledException) OrcidProfileUserDetails(org.orcid.core.oauth.OrcidProfileUserDetails) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Transactional(org.springframework.transaction.annotation.Transactional)

Example 77 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project av-service by dvoraka.

the class BasicUserDetailsService method loadUserByUsername.

@Override
public UserDetails loadUserByUsername(String username) {
    if ("JOHN".equals(username)) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return new User("JOHN", "PASS", true, true, true, true, authorities);
    } else {
        throw new UsernameNotFoundException("User not found: " + username);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) User(org.springframework.security.core.userdetails.User) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList)

Example 78 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project opennms by OpenNMS.

the class OpenNMSUserDetailsService method loadUserByUsername.

/**
 * {@inheritDoc}
 */
@Override
public UserDetails loadUserByUsername(final String rawUsername) throws UsernameNotFoundException, DataAccessException {
    final String username;
    if (m_trimRealm && rawUsername.contains("@")) {
        username = rawUsername.substring(0, rawUsername.indexOf("@"));
    } else {
        username = rawUsername;
    }
    final UserDetails userDetails = m_userDao.getByUsername(username);
    if (userDetails == null) {
        throw new UsernameNotFoundException("Unable to locate " + username + " in the userDao");
    }
    return userDetails;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserDetails(org.springframework.security.core.userdetails.UserDetails)

Example 79 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project vorto by eclipse.

the class UserController method updateUser.

@ApiOperation(value = "Update an existing User")
@RequestMapping(method = RequestMethod.PUT, value = "/users/{username}")
public ResponseEntity<UserDto> updateUser(Principal currentlyLoggedInUser, @ApiParam(value = " Username", required = true) @PathVariable String username, @ApiParam(value = "User Data Transfer Object", required = true) @RequestBody UserDto userDto) {
    if (!isUpdateAllowed(currentlyLoggedInUser, username, userDto)) {
        return new ResponseEntity<UserDto>(HttpStatus.UNAUTHORIZED);
    }
    User user = userRepository.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("User does not exists");
    }
    user.setUsername(userDto.getUsername());
    user.setEmail(userDto.getEmail());
    user.setLastUpdated(new Timestamp(System.currentTimeMillis()));
    if (UserUtils.isAdmin(currentlyLoggedInUser)) {
        user.setHasWatchOnRepository(userDto.isHasWatchOnRepository());
    }
    userRepository.save(user);
    User updatedUser = userRepository.findByUsername(userDto.getUsername());
    return new ResponseEntity<UserDto>(UserDto.fromUser(updatedUser), HttpStatus.OK);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) ResponseEntity(org.springframework.http.ResponseEntity) User(org.eclipse.vorto.repository.account.impl.User) Timestamp(java.sql.Timestamp) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 80 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project ORCID-Source by ORCID.

the class SocialController method signinHandler.

@RequestMapping(value = { "/access" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response) {
    SocialType connectionType = socialContext.isSignedIn(request, response);
    if (connectionType != null) {
        Map<String, String> userMap = retrieveUserDetails(connectionType);
        String providerId = connectionType.value();
        String userId = socialContext.getUserId();
        UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserId(userMap.get("providerUserId"), providerId);
        if (userConnectionEntity != null) {
            if (userConnectionEntity.isLinked()) {
                ProfileEntity profile = profileEntityCacheManager.retrieve(userConnectionEntity.getOrcid());
                if (profile.getUsing2FA()) {
                    return new ModelAndView("social_2FA");
                }
                UserconnectionPK pk = new UserconnectionPK(userId, providerId, userMap.get("providerUserId"));
                String aCredentials = new StringBuffer(providerId).append(":").append(userMap.get("providerUserId")).toString();
                PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), aCredentials);
                token.setDetails(getOrcidProfileUserDetails(userConnectionEntity.getOrcid()));
                Authentication authentication = authenticationManager.authenticate(token);
                userConnectionManager.updateLoginInformation(pk);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
            } else {
                ModelAndView mav = new ModelAndView();
                mav.setViewName("social_link_signin");
                mav.addObject("providerId", providerId);
                mav.addObject("accountId", getAccountIdForDisplay(userMap));
                mav.addObject("linkType", "social");
                mav.addObject("emailId", (userMap.get("email") == null) ? "" : userMap.get("email"));
                mav.addObject("firstName", (userMap.get("firstName") == null) ? "" : userMap.get("firstName"));
                mav.addObject("lastName", (userMap.get("lastName") == null) ? "" : userMap.get("lastName"));
                return mav;
            }
        } else {
            throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
        }
    } else {
        throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Authentication(org.springframework.security.core.Authentication) ModelAndView(org.springframework.web.servlet.ModelAndView) SocialType(org.orcid.frontend.spring.web.social.config.SocialType) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) UserconnectionPK(org.orcid.persistence.jpa.entities.UserconnectionPK) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)132 GrantedAuthority (org.springframework.security.core.GrantedAuthority)40 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 UserDetails (org.springframework.security.core.userdetails.UserDetails)36 Authentication (org.springframework.security.core.Authentication)24 Transactional (org.springframework.transaction.annotation.Transactional)20 Logger (org.slf4j.Logger)18 LoggerFactory (org.slf4j.LoggerFactory)18 java.util (java.util)16 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)15 Collectors (java.util.stream.Collectors)14 UserDetailsService (org.springframework.security.core.userdetails.UserDetailsService)14 Component (org.springframework.stereotype.Component)14 User (org.springframework.security.core.userdetails.User)13 ArrayList (java.util.ArrayList)12 HashSet (java.util.HashSet)11 UserRepository (io.github.jhipster.sample.repository.UserRepository)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)9 User (io.github.jhipster.sample.domain.User)6 Date (java.util.Date)6