Java 类org.springframework.security.authentication.AuthenticationCredentialsNotFoundException 实例源码

项目:AngularAndSpring    文件:MyAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();       
    Query query = new Query();
    query.addCriteria(Criteria.where("userId").is(name));
    MyUser user = operations.findOne(query, MyUser.class).block();
    String encryptedPw = null;
    try {
        encryptedPw = this.passwordEncryption.getEncryptedPassword(password, user.getSalt());
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        log.error("Pw decrytion error: ",e);
    }
    if(encryptedPw == null || !encryptedPw.equals(user.getPassword())) {
        throw new AuthenticationCredentialsNotFoundException("User: "+name+" not found.");
    }
    log.info("User: "+name+" logged in.");
    return new UsernamePasswordAuthenticationToken(
            name, password, user.getAuthorities());
}
项目:joal    文件:WebSocketAuthenticatorService.java   
public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final CharSequence username, final CharSequence authToken) throws AuthenticationException {
    if (StringUtils.isBlank(username)) {
        throw new AuthenticationCredentialsNotFoundException("Username was null or empty.");
    }
    if (StringUtils.isBlank(authToken)) {
        throw new AuthenticationCredentialsNotFoundException("Authentication token was null or empty.");
    }
    if (!appSecretToken.equals(authToken)) {
        throw new BadCredentialsException("Authentication token does not match the expected token");
    }

    // Everithing is fine, return an authenticated Authentication. (the constructor with grantedAuthorities auto set authenticated = true)
    // null credentials, we do not pass the password along to prevent security flaw
    return new UsernamePasswordAuthenticationToken(
            username,
            null,
            Collections.singleton((GrantedAuthority) () -> "USER")
    );
}
项目:OpenLRW    文件:AjaxAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");

    String key = (String) authentication.getPrincipal();
    String secret = (String) authentication.getCredentials();

    Org org;
    try {
      org = orgService.findByApiKeyAndApiSecret(key, secret);
    } 
    catch (OrgNotFoundException e) {
      throw new AuthenticationCredentialsNotFoundException(e.getMessage());
    }
    List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_ORG_ADMIN"));        
    UserContext userContext = UserContext.create(org.getMetadata().get(Vocabulary.TENANT), org.getSourcedId(), authorities);        
    return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
}
项目:item-shop-reactive-backend    文件:AuthorizationWebFilter.java   
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    return exchange.getPrincipal()
        .filter(p -> p instanceof Authentication)
        .then( p-> Mono.just((Authentication) p))
        .filter(authentication -> {
            return authentication != null && authentication.isAuthenticated();
        })
        .then(authentication -> {
            return source.getConfigAttributes(exchange).as( (Function<? super Flux<ConfigAttribute>, Mono<Boolean>>) a -> {
                return accessDecisionManager.decide(authentication, exchange, a);
            });
        })
        .filter(t -> t)
        .otherwiseIfEmpty(Mono.defer(() -> {
            return entryPoint.commence(exchange, new AuthenticationCredentialsNotFoundException("Not Found"));
        }))
        .then(sc -> {
            return chain.filter(exchange);
        });
}
项目:secrets-proxy    文件:JwtTokenService.java   
/**
 * Retrieves the JWT authentication token from http request.
 *
 * @param req http request.
 * @return {@link JwtAuthToken} or <code>null</code> if the Bearer token is not present or empty.
 */
