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:sk.lazyman.gizmo.security.GizmoAuthWebSession.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 {//  w w w.  j  a v  a  2  s .c  om
        Authentication authentication = authenticationProvider
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        authenticated = authentication.isAuthenticated();
    } catch (AuthenticationException ex) {
        LOGGER.error("Couldn't authenticate user, reason: {}", ex.getMessage());
        LOGGER.debug("Couldn't authenticate user.", ex);
        authenticated = false;

        String msg = new StringResourceModel(ex.getMessage(), null, ex.getMessage()).getString();
        error(msg);
    }

    return authenticated;
}

From source file:org.xaloon.wicket.security.spring.SpringSecurityFacade.java

@Override
public boolean isLoggedIn() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return (authentication != null && authentication.isAuthenticated()
            && !ANONYMOUS_USER.equalsIgnoreCase(authentication.getPrincipal().toString()));
}

From source file:eu.openanalytics.shinyproxy.controllers.BaseController.java

protected void prepareMap(ModelMap map, HttpServletRequest request) {
    map.put("title", environment.getProperty("proxy.title", "ShinyProxy"));
    map.put("logo", resolveImageURI(environment.getProperty("proxy.logo-url")));
    map.put("showNavbar", !Boolean.valueOf(environment.getProperty("proxy.hide-navbar")));

    map.put("bootstrapCss", "/webjars/bootstrap/3.3.7/css/bootstrap.min.css");
    map.put("bootstrapJs", "/webjars/bootstrap/3.3.7/js/bootstrap.min.js");
    map.put("jqueryJs", "/webjars/jquery/3.3.1/jquery.min.js");

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    boolean isLoggedIn = authentication != null && !(authentication instanceof AnonymousAuthenticationToken)
            && authentication.isAuthenticated();
    map.put("isLoggedIn", isLoggedIn);
    map.put("isAdmin", userService.isAdmin(authentication));
    map.put("isSupportEnabled", isLoggedIn && getSupportAddress() != null);
}

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.UserApprovalHandler.java

/**
 * Allows automatic approval for trusted clients.
 * /*from   w  w  w. j a v a 2 s  .com*/
 * @param authorizationRequest The authorization request.
 * @param userAuthentication the current user authentication
 * 
 * @return Whether the specified request has been approved by the current user.
 */
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    // If we are allowed to check existing approvals this will short circuit the decision
    if (super.isApproved(authorizationRequest, userAuthentication)) {
        return true;
    }

    if (!userAuthentication.isAuthenticated()) {
        return false;
    }

    String flag = authorizationRequest.getApprovalParameters().get(AuthorizationRequest.USER_OAUTH_APPROVAL);
    boolean approved = flag != null && flag.toLowerCase().equals("true");
    if (approved)
        return true;

    // or trusted client
    if (authorizationRequest.getAuthorities() != null) {
        for (GrantedAuthority ga : authorizationRequest.getAuthorities())
            if (Config.AUTHORITY.ROLE_CLIENT_TRUSTED.toString().equals(ga.getAuthority()))
                return true;
    }
    // or test token redirect uri
    // or accesses only own resources
    return authorizationRequest.getRedirectUri().equals(ExtRedirectResolver.testTokenPath(servletContext))
            || useOwnResourcesOnly(authorizationRequest.getClientId(), authorizationRequest.getScope());
}

From source file:org.osiam.security.authorization.OsiamUserApprovalHandler.java

/**
 * Checks if the client is configured to not ask the user for approval or if the date to ask again expires.
 *
 * @param authorizationRequest/*ww  w .  j  av a2  s  .  c  o m*/
 *            spring authorizationRequest
 * @param userAuthentication
 *            spring userAuthentication
 * @return whether user approved the client or not
 */
@Override
public boolean isApproved(final AuthorizationRequest authorizationRequest,
        final Authentication userAuthentication) {
    // check if implicit is configured in client or if user already confirmed approval once and validity time is not
    // over
    final OsiamClientDetails client = getClientDetails(authorizationRequest);
    if (userAuthentication.isAuthenticated() && client.isImplicit()) {
        return true;
    } else if (userAuthentication.isAuthenticated() && client.getExpiry() != null
            && client.getExpiry().compareTo(new Date()) >= 0) {
        return true;
    }
    return false;
}

From source file:com.khs.sherpa.spring.SpringAuthentication.java

public String[] authenticate(String username, String password, HttpServletRequest request,
        HttpServletResponse response) {//from  w w  w .j a  va2s.  c o  m
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

    Authentication authentication = null;

    try {
        authentication = authenticationManager.authenticate(token);
    } catch (AuthenticationException e) {
        throw new SherpaInvalidUsernamePassword("username and/or password is incorrect");
    }

    if (authentication.isAuthenticated() == false) {
        throw new SherpaInvalidUsernamePassword("username and/or password is incorrect");
    }

    List<String> roles = new ArrayList<String>();
    for (GrantedAuthority auth : authentication.getAuthorities()) {
        roles.add(auth.getAuthority());
    }

    SecurityContextImpl context = new SecurityContextImpl();
    context.setAuthentication(authentication);

    SecurityContextHolder.setContext(context);

    request.getSession().setAttribute("SPRING_SECURITY_CONTEXT_KEY", context);

    return roles.toArray(new String[roles.size()]);

}

