Example usage for org.springframework.security.core Authentication isAuthenticated

List of usage examples for org.springframework.security.core Authentication isAuthenticated

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication isAuthenticated.

Prototype

boolean isAuthenticated();

Source Link

Document

Used to indicate to AbstractSecurityInterceptor whether it should present the authentication token to the AuthenticationManager.

Usage

From source file:com.utest.webservice.auth.UtestWSS4JInInterceptor.java

@SuppressWarnings("unchecked")
@Override/*  w w  w.  j av  a  2 s.c om*/
public void handleMessage(final SoapMessage message) throws Fault {
    try {
        super.handleMessage(message);
        final Vector<WSHandlerResult> result = (Vector<WSHandlerResult>) message
                .getContextualProperty(WSHandlerConstants.RECV_RESULTS);
        if ((result != null) && !result.isEmpty()) {
            for (final WSHandlerResult res : result) {
                // loop through security engine results
                for (final WSSecurityEngineResult securityResult : (Vector<WSSecurityEngineResult>) res
                        .getResults()) {
                    final int action = (Integer) securityResult.get(WSSecurityEngineResult.TAG_ACTION);
                    // determine if the action was a username token
                    if ((action & WSConstants.UT) > 0) {
                        // get the principal object
                        final WSUsernameTokenPrincipal principal = (WSUsernameTokenPrincipal) securityResult
                                .get(WSSecurityEngineResult.TAG_PRINCIPAL);
                        if (principal.getPassword() == null) {
                            principal.setPassword("");
                        }
                        Authentication authentication = new UsernamePasswordAuthenticationToken(
                                principal.getName(), principal.getPassword());
                        authentication = authenticationProvider.authenticate(authentication);
                        if (!authentication.isAuthenticated()) {
                            System.out.println("This user is not authentic.");
                        }
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        }
    } catch (final RuntimeException ex) {
        ex.printStackTrace();
        throw ex;
    }
}

From source file:com.stormpath.spring.config.StormpathAuthenticationEntryPoint.java

private boolean isAuthenticated() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return false;
    }/*from  w  ww  . j  a  v a 2 s . c  om*/
    if (authentication instanceof AnonymousAuthenticationToken) {
        return false;
    }
    return authentication.isAuthenticated();
}

From source file:org.artifactory.ui.rest.service.admin.security.auth.login.LoginService.java

/**
 * set session with authentication data//from  w  ww  .  ja v a  2 s  . c om
 * @param authentication - spring authentication
 * @param securityContext - spring security context
 * @param servletRequest - http servlet request
 */
void setAuthentication(Authentication authentication, SecurityContext securityContext,
        HttpServletRequest servletRequest) {
    if (authentication.isAuthenticated()) {
        //Log authentication if not anonymous
        if (!isAnonymous(authentication)) {
            AccessLogger.loggedIn(authentication);
        }
        //Set a http session token so that we can reuse the login in direct repo browsing
        UiRequestUtils.setAuthentication(servletRequest, authentication, true);
        //Update the spring  security context
        bindAuthentication(securityContext, authentication);
    }
}

From source file:org.musicrecital.webapp.services.impl.SpringSecurityContext.java

public boolean isLoggedIn() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.getPrincipal() != null) {
        if ("anonymousUser".equals(authentication.getName())) {
            return false;
        }//from  www .  ja  v a2s .  c  o m
        return authentication.isAuthenticated();
    }
    return false;
}

From source file:org.openengsb.openticket.integrationtest.util.AbstractExamTestHelper.java

protected void authenticate(String user, String password) throws InterruptedException {
    AuthenticationManager authenticationManager = getOsgiService(AuthenticationManager.class, 20000);
    Authentication authentication = authenticationManager
            .authenticate(new UsernamePasswordAuthenticationToken(user, password));
    assertThat(authentication.isAuthenticated(), is(true));
    SecurityContextHolder.getContext().setAuthentication(authentication);
}

From source file:org.apache.nifi.minifi.c2.security.authorization.GrantedAuthorityAuthorizer.java

@Override
public void authorize(Authentication authentication, UriInfo uriInfo) throws AuthorizationException {
    if (authentication == null) {
        throw new AuthorizationException("null authentication object provided.");
    }/* w  w  w  . j ava2 s  . c  o  m*/

    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");
    }
}

From source file:com.evolveum.midpoint.web.security.MidPointAuthWebSession.java

@Override
public boolean authenticate(String username, String password) {
    LOGGER.debug("Authenticating '{}' {} password in web session.",
            new Object[] { username, (StringUtils.isEmpty(password) ? "without" : "with") });

    boolean authenticated;
    try {/*from www  .  j  a va  2s.c o m*/
        Authentication authentication = authenticationProvider
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        authenticated = authentication.isAuthenticated();

        auditEvent(authentication, username, OperationResultStatus.SUCCESS);
    } catch (AuthenticationException ex) {
        String key = ex.getMessage() != null ? ex.getMessage() : "web.security.provider.unavailable";
        MidPointApplication app = (MidPointApplication) getSession().getApplication();
        error(app.getString(key));

        LOGGER.debug("Couldn't authenticate user.", ex);
        authenticated = false;

        auditEvent(null, username, OperationResultStatus.FATAL_ERROR);
    }

    return authenticated;
}

From source file:org.jamwiki.authentication.JAMWikiPostAuthenticationFilter.java

/**
 *
 *//*from  ww  w.  j a  v  a  2 s.com*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("HttpServletRequest required");
    }
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof AnonymousAuthenticationToken) {
        // anonymous user
        this.handleAnonymousUser(auth);
    } else if (auth != null && auth.isAuthenticated()) {
        // registered user
        this.handleRegisteredUser(auth);
    }
    chain.doFilter(request, response);
}

From source file:com.jd.survey.web.security.AccountController.java

/**
 * Updates  logged in user password//from  w  w  w .  j  a  va2s . c o m
 * @param oldPassword
 * @param newPassword
 * @param newPasswordConfirm
 * @param proceed
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/rpass", method = RequestMethod.POST, produces = "text/html")
public String updatePasswordPost(@RequestParam(value = "password", required = true) String oldPassword,
        @RequestParam(value = "nPassword", required = true) String newPassword,
        @RequestParam(value = "cPassword", required = true) String newPasswordConfirm,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        if (proceed != null) {

            //check that the old password is correct
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    principal.getName(), oldPassword);
            authenticationToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
            try {
                Authentication auth = authenticationManager.authenticate(authenticationToken);
                if (auth == null || !auth.isAuthenticated()) {
                    //invalid password enetered
                    uiModel.asMap().clear();
                    uiModel.addAttribute("status", "E"); //Unmatching Passwords
                    return "account/rpass";
                }

            } catch (AuthenticationException e) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "E"); //Unmatching Passwords
                return "account/rpass";
            }
            //Check new password strenght 
            if (!GenericValidator.matchRegexp(newPassword, globalSettings.getPasswordEnforcementRegex())) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "I"); //Unmatching Passwords
                return "account/rpass";
            }
            //check that passwords match    
            if (!newPassword.equals(newPasswordConfirm)) {
                uiModel.asMap().clear();

                uiModel.addAttribute("status", "U"); //Unmatching Passwords
                return "account/rpass";
            }
            User loggedInUser = userService.user_findByLogin(principal.getName());
            //All validations passed, save the HASH of the password in the database
            loggedInUser.setPassword(newPassword);
            userService.user_updatePassword(loggedInUser);
            uiModel.addAttribute("status", "S");//success
            return "account/rpass";
        } else {
            return "redirect:/account/show";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}