public @Nullable
JwtAuthToken getAccessToken(@Nonnull HttpServletRequest req) {
    log.debug("Getting the access token for " + req.getRequestURI());

    String bearerToken = req.getHeader(tokenHeader);
    if (bearerToken != null) {
        // Make sure it's valid token type.
        if (!bearerToken.startsWith(tokenType)) {
            throw new AuthenticationCredentialsNotFoundException("Invalid Authorization Token.");
        }

        String jwtToken = bearerToken.replaceFirst(tokenType, "").trim();
        if (!isEmpty(jwtToken)) {
            return new JwtAuthToken("JwtToken", jwtToken, Collections.emptyList());
        }
    }

    log.debug("JWT Bearer token is null/empty for " + req.getRequestURI());
    return null;
}
项目:spring-security-reactive    文件:AuthorizationWebFilter.java   
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    return exchange.getPrincipal()
        .filter(p -> p instanceof Authentication)
        .flatMap( p-> Mono.just((Authentication) p))
        .filter(authentication -> {
            return authentication != null && authentication.isAuthenticated();
        })
        .flatMap(authentication -> {
            return source.getConfigAttributes(exchange).as( (Function<? super Flux<ConfigAttribute>, Mono<Boolean>>) a -> {
                return accessDecisionManager.decide(authentication, exchange, a);
            });
        })
        .filter(t -> t)
        .switchIfEmpty(Mono.defer(() -> {
            return entryPoint.commence(exchange, new AuthenticationCredentialsNotFoundException("Not Found"));
        }))
        .flatMap(sc -> {
            return chain.filter(exchange);
        });
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) 
        throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, 
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {     

    checkEnteredCredentials(connEnv, authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    if (checkCredentials(principal, authnCtx, connEnv)) {

        recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, 
                authnCtx.getEnteredCredential(), principal.getAuthorities());
        return token;

    } else {
        recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) 
        throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, 
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {     

    checkEnteredCredentials(connEnv, authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    if (checkCredentials(principal, authnCtx, connEnv)) {
        return userType;
    } else {
        recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials,
        P passwordCredentialsPolicy) {
    if (credentials == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored credential value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad");
    }

    validateCredentialNotNull(connEnv, principal, credentials);

    if (passwordCredentialsPolicy == null) {
        return;
    }

    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        MetadataType credentialMetedata = credentials.getMetadata();
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal, connEnv, "password expired");
                throw new CredentialsExpiredException("web.security.provider.password.bad");
            }
        }
    }
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata, 
        CredentialPolicyType passwordCredentialsPolicy) {
    if (protectedString == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }
    if (passwordCredentialsPolicy == null) {
        return;
    }
    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal, connEnv, "password expired");
                throw new CredentialsExpiredException("web.security.provider.password.bad");
            }
        }
    }
}
项目:cibet    文件:SpringSecurityActuator.java   
private Authentication swapAuthentication() {
   if (secondPrincipal) {
      Object secP = Context.internalSessionScope().getProperty(InternalSessionScope.SECOND_PRINCIPAL);
      if (secP == null) {
         throw new AuthenticationCredentialsNotFoundException(
               "No Authentication object found in CibetContext.getSecondPrincipal()");
      }

      if (!(secP instanceof Authentication)) {
         throw new AccessDeniedException("CibetContext.getSecondPrincipal() is expected to be of type "
               + Authentication.class.getName() + " but is of type " + secP.getClass().getName());
      }

      log.debug("SpringSecurity actuator for second principal " + secP);
      Authentication auth = (Authentication) secP;
      Authentication original = SecurityContextHolder.getContext().getAuthentication();
      SecurityContextHolder.getContext().setAuthentication(auth);
      return original;
   }
   return null;
}
项目:Open-Clinica-Data-Uploader    文件:ListStudiesResponseHandler.java   
public static List<Study> parseListStudiesResponse(SOAPMessage response) throws Exception { //TODO: handle exception
    Document document = toDocument(response);
    String result = isAuthFailure(document);
    if (! StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList studyNodes = (NodeList) xpath.evaluate("//listAllResponse/studies/study", document, XPathConstants.NODESET);
    List<Study> studiesParsed = new ArrayList<>();
    for (int i = 0; i < studyNodes.getLength(); i++) {
        Node studyNode = studyNodes.item(i);
        Study study = parseStudy(studyNode);
        studiesParsed.add(study);
    }
    return studiesParsed;
}
项目:Open-Clinica-Data-Uploader    文件:SOAPResponseHandler.java   
/**
 * Checks if an error occurred on the OpenClinica-side and reports it back as the
 * return value
 *
 * @param response the SOAP-response.
 * @return a non <code>null</code> error code.message if an error occurred. Some are reported by the OpenClinica-WS
 * instance at url. Returns <code>null</code> if everything went OK.
 * @throws Exception if a technical error occurs.
 */

public static String parseOpenClinicaResponse(SOAPMessage response, String xPathToResponse) throws Exception {
    Document document = toDocument(response);
    System.out.println("SOAP:----->\n" + SoapUtils.soapMessageToString(response));
    String result = isAuthFailure(document);
    if (! StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node importDataResponseNode = (Node) xpath.evaluate(xPathToResponse, document, XPathConstants.NODE);
    Node resultNode = (Node) xpath.evaluate("//result", importDataResponseNode, XPathConstants.NODE);
    if ("fail".equalsIgnoreCase(resultNode.getTextContent())) {
        Node errorNode = (Node) xpath.evaluate("//error", importDataResponseNode, XPathConstants.NODE);
        return errorNode.getTextContent();
    }
    return null;
}
项目:Open-Clinica-Data-Uploader    文件:IsStudySubjectResponseHandler.java   
/**
 * Retrieve the study subjects technical ID; <code>studuSubjectOID</code> in OpenClinica
 * terminology.
 * @param response the SOAP-response
 * @return <code>null</code> if the provided subject label does not exist in the study otherwise
 * the <code>studySubjectOID</code>
 * @throws Exception on authentication failures or response structure mismatch
 */
public static String parseIsStudySubjectResponse(SOAPMessage response) throws Exception {
    if (response == null) {
        return null;
    }
    Document document = toDocument(response);
    String result = isAuthFailure(document);
    if (! StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node createResponseNode = (Node) xpath.evaluate("//createResponse", document, XPathConstants.NODE);
    Node resultNode = (Node) xpath.evaluate("//result", createResponseNode, XPathConstants.NODE);
    if ("Success".equals(resultNode.getTextContent())) {
        Node subjectOIDNode = (Node) xpath.evaluate("//subjectOID", createResponseNode, XPathConstants.NODE);
        if (subjectOIDNode != null) {
            return subjectOIDNode.getTextContent();
        }
        throw new IllegalStateException("SubjectOID node is null");
    }
    else {
        return null;
    }
}
项目:spring-json-sms-gateway    文件:SMS.java   
public SMS(JSON_SMS jsonSMS, int user_id) throws GatewayException {

        if (user_id < 1)
            throw new AuthenticationCredentialsNotFoundException("no user id on sms repository");

        this.id = jsonSMS.getId();
        this.user_id = user_id;
        this.sender = jsonSMS.getSender();
        this.msisdn = jsonSMS.getMsisdn();
        this.text = jsonSMS.getText();
        this.subid = jsonSMS.getSubid();
        this.ackurl = jsonSMS.getAck_url();
        this.datetimeScheduled = jsonSMS.getDatetime();
        this.test = jsonSMS.isTest();

        if (datetimeScheduled != null)
            sms_status = SMS_Status.SCHEDULED;
        else
            sms_status = SMS_Status.ACCEPTD;

    }
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx)
        throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {

    checkEnteredCredentials(connEnv, authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    if (checkCredentials(principal, authnCtx, connEnv)) {

        recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
                authnCtx.getEnteredCredential(), principal.getAuthorities());
        return token;

    } else {
        recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx)
        throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {

    checkEnteredCredentials(connEnv, authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    if (checkCredentials(principal, authnCtx, connEnv)) {
        return userType;
    } else {
        recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials,
        P passwordCredentialsPolicy) {
    if (credentials == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored credential value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad");
    }

    validateCredentialNotNull(connEnv, principal, credentials);

    if (passwordCredentialsPolicy == null) {
        return;
    }

    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        MetadataType credentialMetedata = credentials.getMetadata();
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal, connEnv, "password expired");
                throw new CredentialsExpiredException("web.security.provider.credential.expired");
            }
        }
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata,
        CredentialPolicyType passwordCredentialsPolicy) {
    if (protectedString == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }
    if (passwordCredentialsPolicy == null) {
        return;
    }
    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal, connEnv, "password expired");
                throw new CredentialsExpiredException("web.security.provider.credential.expired");
            }
        }
    }
}
项目:syncope    文件:AuthDataAccessor.java   
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
    synchronized (this) {
        if (jwtSSOProviders == null) {
            jwtSSOProviders = new HashMap<>();

            implementationLookup.getJWTSSOProviderClasses().stream().
                    map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().
                    createBean(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true)).
                    forEachOrdered(jwtSSOProvider -> {
                        jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider);
                    });
        }
    }

    if (issuer == null) {
        throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
    }
    JWTSSOProvider provider = jwtSSOProviders.get(issuer);
    if (provider == null) {
        throw new AuthenticationCredentialsNotFoundException(
                "Could not find any registered JWTSSOProvider for issuer " + issuer);
    }

    return provider;
}
项目:vaadin4spring    文件:AbstractVaadinSecurityConfiguration.java   
@Bean(name = CURRENT_USER_BEAN)
Authentication currentUser() {

    return ProxyFactory.getProxy(Authentication.class, new MethodInterceptor() {

        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
            if (authentication == null) {
                throw new AuthenticationCredentialsNotFoundException("No authentication found in current security context");
            }
            return invocation.getMethod().invoke(authentication, invocation.getArguments());
        }

    });

}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx)
        throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {

    checkEnteredCredentials(connEnv, authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    if (checkCredentials(principal, authnCtx, connEnv)) {

        recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
                authnCtx.getEnteredCredential(), principal.getAuthorities());
        return token;

    } else {
        recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx)
        throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {

    checkEnteredCredentials(connEnv, authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    if (checkCredentials(principal, authnCtx, connEnv)) {
        return userType;
    } else {
        recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials,
        P passwordCredentialsPolicy) {
    if (credentials == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored credential value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad");
    }

    validateCredentialNotNull(connEnv, principal, credentials);

    if (passwordCredentialsPolicy == null) {
        return;
    }

    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        MetadataType credentialMetedata = credentials.getMetadata();
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal, connEnv, "password expired");
                throw new CredentialsExpiredException("web.security.provider.credential.expired");
            }
        }
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata,
        CredentialPolicyType passwordCredentialsPolicy) {
    if (protectedString == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }
    if (passwordCredentialsPolicy == null) {
        return;
    }
    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal, connEnv, "password expired");
                throw new CredentialsExpiredException("web.security.provider.credential.expired");
            }
        }
    }
}
项目:metka    文件:AuthenticationUtil.java   
public static boolean authenticate(MetkaAuthenticationDetails details) {
    SecurityContext context = SecurityContextHolder.getContext();
    if(context == null) {
        Logger.error(AuthenticationUtil.class, "Authentication was requested but no SecurityContext was found");
        throw new AuthenticationCredentialsNotFoundException("Couldn't find security context");
    }
    /*Authentication authentication = context.getAuthentication();
    if(authentication != null && authentication.getDetails() != null) {
        logger.error("Authentication details already set");
        throw new AuthenticationCredentialsNotFoundException("Authentication details already set");
    }*/
    PreAuthenticatedAuthenticationToken auth = new PreAuthenticatedAuthenticationToken(details.getUserName(), "credentials", details.getGrantedAuthorities());
    auth.setDetails(details);
    context.setAuthentication(auth);
    return true;
}
项目:metka    文件:AuthenticationUtil.java   
private static MetkaAuthenticationDetails getDetails() throws AuthenticationCredentialsNotFoundException {
    SecurityContext context = SecurityContextHolder.getContext();
    if(context == null) {
        Logger.error(AuthenticationUtil.class, "User name was requested but no SecurityContext was found");
        throw new AuthenticationCredentialsNotFoundException("Couldn't find security context");
    }
    Authentication authentication = context.getAuthentication();
    if(authentication == null) {
        Logger.error(AuthenticationUtil.class, "SecurityContext was found but no authentication details were set");
        throw new AuthenticationCredentialsNotFoundException("Couldn't find Authentication information");
    }
    if(authentication.getDetails() == null || !(authentication.getDetails() instanceof MetkaAuthenticationDetails)) {
        Logger.error(AuthenticationUtil.class, "Authentication details are null or don't match expected format");
        throw new AuthenticationCredentialsNotFoundException("Authentication details are null or not in expected format");
    }
    return (MetkaAuthenticationDetails)authentication.getDetails();
}
项目:spring-boot-start-current    文件:ContextUtils.java   
/**
 * 得到凭证
 */
