Search in sources :

Example 31 with UsernameNotFoundException

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

the class UserDetailsServiceImpl method loadUserByUsername.

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    Customer customer = customerService.readCustomerByUsername(username, false);
    if (customer == null) {
        throw new UsernameNotFoundException("The customer was not found");
    }
    List<GrantedAuthority> grantedAuthorities = createGrantedAuthorities(roleService.findCustomerRolesByCustomerId(customer.getId()));
    return new CustomerUserDetails(customer.getId(), username, customer.getPassword(), !customer.isDeactivated(), true, !customer.isPasswordChangeRequired(), true, grantedAuthorities);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Customer(org.broadleafcommerce.profile.core.domain.Customer) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 32 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project onebusaway-application-modules by camsys.

the class UserDetailsServiceImpl method getUserForIndexKey.

/**
 **
 * {@link IndexedUserDetailsService} Interface
 ***
 */
@Transactional
@Override
public IndexedUserDetails getUserForIndexKey(UserIndexKey key) throws UsernameNotFoundException, DataAccessException {
    UserIndex userIndex = _userService.getUserIndexForId(key);
    if (userIndex == null)
        throw new UsernameNotFoundException(key.toString());
    setLastAccessTimeForUser(userIndex);
    return new IndexedUserDetailsImpl(_authoritiesService, userIndex);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserIndex(org.onebusaway.users.model.UserIndex) Transactional(org.springframework.transaction.annotation.Transactional)

Example 33 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project onebusaway-application-modules by camsys.

the class UserDetailsServiceImpl method loadUserByUsername.

/**
 **
 * {@link UserDetailsService} Interface
 ***
 */
@Transactional
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    int index = username.indexOf('_');
    if (index == -1)
        throw new UsernameNotFoundException("username did not take the form type_value: " + username);
    String type = username.substring(0, index);
    String value = username.substring(index + 1);
    UserIndexKey key = new UserIndexKey(type, value);
    return getUserForIndexKey(key);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserIndexKey(org.onebusaway.users.model.UserIndexKey) Transactional(org.springframework.transaction.annotation.Transactional)

Example 34 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project ArTEMiS by ls1intum.

the class JiraAuthenticationProvider method getOrCreateUser.

/**
 * Gets or creates the user object for an JIRA user.
 *
 * @param authentication
 * @param skipPasswordCheck     Skip checking the password
 * @return
 */
@Override
public User getOrCreateUser(Authentication authentication, Boolean skipPasswordCheck) {
    String username = authentication.getName().toLowerCase();
    String password = authentication.getCredentials().toString();
    HttpEntity<Principal> entity = new HttpEntity<>(!skipPasswordCheck ? HeaderUtil.createAuthorization(username, password) : HeaderUtil.createAuthorization(JIRA_USER, JIRA_PASSWORD));
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Map> authenticationResponse = null;
    try {
        authenticationResponse = restTemplate.exchange(JIRA_URL + "/rest/api/2/user?username=" + username + "&expand=groups", HttpMethod.GET, entity, Map.class);
    } catch (HttpStatusCodeException e) {
        if (e.getStatusCode().value() == 401) {
            throw new BadCredentialsException("Wrong credentials");
        } else if (e.getStatusCode().is5xxServerError()) {
            throw new ProviderNotFoundException("Could not authenticate via JIRA");
        }
    }
    if (authenticationResponse != null) {
        Map content = authenticationResponse.getBody();
        User user = userRepository.findOneByLogin((String) content.get("name")).orElseGet(() -> {
            return userService.createUser((String) content.get("name"), "", (String) content.get("displayName"), "", (String) content.get("emailAddress"), null, "en");
        });
        user.setGroups(getGroupStrings((ArrayList) ((Map) content.get("groups")).get("items")));
        user.setAuthorities(buildAuthoritiesFromGroups(getGroupStrings((ArrayList) ((Map) content.get("groups")).get("items"))));
        userRepository.save(user);
        if (!user.getActivated()) {
            userService.activateRegistration(user.getActivationKey());
        }
        Optional<User> matchingUser = userService.getUserWithAuthoritiesByLogin(username);
        if (matchingUser.isPresent()) {
            return matchingUser.get();
        } else {
            throw new UsernameNotFoundException("User " + username + " was not found in the " + "database");
        }
    } else {
        throw new InternalAuthenticationServiceException("JIRA Authentication failed for user " + username);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) User(de.tum.in.www1.artemis.domain.User) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ProviderNotFoundException(org.springframework.security.authentication.ProviderNotFoundException) RestTemplate(org.springframework.web.client.RestTemplate) Principal(java.security.Principal)

Example 35 with UsernameNotFoundException

use of org.springframework.security.core.userdetails.UsernameNotFoundException in project ArTEMiS by ls1intum.

the class PersistentTokenRememberMeServices method onLoginSuccess.

@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
    String login = successfulAuthentication.getName();
    log.debug("Creating new persistent login for user {}", login);
    PersistentToken token = userRepository.findOneByLogin(login).map(u -> {
        PersistentToken t = new PersistentToken();
        t.setSeries(RandomUtil.generateSeriesData());
        t.setUser(u);
        t.setTokenValue(RandomUtil.generateTokenData());
        t.setTokenDate(LocalDate.now());
        t.setIpAddress(request.getRemoteAddr());
        t.setUserAgent(request.getHeader("User-Agent"));
        return t;
    }).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database"));
    try {
        persistentTokenRepository.saveAndFlush(token);
        addCookie(token, request, response);
    } catch (DataAccessException e) {
        log.error("Failed to save persistent token ", e);
    }
}
Also used : DataAccessException(org.springframework.dao.DataAccessException) Arrays(java.util.Arrays) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) PersistentTokenRepository(de.tum.in.www1.artemis.repository.PersistentTokenRepository) RandomUtil(de.tum.in.www1.artemis.service.util.RandomUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserRepository(de.tum.in.www1.artemis.repository.UserRepository) Service(org.springframework.stereotype.Service) UserDetails(org.springframework.security.core.userdetails.UserDetails) RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) CookieTheftException(org.springframework.security.web.authentication.rememberme.CookieTheftException) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) Serializable(java.io.Serializable) TimeUnit(java.util.concurrent.TimeUnit) LocalDate(java.time.LocalDate) AbstractRememberMeServices(org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) Authentication(org.springframework.security.core.Authentication) JHipsterProperties(io.github.jhipster.config.JHipsterProperties) Transactional(org.springframework.transaction.annotation.Transactional) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) DataAccessException(org.springframework.dao.DataAccessException)

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