From source file:com.companyname.providers.DAOAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    // Determine username and password
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    String credentials = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : (String) authentication.getCredentials();

    logger.info("platform: Start authenticating user [" + username + "]");

    try {/*from   ww  w. j a va2s.c o  m*/
        Authentication auth = null;

        // authenticate from cache first to enhance performance
        auth = cache.authenticateFromCache(authentication);

        // perform authentication against our user's database store
        if (auth != null && auth.isAuthenticated()) {
            logger.info("User [" + username + "] is successfully authenticated against the cache");
        } else {
            auth = super.authenticate(authentication);
            cache.add(auth);
            logger.info("User [" + username + "] is successfully authenticated against DB store");
        }

        // build platform authentication object
        Authentication platformAuthentication = PlatAuthentication.getPlatAuthentication(auth);
        ((PlatAuthentication) platformAuthentication).setUserCredentials(credentials);
        return platformAuthentication;

    } catch (AuthenticationException ex1) {
        logger.log(Level.SEVERE, "Unsuccessfully authenticating user [" + username + "] ", ex1);
    }

    return null;
}

From source file:org.xaloon.wicket.security.spring.SpringSecurityFacade.java

private AuthenticationToken authenticateInternal(AbstractAuthenticationToken authenticationRequestToken) {
    boolean authenticated = false;
    String name = authenticationRequestToken.getName();
    String errorMessage = null;/*from www. j  av a  2  s  .  c  o m*/
    try {
        Authentication authentication = authenticationManager.authenticate(authenticationRequestToken);
        authenticated = authentication.isAuthenticated();
        if (authenticated && authentication.getDetails() == null) {
            // Try to load user details. Copy information into new token
            UsernamePasswordAuthenticationToken authenticationWithDetails = new UsernamePasswordAuthenticationToken(
                    authentication.getPrincipal(), authentication.getCredentials(),
                    authentication.getAuthorities());
            authenticationWithDetails.setDetails(userDao.getUserByUsername(authentication.getName()));
            authentication = authenticationWithDetails;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        name = authentication.getName();
    } catch (AuthenticationException e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("User " + name + " failed to login. Reason: ", e);
        }
        authenticated = false;
        errorMessage = e.getMessage();
    }
    if (authenticated) {
        return new AuthenticationToken(name, new ArrayList<AuthenticationAttribute>());
    }
    return new AuthenticationToken(name, errorMessage);
}

From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java

/**
 * // w w  w  . j a  v a  2 s  .co  m
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication existingAuth = securityContext.getAuthentication();

    final String gnCookie = getGeoNodeCookieValue(httpRequest);

    final boolean alreadyAuthenticated = existingAuth != null && existingAuth.isAuthenticated();
    final boolean anonymous = existingAuth == null || existingAuth instanceof AnonymousAuthenticationToken;
    // if logging in via geoserver web form, we want to short circuit the cookie
    // check below which might get triggered with an anon geonode cookie
    // the result looks like the login worked but because we replace the
    // auth below, it functionaly fails
    final boolean loggedInWithPassword = existingAuth instanceof UsernamePasswordAuthenticationToken
            && alreadyAuthenticated;
    final boolean hasPreviouslyValidatedGeoNodeCookie = (existingAuth instanceof GeoNodeSessionAuthToken)
            && existingAuth.getCredentials().equals(gnCookie);

    if (hasPreviouslyValidatedGeoNodeCookie)
        existingAuth.setAuthenticated(true);

    // if we still need to authenticate and we find the cookie, consult GeoNode for
    // an authentication
    final boolean authenticationRequired = (!alreadyAuthenticated || anonymous
            || !hasPreviouslyValidatedGeoNodeCookie);

    if (!loggedInWithPassword && authenticationRequired && gnCookie != null) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine(
                    "Found GeoNode cookie - checking if we have the authorizations in cache or if we have to reload from GeoNode");
        }
        try {
            Object principal = existingAuth == null ? null : existingAuth.getPrincipal();
            Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null
                    : existingAuth.getAuthorities();
            Authentication authRequest = new GeoNodeSessionAuthToken(principal, gnCookie, authorities);
            final Authentication authResult = getSecurityManager().authenticate(authRequest);
            LOGGER.log(Level.FINE, "authResult : {0}", authResult);
            securityContext.setAuthentication(authResult);
        } catch (AuthenticationException e) {
            // we just go ahead and fall back on basic authentication
            LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e);
        }
    }

    // move forward along the chain
    chain.doFilter(request, response);
}

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

/**
 * Checks if the current user is authorized based on the specified security configuration attributes. The attributes
 * can be roles or Spring EL expressions (basically anything you can specify as values of the {@link org.springframework.security.access.annotation.Secured} annotation).
 *
 * @param securedObject                   the secured object.
 * @param securityConfigurationAttributes the security configuration attributes.
 * @return true if the current user is authorized, false if not.
 *//*  w  w  w . j av a2s .c om*/
public boolean hasAccessToObject(Object securedObject, String... securityConfigurationAttributes) {
    final Authentication authentication = getAuthentication();
    if (accessDecisionManager == null || authentication == null || !authentication.isAuthenticated()) {
        if (accessDecisionManager == 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 {
        accessDecisionManager.decide(authentication, securedObject, configAttributes);
        return true;
    } catch (AccessDeniedException ex) {
        return false;
    } catch (InsufficientAuthenticationException ex) {
        return false;
    }
}