private static Authentication getAuthentication () {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if ( Objects.isNull( authentication ) ) {
        throw new AuthenticationCredentialsNotFoundException( "未授权" );
    }
    return authentication;
}
项目:spring-boot-start-current    文件:AuthenticationController.java   
/**
 * 刷新并认证token
 *
 * @return token
 */
@PutMapping
public ResponseEntity refreshAndGetAuthenticationToken ( @RequestHeader( "${jwt.header:Authorization}" ) final String token ) {
    String username = jwtTokenUtil.getUsernameFromToken( token );
    if ( StringUtils.isBlank( username ) ) {
        throw new AuthenticationCredentialsNotFoundException( "无效token" );
    }
    JwtUser user = ( JwtUser ) userDetailsService.loadUserByUsername( username );
    if ( jwtTokenUtil.canTokenBeRefreshed( token , user.getLastPasswordResetDate() ) ) {
        String refreshedToken = jwtTokenUtil.refreshToken( token );
        return new ResponseEntityPro().add( "token" , refreshedToken ).buildOk();
    } else {
        return ResponseEntityPro.badRequest( "原 token 无效" );
    }
}
项目:nifi-registry    文件:AuthenticationCredentialsNotFoundExceptionMapper.java   
@Override
public Response toResponse(AuthenticationCredentialsNotFoundException exception) {
    // log the error
    logger.info(String.format("No valid credentials were found in the request: %s. Returning %s response.", exception, Response.Status.FORBIDDEN));

    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    return Response.status(Response.Status.FORBIDDEN).entity("Access is denied.").type("text/plain").build();
}
项目:secrets-proxy    文件:TokenAuthProcessingFilter.java   
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
    log.debug("Attempting token authentication.");
    JwtAuthToken jwtAuthToken = jwtTokenService.getAccessToken(req);
    if (jwtAuthToken == null) {
        throw new AuthenticationCredentialsNotFoundException("Authorization header is missing.");
    }
    return getAuthenticationManager().authenticate(jwtAuthToken);
}
项目:engerek    文件:SecurityQuestionAuthneticationEvaluatorImpl.java   
@Override
protected void validateCredentialNotNull(ConnectionEnvironment connEnv, MidPointPrincipal principal,
        SecurityQuestionsCredentialsType credential) {
    List<SecurityQuestionAnswerType> securityQuestionsAnswers = credential.getQuestionAnswer();

    if (securityQuestionsAnswers == null || securityQuestionsAnswers.isEmpty()) {
        recordAuthenticationFailure(principal, connEnv, "no stored security questions");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }

}
项目:engerek    文件:NonceAuthenticationEvaluatorImpl.java   
@Override
protected void validateCredentialNotNull(ConnectionEnvironment connEnv, MidPointPrincipal principal,
        NonceType credential) {
    if (credential.getValue() == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }

}
项目:engerek    文件:PasswordAuthenticationEvaluatorImpl.java   
@Override
protected void validateCredentialNotNull(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, PasswordType credential) {

    ProtectedStringType protectedString = credential.getValue();

    if (protectedString == null) {
        recordAuthenticationFailure(principal, connEnv, "no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }

}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, ConnectionEnvironment connEnv) {

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    if (credentials == null || getCredential(credentials) == null) {
        recordAuthenticationFailure(principal, connEnv, "no credentials in user");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
    }

    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    // Lockout
    if (isLockedOut(getCredential(credentials), credentialsPolicy)) {
        recordAuthenticationFailure(principal, connEnv, "password locked-out");
        throw new LockedException("web.security.provider.locked");
    }

    if (suportsAuthzCheck()) {
        // Authorizations
        if (!hasAnyAuthorization(principal)) {
            recordAuthenticationFailure(principal, connEnv, "no authorizations");
            throw new DisabledException("web.security.provider.access.denied");
        }
    }

    // Password age
    checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy);

    return passwordMatches(connEnv, principal, getCredential(credentials), authnCtx);
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
/**
 * Special-purpose method used for Web Service authentication based on javax.security callbacks.
 * 
 * In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the
 * AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work.
 */
public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername) 
        throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException, 
        CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {     

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    if (credentials == null) {
        recordAuthenticationFailure(principal, connEnv, "no credentials in user");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
    }
    PasswordType passwordType = credentials.getPassword();
    SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
    PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy);

    // Lockout
    if (isLockedOut(passwordType, passwordCredentialsPolicy)) {
        recordAuthenticationFailure(principal, connEnv, "password locked-out");
        throw new LockedException("web.security.provider.locked");
    }

    // Authorizations
    if (!hasAnyAuthorization(principal)) {
        recordAuthenticationFailure(principal, connEnv, "no authorizations");
        throw new AccessDeniedException("web.security.provider.access.denied");
    }

    // Password age
    checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(), passwordCredentialsPolicy);

    return getPassword(connEnv, principal, passwordType.getValue());
}
项目:Open-Clinica-Data-Uploader    文件:GetStudyMetadataResponseHandler.java   
public static Document getOdm(SOAPMessage response) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException, SOAPException, TransformerException {
    Document document = toDocument(response);
    String result = isAuthFailure(document);
    if (!StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    Node odmCDATANode = (Node) xpath.evaluate(odmSelector, document, XPathConstants.NODE);
    if (odmCDATANode == null) {
        return null;
    }
    String textContent = odmCDATANode.getTextContent(); //TODO: Add handling case when no ODM is served by OC
    Document odm = SoapUtils.unEscapeCDATAXML(textContent);
    return odm;
}
项目:Open-Clinica-Data-Uploader    文件:OCResponseHandler.java   
public static String parseGenericResponse(SOAPMessage response, String selector) throws Exception {
    Document document = toDocument(response);
    System.out.println("-->" + SoapUtils.soapMessageToString(response));
    if (! isAuthFailure(document).equals("")) {
        throw new AuthenticationCredentialsNotFoundException("Authentication against OpenClinica unsuccessfull");
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node importDataResponseNode = (Node) xpath.evaluate(selector, document, XPathConstants.NODE);
    Node resultNode = (Node) xpath.evaluate("//result", importDataResponseNode, XPathConstants.NODE);
    if ("fail".equalsIgnoreCase(resultNode.getTextContent())) {
        Node errorNode = (Node) xpath.evaluate("//error", importDataResponseNode, XPathConstants.NODE);
        return errorNode.getTextContent();
    }
    return null;
}
项目:communote-server    文件:SwitchUserHelper.java   
/**
 * Create an authentication for the target user that will contain the current auth as granted
 * authentication. This method does not do any checking if the current user is actually alowed
 * to do the switching (therefore it is a private method).
 *
 * @param targetUser
 *            the user for the new authentication
 * @return the authentication of the target user
 */
private static Authentication createSwitchUserAuthentication(User targetUser) {

    UsernamePasswordAuthenticationToken targetUserAuthentication;

    Authentication currentAuth;

    try {
        // Check first if we are already switched.
        currentAuth = removeSwitchedUser();
    } catch (AuthenticationCredentialsNotFoundException e) {
        currentAuth = SecurityContextHolder.getContext().getAuthentication();
    }

    org.springframework.security.core.userdetails.User targetUserDetails = new UserDetails(
            targetUser, targetUser.getAlias());

    GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_SWITCH_ORGINAL_USER,
            currentAuth);

    // add the new switch user authority
    List<GrantedAuthority> newAuths = new ArrayList<GrantedAuthority>();
    for (GrantedAuthority authority : targetUserDetails.getAuthorities()) {
        // only use roles that are allowed
        if (ALLOWED_SWITCH_ROLE_NAMES.contains(authority.getAuthority())) {
            newAuths.add(authority);
        }
    }
    newAuths.add(switchAuthority);

    // create the new authentication token
    targetUserAuthentication = new UsernamePasswordAuthenticationToken(targetUserDetails,
            targetUser.getPassword(), newAuths);

    return targetUserAuthentication;
}