Java Code Examples for org.springframework.security.core.Authentication#isAuthenticated()

The following examples show how to use org.springframework.security.core.Authentication#isAuthenticated() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicAuthenticationInterceptor.java    From grpc-spring-security-demo with MIT License 6 votes vote down vote up
private boolean authenticationIsRequired(String username) {
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if (Objects.isNull(existingAuth) || !existingAuth.isAuthenticated()) {
        return true;
    }

    if (existingAuth instanceof UsernamePasswordAuthenticationToken
            && !existingAuth.getName().equals(username)) {
        return true;
    }

    if (existingAuth instanceof AnonymousAuthenticationToken) {
        return true;
    }

    return false;
}
 
Example 2
Source File: MolgenisChangePasswordFilter.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;

  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if (authentication instanceof UsernamePasswordAuthenticationToken
      && authentication.isAuthenticated()
      && !authentication.getName().equals(ANONYMOUS_USERNAME)
      && !httpRequest.getRequestURI().equalsIgnoreCase(CHANGE_PASSWORD_URI)) {
    User user = userService.getUser(authentication.getName());
    if (user == null) {
      throw new RuntimeException("Unknown username [" + authentication.getName() + "]");
    }

    if (user.isChangePassword() != null && user.isChangePassword()) {
      redirectStrategy.sendRedirect(httpRequest, httpResponse, CHANGE_PASSWORD_URI);
      return;
    }
  }

  chain.doFilter(request, response);
}
 
Example 3
Source File: TenantBasedPermissionEvaluator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasPermission(Authentication authentication, Object target, Object permission) {
    if (!authentication.isAuthenticated()) {
        return true;
    }
    if (target instanceof Optional) {
        target = ((Optional<?>) target).orElse(null);
    }
    if (target == null) {
        return false;
    }
    CloudbreakUser cloudbreakUser = restRequestThreadLocalService.getCloudbreakUser();
    Collection<?> targets = target instanceof Collection ? (Collection<?>) target : Collections.singleton(target);
    return targets.stream().allMatch(t -> {
        if (!(t instanceof Clustered)) {
            return true;
        }
        Cluster cluster = ((Clustered) t).getCluster();
        if (cluster == null || !cloudbreakUser.getTenant().contentEquals(cluster.getClusterPertain().getTenant())) {
            return false;
        }
        cloudbreakAuthorizationService.hasAccess(cluster.getStackCrn(), cloudbreakUser.getUserId(), cloudbreakUser.getTenant(), permission.toString());
        return true;
    });
}
 
Example 4
Source File: X509AuthenticationFilter.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
private void authenticateIfPossible(ServletRequest request) {
    if (!request.isSecure()) {
        return;
    }

    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

    if (certs == null || certs.length == 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to get certificates in request from " + HttpRequestUtil.getClientString(request));
        }
        return;
    }

    Authentication authentication = authenticationManager.authenticate(new X509AuthenticationToken(certs));
    if (authentication.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
 
Example 5
Source File: AcTokenGranter.java    From cola with MIT License 6 votes vote down vote up
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
	Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
	String authorizationCode = parameters.get("authorizationCode");
	String provider = parameters.get("provider");

	Authentication userAuth = new AcAuthenticationToken(authorizationCode, provider);
	((AbstractAuthenticationToken) userAuth).setDetails(parameters);
	try {
		userAuth = authenticationManager.authenticate(userAuth);
	} catch (AccountStatusException | BadCredentialsException ase) {
		//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
		throw new InvalidGrantException(ase.getMessage());
	}
	if (userAuth == null || !userAuth.isAuthenticated()) {
		throw new InvalidGrantException("Could not authenticate user: " + authorizationCode);
	}

	OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
	return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
 
Example 6
Source File: AuthenticationTestAction.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
private void performLdapTest(FieldModel fieldModel, FieldAccessor registeredFieldValues) throws IntegrationException {
    logger.info("LDAP enabled testing LDAP authentication.");
    String userName = fieldModel.getFieldValue(AuthenticationUIConfig.TEST_FIELD_KEY_USERNAME).orElse("");
    Optional<LdapAuthenticationProvider> ldapProvider = ldapManager.createAuthProvider(registeredFieldValues);
    String errorMessage = String.format("Ldap Authentication test failed for the test user %s.  Please check the LDAP configuration.", userName);
    Map<String, String> errorsMap = new HashMap<>();
    if (!ldapProvider.isPresent()) {
        errorsMap.put(AuthenticationDescriptor.KEY_LDAP_ENABLED, errorMessage);
    } else {
        Authentication pendingAuthentication = new UsernamePasswordAuthenticationToken(userName,
            fieldModel.getFieldValue(AuthenticationUIConfig.TEST_FIELD_KEY_PASSWORD).orElse(""));
        Authentication authentication = ldapProvider.get().authenticate(pendingAuthentication);
        if (!authentication.isAuthenticated()) {
            errorsMap.put(AuthenticationDescriptor.KEY_LDAP_ENABLED, errorMessage);
        }
        authentication.setAuthenticated(false);
    }

    if (!errorsMap.isEmpty()) {
        throw new AlertFieldException(errorsMap);
    }
}
 
Example 7
Source File: SpringSecurityAuditorAware.java    From galeb with Apache License 2.0 6 votes vote down vote up
public String getCurrentAuditor() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUser = "anonymousUser";

        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                currentUser = ((UserDetails)principal).getUsername();
            } else {
                currentUser = principal.toString();
            }
        }

        return currentUser;
    }
 
