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:org.vaadin.spring.security.AbstractVaadinSecurity.java

@Override
public boolean hasAccessToObject(Object securedObject, String... securityConfigurationAttributes) {
    final Authentication authentication = getAuthentication();
    if (getAccessDecisionManager() == null) {
        logger.warn("Access was denied to object because there was no AccessDecisionManager set!");
        return false;
    } else if (authentication == null || !authentication.isAuthenticated()) {
        return false;
    }//  w  w  w.  j  a v a 2  s .  co m

    final Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>(
            securityConfigurationAttributes.length);
    for (String securityConfigString : securityConfigurationAttributes) {
        configAttributes.add(new SecurityConfig(securityConfigString));
    }

    try {
        getAccessDecisionManager().decide(authentication, securedObject, configAttributes);
        return true;
    } catch (AccessDeniedException ex) {
        logger.trace("Access denied when accessing {}", securedObject);
        return false;
    } catch (InsufficientAuthenticationException ex) {
        logger.trace("Insufficient authentication when accessing {}", securedObject);
        return false;
    }
}

From source file:cz.zcu.kiv.eegdatabase.wui.app.session.EEGDataBaseSession.java

@Override
public boolean authenticate(String username, String password) {

    if (password.equalsIgnoreCase(SOCIAL_PASSWD)) {
        this.setLoggedUser(facade.getPerson(username));
        this.createShoppingCart();
        this.createExperimentLicenseMap();
        reloadPurchasedItemCache();//from www  .ja  v  a2 s .  c om
        return true;
    }

    boolean authenticated = false;
    try {
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        authenticated = authentication.isAuthenticated();
        this.setLoggedUser(facade.getPerson(username));
        reloadPurchasedItemCache();
        this.createShoppingCart();
        this.createExperimentLicenseMap();

    } catch (AuthenticationException e) {
        error((String.format("User '%s' failed to login. Reason: %s", username, e.getMessage())));
        authenticated = false;
    }

    if (getLoggedUser() != null && getLoggedUser().isLock()) {
        this.setLoggedUser(null);
        SecurityContextHolder.clearContext();
        this.shoppingCart = null;
        error(ResourceUtils.getString("text.user.lock.login", username));
        return false;
    }

    return authenticated;
}

From source file:org.red5.demo.auth.Red5SpringAuthenticationHandler.java

