List of usage examples for org.springframework.security.core.userdetails UsernameNotFoundException UsernameNotFoundException
public UsernameNotFoundException(String msg)
UsernameNotFoundException
with the specified message. From source file:org.mitre.openid.connect.assertion.JWTBearerAuthenticationProvider.java
/** * Try to validate the client credentials by parsing and validating the JWT. *//*from w w w . ja va 2 s. c o m*/ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { JWTBearerAssertionAuthenticationToken jwtAuth = (JWTBearerAssertionAuthenticationToken) authentication; try { ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getClientId()); JWT jwt = jwtAuth.getJwt(); JWTClaimsSet jwtClaims = jwt.getJWTClaimsSet(); // check the signature with nimbus if (jwt instanceof SignedJWT) { SignedJWT jws = (SignedJWT) jwt; JWSAlgorithm alg = jws.getHeader().getAlgorithm(); if (client.getTokenEndpointAuthSigningAlg() != null && !client.getTokenEndpointAuthSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } if (client.getTokenEndpointAuthMethod() == null || client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST)) { // this client doesn't support this type of authentication throw new AuthenticationServiceException("Client does not support this authentication method."); } else if ((client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) && (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384) || alg.equals(JWSAlgorithm.RS512) || alg.equals(JWSAlgorithm.ES256) || alg.equals(JWSAlgorithm.ES384) || alg.equals(JWSAlgorithm.ES512) || alg.equals(JWSAlgorithm.PS256) || alg.equals(JWSAlgorithm.PS384) || alg.equals(JWSAlgorithm.PS512))) || (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT) && (alg.equals(JWSAlgorithm.HS256) || alg.equals(JWSAlgorithm.HS384) || alg.equals(JWSAlgorithm.HS512)))) { // double-check the method is asymmetrical if we're in HEART mode if (config.isHeartMode() && !client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY)) { throw new AuthenticationServiceException("[HEART mode] Invalid authentication method"); } JWTSigningAndValidationService validator = validators.getValidator(client, alg); if (validator == null) { throw new AuthenticationServiceException("Unable to create signature validator for client " + client + " and algorithm " + alg); } if (!validator.validateSignature(jws)) { throw new AuthenticationServiceException( "Signature did not validate for presented JWT authentication."); } } else { throw new AuthenticationServiceException("Unable to create signature validator for method " + client.getTokenEndpointAuthMethod() + " and algorithm " + alg); } } // check the issuer if (jwtClaims.getIssuer() == null) { throw new AuthenticationServiceException("Assertion Token Issuer is null"); } else if (!jwtClaims.getIssuer().equals(client.getClientId())) { throw new AuthenticationServiceException( "Issuers do not match, expected " + client.getClientId() + " got " + jwtClaims.getIssuer()); } // check expiration if (jwtClaims.getExpirationTime() == null) { throw new AuthenticationServiceException("Assertion Token does not have required expiration claim"); } else { // it's not null, see if it's expired Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000)); if (now.after(jwtClaims.getExpirationTime())) { throw new AuthenticationServiceException( "Assertion Token is expired: " + jwtClaims.getExpirationTime()); } } // check not before if (jwtClaims.getNotBeforeTime() != null) { Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); if (now.before(jwtClaims.getNotBeforeTime())) { throw new AuthenticationServiceException( "Assertion Token not valid untill: " + jwtClaims.getNotBeforeTime()); } } // check issued at if (jwtClaims.getIssueTime() != null) { // since it's not null, see if it was issued in the future Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); if (now.before(jwtClaims.getIssueTime())) { throw new AuthenticationServiceException( "Assertion Token was issued in the future: " + jwtClaims.getIssueTime()); } } // check audience if (jwtClaims.getAudience() == null) { throw new AuthenticationServiceException("Assertion token audience is null"); } else if (!(jwtClaims.getAudience().contains(config.getIssuer()) || jwtClaims.getAudience().contains(config.getIssuer() + "token"))) { throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer() + " or " + (config.getIssuer() + "token") + " got " + jwtClaims.getAudience()); } // IFF we managed to get all the way down here, the token is valid // add in the ROLE_CLIENT authority Set<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities()); authorities.add(ROLE_CLIENT); return new JWTBearerAssertionAuthenticationToken(client.getClientId(), jwt, authorities); } catch (InvalidClientException e) { throw new UsernameNotFoundException("Could not find client: " + jwtAuth.getClientId()); } catch (ParseException e) { logger.error("Failure during authentication, error was: ", e); throw new AuthenticationServiceException("Invalid JWT format"); } }
From source file:de.whs.poodle.security.SpringSecurityConfig.java
@Bean public SwitchUserFilter switchUserFilter() { SwitchUserFilter filter = new SwitchUserFilter(); filter.setTargetUrl("/"); filter.setSwitchUserUrl("/switchUser"); filter.setExitUserUrl("/exitUser"); filter.setSwitchFailureUrl("/?switchUserFailed=1"); /*// ww w .j a v a 2s . co m * Called when a user is switched and returns the UserDetails. */ filter.setUserDetailsService(username -> { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); /* If no username is specified, we interpret this as "student mode" * (see <form> in instructor/navItems.html). */ if (username.isEmpty()) { // get the logged in student Instructor instructor = instructorRepo.getByUsername(auth.getName()); log.debug("{} switched to student mode", instructor.getUsername()); // create the fake student and switch Student fakeStudent = studentRepo.createFakeStudent(instructor.getId()); ArrayList<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_STUDENT")); authorities.add(new SimpleGrantedAuthority("ROLE_FAKE_STUDENT")); return new User(fakeStudent.getUsername(), "password", authorities); } else { // switch to specified user (admins only) boolean isAdmin = auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN")); if (!isAdmin) throw new ForbiddenException(); log.debug("User {} switching to {}", auth.getName(), username); ArrayList<GrantedAuthority> authorities = new ArrayList<>(); /* * username is the user that we switched to. We have no information * on whether he is a student or an instructor. Since he must be * in the database, let's just check there. */ if (studentRepo.studentExists(username)) authorities.add(new SimpleGrantedAuthority("ROLE_STUDENT")); else if (instructorRepo.exists(username)) authorities.add(new SimpleGrantedAuthority("ROLE_INSTRUCTOR")); else throw new UsernameNotFoundException("user doesn't exist."); return new User(username, "password", authorities); } }); return filter; }
From source file:ru.efo.security.ADUserDetailsService.java
@Override public ADUserDetails loadUserByUsername(String username) throws UsernameNotFoundException { DirContext context = null;/*from w w w. ja va 2 s. com*/ try { context = getDirContext(ldapAccount + userSuffix, ldapPassword); logger.log(Level.FINE, "Successfully logged on " + ldapUrl); return loadUserByUsername(context, username, null); } catch (NamingException ex) { logger.log(Level.SEVERE, "Could not login to " + ldapUrl, ex); throw new UsernameNotFoundException(ex.getMessage()); } finally { if (context != null) { try { context.close(); } catch (NamingException ex) { logger.log(Level.WARNING, "Could not close DirContext", ex); } } } }
From source file:ch.wisv.areafiftylan.users.service.UserServiceImpl.java
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userRepository.findOneByUsernameIgnoreCase(username) .orElseThrow(() -> new UsernameNotFoundException(username)); }
From source file:ru.efo.security.ADUserDetailsService.java
private ADUserDetails loadUserByUsername(DirContext context, String username, String password) throws UsernameNotFoundException { try {// ww w .ja v a2s. com SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // search for username NamingEnumeration<SearchResult> renum = context.search(userSearchBase, "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls); if (!renum.hasMoreElements()) { throw new UsernameNotFoundException("User '" + username + "' is not exist"); } SearchResult result = renum.next(); final Attributes attributes = result.getAttributes(); // User's display name String displayName = null; Attribute attr = attributes.get(displayNameAttribute); if (attr != null) { displayName = attr.get().toString(); } if (!StringUtils.hasText(displayName)) displayName = username; logger.log(Level.FINE, "Display name: " + displayName); // User's email String email = null; attr = attributes.get(emailAttribute); if (attr != null) { email = attr.get().toString(); } logger.log(Level.FINE, "E-mail: " + email); // User's phone number String phone = null; attr = attributes.get(phoneAttribute); if (attr != null) { phone = attr.get().toString(); } logger.log(Level.FINE, "Phone: " + phone); // Is user blocked boolean blocked = false; attr = attributes.get("userAccountControl"); if (attr != null) { blocked = (Long.parseLong(attr.get().toString()) & 2) != 0; } logger.log(Level.FINE, "Blocked: " + blocked); // describe roles and groups final Set<String> roles = new TreeSet<>(); final Set<String> groups = new TreeSet<>(); Attribute memberOf = attributes.get("memberOf"); describeRoles(context, memberOf, groups, roles); // Describe user primary role Attribute attrPrimaryGroupId = attributes.get("primaryGroupId"); Attribute attrObjectSid = attributes.get("objectSid"); if (attrPrimaryGroupId != null && attrObjectSid != null) { int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString()); byte[] objectSid = (byte[]) attrObjectSid.get(); // add primary group RID for (int i = 0; i < 4; i++) { objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF); primaryGroupId >>= 8; } StringBuilder tmp = new StringBuilder(); for (int i = 2; i <= 7; i++) { tmp.append(Integer.toHexString(objectSid[i] & 0xFF)); } // convert objectSid to String StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-") .append(Long.parseLong(tmp.toString(), 16)); // the sub authorities count int count = objectSid[1]; // add authorities for (int i = 0; i < count; i++) { tmp.setLength(0); int offset = i * 4; tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF), (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF), (objectSid[8 + offset] & 0xFF))); sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16)); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))", new Object[] { sidBuilder.toString() }, searchControls); if (renum.hasMoreElements()) { result = renum.next(); attr = result.getAttributes().get("distinguishedName"); describeRoles(context, attr, groups, roles); } } return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles); } catch (NamingException ex) { logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex); throw new UsernameNotFoundException(ex.getMessage()); } }
From source file:com.evolveum.midpoint.model.impl.security.AuthenticationEvaluatorImpl.java
@NotNull private MidPointPrincipal getAndCheckPrincipal(ConnectionEnvironment connEnv, String enteredUsername, boolean supportsActivationCheck) { if (StringUtils.isBlank(enteredUsername)) { recordAuthenticationFailure(enteredUsername, connEnv, "no username"); throw new UsernameNotFoundException("web.security.provider.invalid"); }/* w w w .java 2 s .co m*/ MidPointPrincipal principal; try { principal = userProfileService.getPrincipal(enteredUsername); } catch (ObjectNotFoundException e) { recordAuthenticationFailure(enteredUsername, connEnv, "no user"); throw new UsernameNotFoundException("web.security.provider.invalid"); } catch (SchemaException e) { recordAuthenticationFailure(enteredUsername, connEnv, "schema error"); throw new AccessDeniedException("web.security.provider.invalid"); } if (principal == null) { recordAuthenticationFailure(enteredUsername, connEnv, "no user"); throw new UsernameNotFoundException("web.security.provider.invalid"); } if (supportsActivationCheck && !principal.isEnabled()) { recordAuthenticationFailure(principal, connEnv, "user disabled"); throw new DisabledException("web.security.provider.disabled"); } return principal; }
From source file:com.sshdemo.common.security.manage.service.UserService.java
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { UserDetails userDetails = userCache.getUserFromCache(username); if (userDetails != null) { if (logger.isDebugEnabled()) { logger.debug("userDetails has cache"); }//from w w w. j ava 2 s. c om return userDetails; } if (logger.isDebugEnabled()) { logger.debug("userDetails has not cache"); } User user = userDao.get(username); if (user == null) { throw new UsernameNotFoundException("not fonund " + username); } userDetails = createUserDetails(user); userCache.putUserInCache(userDetails); return userDetails; }
From source file:de.thm.arsnova.service.UserServiceImpl.java
@Override public void authenticate(final UsernamePasswordAuthenticationToken token, final UserProfile.AuthProvider authProvider) { Authentication auth;/*from w ww.ja va2 s . c o m*/ switch (authProvider) { case LDAP: auth = ldapAuthenticationProvider.authenticate(token); break; case ARSNOVA: auth = daoProvider.authenticate(token); break; case ARSNOVA_GUEST: String id = token.getName(); boolean autoCreate = false; if (id == null || id.isEmpty()) { id = generateGuestId(); autoCreate = true; } UserDetails userDetails = guestUserDetailsService.loadUserByUsername(id, autoCreate); if (userDetails == null) { throw new UsernameNotFoundException("Guest user does not exist"); } auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); break; default: throw new IllegalArgumentException("Unsupported authentication provider"); } if (!auth.isAuthenticated()) { throw new BadRequestException(); } SecurityContextHolder.getContext().setAuthentication(auth); }
From source file:gr.abiss.calipso.userDetails.service.impl.UserDetailsServiceImpl.java
/** * @see org.springframework.social.security.SocialUserDetailsService#loadUserByUserId(java.lang.String) *//* w ww .j a v a 2 s. c o m*/ @Override public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException { ICalipsoUserDetails userDetails = null; // LOGGER.info("loadUserByUserId using: " + userId); LocalUser user = this.localUserService.findByUserNameOrEmail(userId); // LOGGER.info("loadUserByUserId user: " + user); if (user != null) { // LOGGER.info("loadUserByUserId about to copy user.roles: " + // user.getRoles()); // Role userRole = new Role(Role.ROLE_USER); // user.addRole(userRole); userDetails = UserDetails.fromUser(user); userDetails.setNotificationCount(this.baseNotificationService.countUnseen(user)); } if (user == null) { throw new UsernameNotFoundException("Could not match user id: " + userId); } return userDetails; }