Example 8
Source File: SecurityContextUser.java    From juiser with Apache License 2.0 5 votes vote down vote up
protected Authentication getValidAuthentication() {
    SecurityContext ctx = getSecurityContext();
    if (ctx != null) {
        Authentication authc = ctx.getAuthentication();
        if (authc != null && !(authc instanceof AnonymousAuthenticationToken) && authc.isAuthenticated()) {
            return authc;
        }
    }
    return null;
}
 
Example 9
Source File: SocialAuthenticationFilter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a user is already authenticated.
 * @return
 */
private boolean authenticated() {
    Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    return authentication != null && authentication.isAuthenticated()
            && !(authentication instanceof AnonymousAuthenticationToken);
}
 
Example 10
Source File: AuthenticationFilter.java    From learning-code with Apache License 2.0 5 votes vote down vote up
private Authentication tryToAuthenticate(Authentication requestAuth) {
    Authentication responseAuth = getAuthenticationManager().authenticate(requestAuth);
    if (responseAuth == null || !responseAuth.isAuthenticated()) {
        throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
    }
    log.debug("User successfully authenticated");
    return responseAuth;
}
 
Example 11
Source File: AuthenticationService.java    From market with MIT License 5 votes vote down vote up
public boolean authenticate(String login, String password) {
	try {
		Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
		SecurityContextHolder.getContext().setAuthentication(auth);
		return auth.isAuthenticated();
	} catch (BadCredentialsException ex) {
		// todo
		return false;
	}
}
 
Example 12
Source File: HttpClientChooser.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isRequestToSign() {
    if (!Boolean.TRUE.equals(RequestContext.getCurrentContext().get(AUTHENTICATION_SCHEME_BY_PASS_KEY))) {
        return false;
    }

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) return false;
    if (!(authentication.getCredentials() instanceof X509Certificate)) return false;

    return authentication.isAuthenticated();
}
 
Example 13
Source File: HttpAuthenticationFilter.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
private void tryAuthenticate(Authentication requestAuth) {
    Authentication authentication = authenticationManager.authenticate(requestAuth);
    if (authentication == null || !authentication.isAuthenticated()) {
        throw new InternalAuthenticationServiceException("Unable to authenticate user with provided credentials");
    }
    logger.debug("Successfully authenticated");
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 14
Source File: KerberosAuthenticationProcessingFilter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (skipIfAlreadyAuthenticated) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth != null && existingAuth.isAuthenticated()
            && !(existingAuth instanceof AnonymousAuthenticationToken)) {
            chain.doFilter(request, response);
            return;
        }
    }
    String header = request.getHeader("Authorization");
    if ((header != null) && header.startsWith("Negotiate ")) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(10).getBytes(StandardCharsets.UTF_8);
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(authenticationRequest);
        } catch (AuthenticationException e) {
            //That shouldn't happen, as it is most likely a wrong
            //configuration on the server side
            logger.warn("Negotiate Header was invalid: " + header, e);
            SecurityContextHolder.clearContext();
            if (failureHandler != null) {
                failureHandler.onAuthenticationFailure(request, response, e);
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.flushBuffer();
            }
            return;
        }
        sessionStrategy.onAuthentication(authentication, request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        if (successHandler != null) {
            successHandler.onAuthenticationSuccess(request, response, authentication);
        }
    }
    chain.doFilter(request, response);
}
 