public boolean appConnect(IConnection conn, Object[] params) {
    log.info("appConnect");
    // start with negative result
    boolean result = false;
    log.debug("Connection: {}", conn);
    log.debug("Params: {}", params);
    // start off with the status being bad authentication
    String status = badAuth;/*  ww  w .  ja  va2s.  c o m*/
    // get the connection parameters
    Map<String, Object> connectionParams = conn.getConnectParams();
    log.debug("Connection params: {}", connectionParams);
    if (!connectionParams.containsKey("queryString")) {
        //set as missing auth notification
        status = rejectMissingAuth;
    } else {
        //get the raw query string
        String rawQueryString = (String) connectionParams.get("queryString");
        try {
            //parse into a usable query string
            UrlQueryStringMap<String, String> queryString = UrlQueryStringMap.parse(rawQueryString);
            log.debug("Query string: {}", queryString);
            //get the values we want
            String userName = queryString.get("user");
            log.debug("User: {}", userName);
            // do a user lookup
            AggregatedUserDetailsService userDetailsService = (AggregatedUserDetailsService) applicationContext
                    .getBean("aggregatedUserDetailsService");
            // this will throw an exception if the user cant be located by name
            UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
            // get the authentication "style"
            String authmod = queryString.get("authmod");
            log.debug("Authmod: {}", authmod);
            //make sure they requested red5 auth
            if ("red5".equals(authmod)) {
                String response = queryString.get("response");
                if (response != null) {
                    response = queryString.get("response").replace(' ', '+');
                }
                log.debug("Response: {}", response);
                //try the querystring first
                String sessionId = queryString.get("sessionid");
                if (sessionId == null) {
                    //get the session id - try conn next
                    sessionId = ((RTMPConnection) conn).getSessionId();
                    if (sessionId == null) {
                        //use attribute
                        if (conn.hasAttribute("sessionId")) {
                            sessionId = conn.getStringAttribute("sessionId");
                        } else {
                            sessionId = SessionManager.getSessionId();
                            conn.setAttribute("sessionId", sessionId);
                        }
                    }
                }
                log.debug("Session id: {}", sessionId);
                String challenge = null;
                if (response != null) {
                    //look up challenge (gets and removes at the same time)
                    challenge = sessionChallenges.remove(sessionId);
                    // get the password
                    String password = userDetails.getPassword();
                    log.debug("Users password: {}", password);
                    //generate response hash to compare
                    String responseHash = calculateHMACSHA256(challenge, password);
                    log.debug("Generated response: {}", responseHash);
                    log.debug("Generated response: {}", response);
                    //decode both hashes before we compare otherwise we will have issues like
                    //4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU != 4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU=                    
                    if (Arrays.areEqual(Base64.decodeBase64(responseHash.getBytes()),
                            Base64.decodeBase64(response.getBytes()))) {
                        // everything matches so now do the actual authentication
                        // get the authentication manager
                        ProviderManager authManager = (ProviderManager) applicationContext
                                .getBean("authManager");
                        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                                userName, password);
                        Authentication auth = null;
                        try {
                            auth = authManager.authenticate(token);
                            log.info("Authentication result: {}\ndetails: {}", auth.isAuthenticated(), auth);
                            result = auth.isAuthenticated();
                            // set the authenticated user into the context (thread-local)
                            if (result) {
                                SecurityContextHolder.getContext().setAuthentication(auth);
                            }
                        } catch (Exception ex) {
                            log.warn("Problem during auth attempt: {}", ex);
                        }
                    }
                } else if (authmod != null && userName != null) {
                    // generate a challenge
                    challenge = calculateHMACSHA256(salt, sessionId);
                    // store the generated data
                    sessionChallenges.put(sessionId, challenge);
                    // set as rejected
                    status = String.format(
                            "[ AccessManager.Reject ] : [ authmod=red5 ] : ?reason=needauth&user=%s&sessionid=%s&challenge=%s",
                            userName, sessionId, challenge);
                }
                log.debug("Challenge: {}", challenge);
            } else {
                status = invalidAuthMod;
            }
        } catch (UsernameNotFoundException ex) {
            status = noSuchUser;
        } catch (Exception e) {
            log.error("Error authenticating", e);
        }
    }
    //send the status object
    log.debug("Status: {}", status);
    if (!result) {
        throw new ClientRejectedException(status);
    }
    return result;
}

From source file:cz.zcu.kiv.eegdatabase.wui.app.session.EEGDataBaseSession.java

public boolean authenticatedSocial() {

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

    for (GrantedAuthority auth : authentication.getAuthorities()) {
        if (auth.getAuthority().equals("ROLE_ANONYMOUS"))
            return false;
    }/*  w w  w.j  ava 2 s.  c o  m*/

    if (authentication.isAuthenticated()) {

        String username = "";

        if (authentication.getPrincipal() instanceof User)
            username = ((User) authentication.getPrincipal()).getUsername();
        else if (authentication.getPrincipal() instanceof Person)
            username = ((Person) authentication.getPrincipal()).getUsername();

        return signIn(username, SOCIAL_PASSWD);
    }

    return false;
}

From source file:de.thm.arsnova.controller.LoginController.java

