use of org.springframework.security.core.userdetails.UsernameNotFoundException in project opencast by opencast.
the class LdapUserProviderInstance method loadUserFromLdap.
/**
* Loads a user from LDAP.
*
* @param userName
* the username
* @return the user
*/
protected User loadUserFromLdap(String userName) {
if (delegate == null || cache == null) {
throw new IllegalStateException("The LDAP user detail service has not yet been configured");
}
ldapLoads.incrementAndGet();
UserDetails userDetails = null;
Thread currentThread = Thread.currentThread();
ClassLoader originalClassloader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(LdapUserProviderFactory.class.getClassLoader());
try {
userDetails = delegate.loadUserByUsername(userName);
} catch (UsernameNotFoundException e) {
cache.put(userName, nullToken);
return null;
}
JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(organization);
// Get the roles and add the extra roles
Collection<GrantedAuthority> authorities = new HashSet<>();
authorities.addAll(userDetails.getAuthorities());
authorities.addAll(setExtraRoles);
Set<JaxbRole> roles = new HashSet<>();
if (authorities != null) {
/*
* Please note the prefix logic for roles:
*
* - Roles that start with any of the "exclude prefixes" are left intact
* - In any other case, the "role prefix" is prepended to the roles read from LDAP
*
* This only applies to the prefix addition. The conversion to uppercase is independent from these
* considerations
*/
for (GrantedAuthority authority : authorities) {
String strAuthority = authority.getAuthority();
boolean hasExcludePrefix = false;
for (String excludePrefix : setExcludePrefixes) {
if (strAuthority.startsWith(excludePrefix)) {
hasExcludePrefix = true;
break;
}
}
if (!hasExcludePrefix) {
strAuthority = rolePrefix + strAuthority;
}
// Finally, add the role itself
roles.add(new JaxbRole(strAuthority, jaxbOrganization));
}
}
User user = new JaxbUser(userDetails.getUsername(), PROVIDER_NAME, jaxbOrganization, roles);
cache.put(userName, user);
return user;
} finally {
currentThread.setContextClassLoader(originalClassloader);
}
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project opencast by opencast.
the class UserAndRoleDirectoryServiceImpl method loadUserByUsername.
/**
* {@inheritDoc}
*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
*/
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, org.springframework.dao.DataAccessException {
User user = loadUser(userName);
if (user == null)
throw new UsernameNotFoundException(userName);
// Store the user in the security service
securityService.setUser(user);
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
// Add additional roles from role providers
if (!InMemoryUserAndRoleProvider.PROVIDER_NAME.equals(user.getProvider())) {
for (RoleProvider roleProvider : roleProviders) {
List<Role> rolesForUser = roleProvider.getRolesForUser(userName);
for (Role role : rolesForUser) authorities.add(new SimpleGrantedAuthority(role.getName()));
}
}
authorities.add(new SimpleGrantedAuthority(securityService.getOrganization().getAnonymousRole()));
// need a non null password to instantiate org.springframework.security.core.userdetails.User
// but CAS authenticated users have no password
String password = user.getPassword() == null ? DEFAULT_PASSWORD : user.getPassword();
return new org.springframework.security.core.userdetails.User(user.getUsername(), password, user.canLogin(), true, true, true, authorities);
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project opencast by opencast.
the class LtiLaunchAuthenticationHandler method createAuthentication.
/**
* {@inheritDoc}
*
* @see org.springframework.security.oauth.provider.OAuthAuthenticationHandler#createAuthentication(javax.servlet.http.HttpServletRequest,
* org.springframework.security.oauth.provider.ConsumerAuthentication,
* org.springframework.security.oauth.provider.token.OAuthAccessProviderToken)
*/
@Override
public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication, OAuthAccessProviderToken authToken) {
// The User ID must be provided by the LTI consumer
String userIdFromConsumer = request.getParameter(LTI_USER_ID_PARAM);
if (StringUtils.isBlank(userIdFromConsumer)) {
logger.warn("Received authentication request without user id ({})", LTI_USER_ID_PARAM);
return null;
}
// Get the consumer guid if provided
String consumerGUID = request.getParameter(LTI_CONSUMER_GUID);
// This is an optional field, so it could be blank
if (StringUtils.isBlank(consumerGUID)) {
consumerGUID = "UnknownConsumer";
}
// We need to construct a complex ID to avoid confusion
userIdFromConsumer = LTI_USER_ID_PREFIX + LTI_ID_DELIMITER + consumerGUID + LTI_ID_DELIMITER + userIdFromConsumer;
// if this is a trusted consumer we trust their details
String oaAuthKey = request.getParameter("oauth_consumer_key");
if (highlyTrustedKeys.contains(oaAuthKey)) {
logger.debug("{} is a trusted key", oaAuthKey);
// If supplied we use the human readable name
String suppliedEid = request.getParameter("lis_person_sourcedid");
// This is an optional field it could be null
if (StringUtils.isNotBlank(suppliedEid)) {
userIdFromConsumer = suppliedEid;
} else {
// if no eid is set we use the supplied ID
userIdFromConsumer = request.getParameter(LTI_USER_ID_PARAM);
}
}
if (logger.isDebugEnabled()) {
logger.debug("LTI user id is : {}", userIdFromConsumer);
}
UserDetails userDetails = null;
Collection<GrantedAuthority> userAuthorities = null;
try {
userDetails = userDetailsService.loadUserByUsername(userIdFromConsumer);
// userDetails returns a Collection<? extends GrantedAuthority>, which cannot be directly casted to a
// Collection<GrantedAuthority>.
// On the other hand, one cannot add non-null elements or modify the existing ones in a Collection<? extends
// GrantedAuthority>. Therefore, we *must* instantiate a new Collection<GrantedAuthority> (an ArrayList in this
// case) and populate it with whatever elements are returned by getAuthorities()
userAuthorities = new HashSet<GrantedAuthority>(userDetails.getAuthorities());
// we still need to enrich this user with the LTI Roles
String roles = request.getParameter(ROLES);
String context = request.getParameter(CONTEXT_ID);
enrichRoleGrants(roles, context, userAuthorities);
} catch (UsernameNotFoundException e) {
// This user is known to the tool consumer, but not to Opencast. Create a user "on the fly"
userAuthorities = new HashSet<GrantedAuthority>();
// We should add the authorities passed in from the tool consumer?
String roles = request.getParameter(ROLES);
String context = request.getParameter(CONTEXT_ID);
enrichRoleGrants(roles, context, userAuthorities);
logger.info("Returning user with {} authorities", userAuthorities.size());
userDetails = new User(userIdFromConsumer, "oauth", true, true, true, true, userAuthorities);
}
// All users need the OAUTH, USER and ANONYMOUS roles
userAuthorities.add(new SimpleGrantedAuthority(ROLE_OAUTH_USER));
userAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
userAuthorities.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
Authentication ltiAuth = new PreAuthenticatedAuthenticationToken(userDetails, authentication.getCredentials(), userAuthorities);
SecurityContextHolder.getContext().setAuthentication(ltiAuth);
return ltiAuth;
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project FuryViewer by TheDoctor-95.
the class DomainUserDetailsService method loadUserByUsername.
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user -> {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(), grantedAuthorities);
}).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database"));
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project irida by phac-nml.
the class UserServiceImpl method loadUserByUsername.
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
@PreAuthorize("permitAll")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.trace("Loading user with username: [" + username + "].");
org.springframework.security.core.userdetails.User userDetails = null;
User u;
try {
u = userRepository.loadUserByUsername(username);
userDetails = new org.springframework.security.core.userdetails.User(u.getUsername(), u.getPassword(), u.getAuthorities());
} catch (EntityNotFoundException e) {
throw new UsernameNotFoundException(e.getMessage());
}
return userDetails;
}
Aggregations