Example 15
Source File: GrantedAuthorityAuthorizer.java    From nifi-minifi with Apache License 2.0 4 votes vote down vote up
@Override
public void authorize(Authentication authentication, UriInfo uriInfo) throws AuthorizationException {
    if (authentication == null) {
        throw new AuthorizationException("null authentication object provided.");
    }

    if (!authentication.isAuthenticated()) {
        throw new AuthorizationException(authentication + " not authenticated.");
    }

    Set<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());

    String defaultAction = as(String.class, grantedAuthorityMap.getOrDefault(DEFAULT_ACTION, DENY));
    String path = uriInfo.getAbsolutePath().getPath();
    Map<String, Object> pathAuthorizations = as(Map.class, grantedAuthorityMap.get("Paths"));
    if (pathAuthorizations == null && !ALLOW.equalsIgnoreCase(defaultAction)) {
        throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow");
    }

    Map<String, Object> pathAuthorization = as(Map.class, pathAuthorizations.get(path));
    if (pathAuthorization == null && !ALLOW.equalsIgnoreCase(defaultAction)) {
        throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow");
    }
    defaultAction = as(String.class, pathAuthorization.getOrDefault(DEFAULT_ACTION, defaultAction));
    List<Map<String, Object>> actions = as(List.class, pathAuthorization.get("Actions"));
    MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
    for (Map<String, Object> action : actions) {
        String ruleAction = as(String.class, action.get("Action"));
        if (ruleAction == null || !(ALLOW.equalsIgnoreCase(ruleAction) || DENY.equalsIgnoreCase(ruleAction))) {
            throw new AuthorizationException("Expected Action key of allow or deny for " + action);
        }
        String authorization = as(String.class, action.get("Authorization"));
        if (authorization != null && !authorities.contains(authorization)) {
            continue;
        }
        Map<String, Object> parameters = as(Map.class, action.get("Query Parameters"));
        if (parameters != null) {
            boolean foundParameterMismatch = false;
            for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
                Object value = parameter.getValue();
                if (value instanceof String) {
                    value = Arrays.asList((String)value);
                }
                if (!Objects.equals(queryParameters.get(parameter.getKey()), value)) {
                    foundParameterMismatch = true;
                    break;
                }
            }
            if (foundParameterMismatch) {
                continue;
            }
        }
        if (ALLOW.equalsIgnoreCase(ruleAction)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Action " + action + "matched which resulted in " + ruleAction);
            }
            return;
        } else {
            throw new AuthorizationException("Action " + action + " matched which resulted in " + ruleAction);
        }
    }
    if (ALLOW.equalsIgnoreCase(defaultAction)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found no matching actions so falling back to default action " + defaultAction);
        }
    } else {
        throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow");
    }
}
 
Example 16
Source File: LockingAndVersioningRepositoryImpl.java    From spring-content with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
 @Transactional
 public <S extends T> S version(S currentVersion, VersionInfo info) {

 	Authentication authentication = auth.getAuthentication();
     if (authentication == null || !authentication.isAuthenticated()) {
         throw new SecurityException("no principal");
     }

     Object id = getId(currentVersion);
     if (id == null) return null;

     if (!isHead(currentVersion)) {
         throw new LockingAndVersioningException("not head");
     }

     Principal lockOwner = lockingService.lockOwner(id);
     if (lockOwner  == null || !authentication.isAuthenticated() || authentication.getName().equals(lockOwner.getName()) == false) {
         throw new LockOwnerException("not lock owner");
     }

     S newVersion = null;
     if (!isPrivateWorkingCopy(currentVersion)) {

         S ancestorRoot;
         if (isAnestralRoot(currentVersion)) {
             currentVersion = (S) versioner.establishAncestralRoot(currentVersion);
             ancestorRoot = currentVersion;
         }
         else {
             Object ancestorRootId = getAncestralRootId(currentVersion);
             ancestorRoot = em.find((Class<S>) currentVersion.getClass(), ancestorRootId);
             if (ancestorRoot == null) {
                 throw new LockingAndVersioningException(format("ancestor root not found: %s", ancestorRootId));
             }
         }

         newVersion = (S) cloner.clone(currentVersion);

         this.unlock(currentVersion);

         newVersion = (S) versioner
                 .establishSuccessor(newVersion, info.getNumber(), info.getLabel(), ancestorRoot, currentVersion);
         em.persist(newVersion);
         Object newId = getId(newVersion);

         newVersion = this.lock(newVersion);
newVersion = em.merge(newVersion);
     } else {

         newVersion = currentVersion;
         BeanUtils.setFieldWithAnnotation(newVersion, VersionNumber.class, info.getNumber());
         BeanUtils.setFieldWithAnnotation(newVersion, VersionLabel.class, info.getLabel());
         newVersion = em.merge(newVersion);

         currentVersion = (S) em.find(newVersion.getClass(), BeanUtils.getFieldWithAnnotation(newVersion, AncestorId.class));
         this.unlock(currentVersion);
     }

     currentVersion = (S) versioner.establishAncestor(currentVersion, newVersion);
     em.merge(currentVersion);

     return newVersion;
 }
 