@RequestMapping(value = { "/auth/login", "/doLogin" }, method = { RequestMethod.POST, RequestMethod.GET })
public void doLogin(@RequestParam("type") final String type,
        @RequestParam(value = "user", required = false) String username,
        @RequestParam(required = false) final String password,
        @RequestParam(value = "role", required = false) final UserSessionService.Role role,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    String addr = request.getRemoteAddr();
    if (userService.isBannedFromLogin(addr)) {
        response.sendError(429, "Too Many Requests");

        return;//  ww w . j  a  va 2s.c o m
    }

    userSessionService.setRole(role);

    if ("arsnova".equals(type)) {
        Authentication authRequest = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication auth = daoProvider.authenticate(authRequest);
            if (auth.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(auth);
                request.getSession(true).setAttribute(
                        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                        SecurityContextHolder.getContext());

                return;
            }
        } catch (AuthenticationException e) {
            LOGGER.info("Authentication failed: {}", e.getMessage());
        }

        userService.increaseFailedLoginCount(addr);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    } else if ("ldap".equals(type)) {
        if (!"".equals(username) && !"".equals(password)) {
            org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                    username, password, true, true, true, true, this.getAuthorities());

            Authentication token = new UsernamePasswordAuthenticationToken(user, password, getAuthorities());
            try {
                Authentication auth = ldapAuthenticationProvider.authenticate(token);
                if (auth.isAuthenticated()) {
                    SecurityContextHolder.getContext().setAuthentication(token);
                    request.getSession(true).setAttribute(
                            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                            SecurityContextHolder.getContext());

                    return;
                }
                LOGGER.info("LDAPLOGIN: {}", auth.isAuthenticated());
            } catch (AuthenticationException e) {
                LOGGER.info("No LDAP login: {}", e);
            }

            userService.increaseFailedLoginCount(addr);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
    } else if ("guest".equals(type)) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_GUEST"));
        if (username == null || !username.startsWith("Guest") || username.length() != MAX_USERNAME_LENGTH) {
            username = "Guest"
                    + Sha512DigestUtils.shaHex(request.getSession().getId()).substring(0, MAX_GUESTHASH_LENGTH);
        }
        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                username, "", true, true, true, true, authorities);
        Authentication token = new UsernamePasswordAuthenticationToken(user, null, authorities);

        SecurityContextHolder.getContext().setAuthentication(token);
        request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());
    }
}

From source file:springacltutorial.infrastructure.MyMethodSecurityInterceptor.java

/**
 * Checks the current authentication token and passes it to the
 * AuthenticationManager if/*from w  w  w  .  j  a v a  2  s .  c  om*/
 * {@link org.springframework.security.core.Authentication#isAuthenticated()}
 * returns false or the property <tt>alwaysReauthenticate</tt> has been set
 * to true.
 * 
 * @return an authenticated <tt>Authentication</tt> object.
 */
private Authentication authenticateIfRequired() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication.isAuthenticated() && !alwaysReauthenticate) {
        if (logger.isDebugEnabled()) {
            logger.debug("Previously Authenticated: " + authentication);
        }

        return authentication;
    }

    authentication = authenticationManager.authenticate(authentication);

    // We don't authenticated.setAuthentication(true), because each provider
    // should do that
    if (logger.isDebugEnabled()) {
        logger.debug("Successfully Authenticated: " + authentication);
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);

    return authentication;
}

From source file:org.vaadin.spring.security.GenericVaadinSecurity.java

/**
 * {@inheritDoc}/*  www  .j  a va  2s.  c om*/
 */
@Override
public boolean hasAccessToObject(Object securedObject, String... securityConfigurationAttributes) {
    final Authentication authentication = getAuthentication();
    if (getAccessDecisionManager() == null || authentication == null || !authentication.isAuthenticated()) {
        if (getAccessDecisionManager() == null) {
            logger.warn("Access was denied to object because there was no AccessDecisionManager set!");
        }
        return false;
    }

    final Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>(
            securityConfigurationAttributes.length);
    for (String securityConfigString : securityConfigurationAttributes) {
        configAttributes.add(new SecurityConfig(securityConfigString));
    }

    try {
        getAccessDecisionManager().decide(authentication, securedObject, configAttributes);
        return true;
    } catch (AccessDeniedException ex) {
        return false;
    } catch (InsufficientAuthenticationException ex) {
        return false;
    }
}