Example 17
Source File: AbstractJWTFilter.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
private boolean isAuthenticated(Authentication authentication) {
  return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
}
 
Example 18
Source File: PoPAuthenticationManager.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
    Authentication authenticationResult = authenticationManager
        .authenticate(authentication);

    if (authenticationResult.isAuthenticated()) {
        // validates nonce because JWT is already valid
        if (authentication instanceof PoPAuthenticationToken) {
            PoPAuthenticationToken popAuthentication = (PoPAuthenticationToken) authentication;

            // starts validating nonce here
            String nonce = popAuthentication.getNonce();
            if (nonce == null) {
                throw new UnapprovedClientAuthenticationException(
                    "This request does not have a valid signed nonce");
            }

            String token = (String) popAuthentication.getPrincipal();

            System.out.println("access token:" + token);

            try {
                JWT jwt = JWTParser.parse(token);
                String publicKey = jwt.getJWTClaimsSet().getClaim("public_key").toString();
                JWK jwk = JWK.parse(publicKey);

                JWSObject jwsNonce = JWSObject.parse(nonce);
                JWSVerifier verifier = new RSASSAVerifier((RSAKey) jwk);
                if (!jwsNonce.verify(verifier)) {
                    throw new InvalidTokenException("Client hasn't possession of given token");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    return authenticationResult;
}
 
Example 19
Source File: AnonymousLoginFilter.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest rec, ServletResponse res, FilterChain chain) throws IOException,
		ServletException {
	HttpServletRequest request = (HttpServletRequest) rec;
	HttpServletResponse response = (HttpServletResponse) res;

	if (request.getAttribute(FILTER_APPLIED) != null) {
		chain.doFilter(request, response);
		return;
	}

	request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

	if ((authentication == null || (authentication != null && !authentication.isAuthenticated()))
			&& "login".equals(request.getParameter("anonymous"))) {

		String tenant = "default";
		if (StringUtils.isNotEmpty(request.getParameter("tenant")))
			tenant = request.getParameter("tenant");

		ContextProperties config = Context.get().getProperties();
		if (config.getBoolean(tenant + ".anonymous.enabled")) {
			LDAuthenticationToken authToken = new LDAuthenticationToken(config.getProperty(tenant + ".anonymous.user"));
			AuthenticationManager authenticationManager = (AuthenticationManager) Context.get().getBean(
					AuthenticationManager.class);
			try {
				Authentication anonAuthentication = authenticationManager.authenticate(authToken);
				if (anonAuthentication.isAuthenticated()) {
					String sid = ((LDAuthenticationToken) anonAuthentication).getSid();
					SessionManager.get().saveSid(request, response, sid);
				}
			} catch (AuthenticationException ae) {

			} catch (Throwable t) {
				log.error(t.getMessage(), t);
			}
		}
	}

	chain.doFilter(request, response);
}
 
Example 20
Source File: BasicAuthenticationFilter.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean authenticationIsRequired(String username) {
	// Only reauthenticate if username doesn't match SecurityContextHolder
	// and user
	// isn't authenticated
	// (see SEC-53)
	Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();

	if (existingAuth == null || !existingAuth.isAuthenticated()) {
		return true;
	}

	// Limit username comparison to providers which use usernames (ie
	// UsernamePasswordAuthenticationToken)
	// (see SEC-348)

	if (existingAuth instanceof UsernamePasswordAuthenticationToken && !existingAuth.getName().equals(username)) {
		return true;
	}

	// Handle unusual condition where an AnonymousAuthenticationToken is
	// already
	// present
	// This shouldn't happen very often, as BasicProcessingFitler is meant
	// to be
	// earlier in the filter
	// chain than AnonymousAuthenticationFilter. Nevertheless, presence of
	// both an
	// AnonymousAuthenticationToken
	// together with a BASIC authentication request header should indicate
	// reauthentication using the
	// BASIC protocol is desirable. This behaviour is also consistent with
	// that
	// provided by form and digest,
	// both of which force re-authentication if the respective header is
	// detected (and
	// in doing so replace
	// any existing AnonymousAuthenticationToken). See SEC-610.
	if (existingAuth instanceof AnonymousAuthenticationToken) {
		return true;
	}

	return false;
}