Example usage for org.apache.shiro.session Session touch

List of usage examples for org.apache.shiro.session Session touch

Introduction

In this page you can find the example usage for org.apache.shiro.session Session touch.

Prototype

void touch() throws InvalidSessionException;

Source Link

Document

Explicitly updates the #getLastAccessTime() lastAccessTime of this session to the current time when this method is invoked.

Usage

From source file:br.com.criativasoft.opendevice.wsrest.filter.AuthenticationFilter.java

License:Open Source License

@Override
public ContainerRequest filter(ContainerRequest request) {

    // Ignore Web Resources.
    String path = request.getPath();
    if (WebUtils.isWebResource(path)) {
        return request;
    }/*from w  w  w . jav  a2 s  .  c  o m*/

    Subject subject = SecurityUtils.getSubject();

    Session session = subject.getSession(false);

    if (session != null && subject.isAuthenticated()) {
        session.touch();
        return request;
    }

    if (!subject.isAuthenticated()) {

        // Google OAuth ( Ex.: Alexa Skill )
        String authorizationHeader = request.getHeaderValue(HttpHeaders.AUTHORIZATION);

        if (authorizationHeader != null && authorizationHeader.startsWith("Google")) {
            String token = authorizationHeader.substring("Google".length()).trim(); // Token

            GoogleAuthToken bearerToken = new GoogleAuthToken(token);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }

        }

        // Extract the token from the HTTP Authorization header (OAuth2)
        authorizationHeader = request.getHeaderValue(HttpHeaders.AUTHORIZATION);
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer")) {
            String token = authorizationHeader.substring("Bearer".length()).trim(); // API_KEY

            BearerAuthToken bearerToken = new BearerAuthToken(token);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // ApiKey in Header (no 2 step auth)
        String header = request.getHeaderValue("ApiKey");
        if ((authorizationHeader != null && authorizationHeader.startsWith("ApiKey")) || header != null) {
            String apiKey = null;
            if (header != null) {
                apiKey = header;
            } else {
                apiKey = authorizationHeader.substring("ApiKey".length()).trim(); // API_KEY
            }

            if (StringUtils.isEmpty(apiKey)) {
                log.warn("ApiKey not found in Request");
                throw new AuthenticationException("ApiKey Required");
            }

            BearerAuthToken bearerToken = new BearerAuthToken(apiKey, true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // WebSocket HttpHeader Upgrade (JavaScript Library).
        header = request.getHeaderValue("Upgrade");
        if (header != null && header.contains("websocket")) {

            String apiKey = path.substring(path.lastIndexOf('/') + 1, path.length());

            BearerAuthToken bearerToken = new BearerAuthToken(apiKey, true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // Query Param (in URL)

        MultivaluedMap<String, String> queryParameters = request.getQueryParameters();

        List<String> apiKeyParams = queryParameters.get("ApiKey");

        if (apiKeyParams != null) {

            BearerAuthToken bearerToken = new BearerAuthToken(apiKeyParams.get(0), true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // GoogleAssistant / Dialogflow Integration
        header = request.getHeaderValue("GoogleAssistant");
        if (header != null && header.contains("Dialogflow")) {

            JsonNode entity = request.getEntity(JsonNode.class);
            JsonNode userNode = entity.get("originalDetectIntentRequest").get("payload").get("user");

            if (userNode == null) {
                log.warn("User not found in Request");
                throw new AuthenticationException("Invalid User / Token");
            }
            String token = userNode.get("accessToken").asText();

            BearerAuthToken bearerToken = new BearerAuthToken(token);

            // request.setEntityInputStream(new ByteArrayInputStream(entity.toString().getBytes()));
            request.setEntityInputStream(new ByteArrayInputStream(entity.toString().getBytes()));
            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }
    }

    // NOTE: if not Autenticated, the UnauthenticatedException will throw (AuthorizationExceptionMap)

    return request;
}

From source file:com.baomidou.kisso.web.interceptor.SSOShiroInterceptor.java

License:Apache License

/**
 * ???//www . j  av  a 2s.com
 * <p>
 *  Controller ??
 * </p>
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (handler instanceof HandlerMethod) {
        SSOToken token = SSOHelper.attrToken(request);
        if (token == null) {
            return true;
        }

        /**
         * shiro ??
         */
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession(false);
        if (session != null) {
            session.touch();
        }

        /**
         * shiro ?
         */
        if (!currentUser.isAuthenticated()) {
            currentUser.login(new SSOAuthToken(token));
            logger.fine(" shiro login success. ");
        }

        /**
         * URL ???
         */
        if (SSOConfig.getInstance().isPermissionUri()) {
            String uri = request.getRequestURI();
            if (uri == null || currentUser.isPermitted(uri)) {
                return true;
            }
        }

        /**
         * ???
         */
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Permission pm = method.getAnnotation(Permission.class);
        if (pm != null) {
            if (pm.action() == Action.Skip) {
                /**
                 * 
                 */
                return true;
            } else if (!"".equals(pm.value()) && currentUser.isPermitted(pm.value())) {
                /**
                 * ???
                 */
                return true;
            }
        }

        /**
         * ??
         */
        return unauthorizedAccess(request, response);
    }

    return true;
}

From source file:com.suime.common.shiro.BaseCache.java

License:Apache License

/**
 * Gets a value of an element which matches the given key.
 *
 * @param key the key of the element to return.
 * @return The value placed into the cache with an earlier put, or null if not found or expired
 *//* w w w. ja v a  2s.  co  m*/
@Override
@SuppressWarnings("unchecked")
public V get(K key) throws CacheException {
    if (key == null) {
        return null;
    }
    ensureCacheInstance();
    V value = (V) cacheService.get(PREFIX_SHIRO_SESSION + key.toString());
    if (value instanceof Session) {
        Session session = (Session) value;
        session.touch();
        cacheService.set(getTimeOut(session), PREFIX_SHIRO_SESSION + key.toString(), session);
    }
    return value;
}

From source file:org.graylog2.security.realm.SessionAuthenticator.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    SessionIdToken sessionIdToken = (SessionIdToken) token;
    final Subject subject = new Subject.Builder().sessionId(sessionIdToken.getSessionId()).buildSubject();
    final Session session = subject.getSession(false);
    if (session == null) {
        LOG.debug("Invalid session {}. Either it has expired or did not exist.", sessionIdToken.getSessionId());
        return null;
    }/*  w  ww  .  j  a v  a 2s  .c  om*/

    final Object username = subject.getPrincipal();
    final User user = userService.load(String.valueOf(username));
    if (user == null) {
        LOG.debug("No user named {} found for session {}", username, sessionIdToken.getSessionId());
        return null;
    }
    if (user.isExternalUser() && !ldapAuthenticator.isEnabled()) {
        throw new LockedAccountException("LDAP authentication is currently disabled.");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Found session {} for user name {}", session.getId(), username);
    }

    @SuppressWarnings("unchecked")
    final MultivaluedMap<String, String> requestHeaders = (MultivaluedMap<String, String>) ThreadContext
            .get("REQUEST_HEADERS");
    // extend session unless the relevant header was passed.
    if (requestHeaders == null
            || !"true".equalsIgnoreCase(requestHeaders.getFirst("X-Graylog2-No-Session-Extension"))) {
        session.touch();
    } else {
        LOG.debug("Not extending session because the request indicated not to.");
    }
    ThreadContext.bind(subject);

    return new SimpleAccount(user.getName(), null, "session authenticator");
}

From source file:org.obiba.agate.web.rest.security.AuthenticationInterceptor.java

License:Open Source License

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    // Set the cookie if the user is still authenticated
    if (isUserAuthenticated()) {
        Session session = SecurityUtils.getSubject().getSession();
        session.touch();
        int timeout = (int) (session.getTimeout() / 1000);
        responseContext.getHeaders().putSingle(HttpHeaders.SET_COOKIE, new NewCookie(
                AGATE_SESSION_ID_COOKIE_NAME, session.getId().toString(), "/", null, null, timeout, false));
    } else {/* www  . j  ava 2s .  com*/
        if (responseContext.getHeaders().get(HttpHeaders.SET_COOKIE) == null) {
            responseContext.getHeaders().putSingle(HttpHeaders.SET_COOKIE, new NewCookie(
                    AGATE_SESSION_ID_COOKIE_NAME, null, "/", null, "Agate session deleted", 0, false));
        }
    }
}

From source file:org.obiba.mica.web.rest.security.AuthenticationInterceptor.java

License:Open Source License

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    // Set the cookie if the user is still authenticated
    if (isUserAuthenticated()) {
        Session session = SecurityUtils.getSubject().getSession();
        session.touch();
        int timeout = (int) (session.getTimeout() / 1000);
        responseContext.getHeaders().putSingle(HttpHeaders.SET_COOKIE, new NewCookie(
                MICA_SESSION_ID_COOKIE_NAME, session.getId().toString(), "/", null, null, timeout, false));
        Object cookieValue = session.getAttribute(HttpHeaders.SET_COOKIE);
        if (cookieValue != null) {
            responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, NewCookie.valueOf(cookieValue.toString()));
        }//ww w .  j av a 2 s  .  c  o  m
    } else {
        if (responseContext.getHeaders().get(HttpHeaders.SET_COOKIE) == null) {
            responseContext.getHeaders().putSingle(HttpHeaders.SET_COOKIE, new NewCookie(
                    MICA_SESSION_ID_COOKIE_NAME, null, "/", null, "Mica session deleted", 0, false));
        }
    }
}

From source file:org.obiba.opal.server.httpd.security.AuthenticationFilter.java

License:Open Source License

/**
 * This method will try to authenticate the user using the provided sessionId or the "Authorization" header. When no
 * credentials are provided, this method does nothing. This will invoke the filter chain with an anonymous subject,
 * which allows fetching public web resources.
 *
 * @param request//w  w w.j  a va2 s.  co m
 */
private void authenticateAndBind(HttpServletRequest request) {

    Subject subject = null;

    if (hasSslCert(request)) {
        subject = authenticateBySslCert(request);
    }

    if (subject == null && hasOpalAuthHeader(request)) {
        subject = authenticateByOpalAuthHeader(request);
    }

    if (subject == null && hasAuthorizationHeader(request)) {
        subject = authenticateByAuthorizationHeader(request);
    }

    if (subject == null && hasOpalSessionCookie(request) && hasOpalRequestCookie(request)) {
        subject = authenticateByCookie(request);
    }

    if (subject != null) {
        Session session = subject.getSession();
        log.debug("Binding subject {} session {} to executing thread {}", subject.getPrincipal(),
                session.getId(), Thread.currentThread().getId());
        session.touch();
        String username = subject.getPrincipal().toString();
        ensureUserHomeExists(username);
        ensureFolderPermissions(username, "/home/" + username);
        ensureFolderPermissions(username, "/tmp");
    }
}

From source file:org.obiba.opal.shell.CommandJob.java

License:Open Source License

@Override
public void progress(String message, long current, long end, int percent) {
    Session session = SecurityUtils.getSubject().getSession(false);

    if (session != null)
        session.touch();

    if (percent == 100) {
        messages.add(createMessage(String.format("%s %s completed.", message, name)));
    }/*from   w w  w. java 2s . c om*/
    messageProgress = message;
    currentProgress = current;
    endProgress = end;
    percentProgress = percent;
}

From source file:org.obiba.opal.web.security.AuthenticationInterceptor.java

License:Open Source License

@Override
public void postProcess(HttpRequest request, ResourceMethod resourceMethod, ServerResponse response) {
    // Set the cookie if the user is still authenticated
    if (isUserAuthenticated()) {
        Session session = SecurityUtils.getSubject().getSession();
        session.touch();
        int timeout = (int) (session.getTimeout() / 1000);
        response.getMetadata().add(HttpHeaderNames.SET_COOKIE, new NewCookie(OPAL_SESSION_ID_COOKIE_NAME,
                session.getId().toString(), "/", null, null, timeout, false));
    } else {/* w ww  .  j  a  v a2s  .  com*/
        // Remove the cookie if the user is not/no longer authenticated
        if (isWebServiceAuthenticated(response.getAnnotations())) {
            // Only web service calls that require authentication will lose their opalsid cookie
            response.getMetadata().add(HttpHeaderNames.SET_COOKIE, new NewCookie(OPAL_SESSION_ID_COOKIE_NAME,
                    null, "/", null, "Opal session deleted", 0, false));
        }
    }
}

From source file:org.obiba.shiro.web.filter.AuthenticationFilter.java

License:Open Source License

/**
 * This method will try to authenticate the user using the provided sessionId or the "Authorization" header. When no
 * credentials are provided, this method does nothing. This will invoke the filter chain with an anonymous subject,
 * which allows fetching public web resources.
 *
 * @param request//from   w ww.  j  a  v a2 s  .co  m
 */
private void authenticateAndBind(HttpServletRequest request) {

    Subject subject = authenticateSslCert(request);
    if (subject == null) {
        subject = authenticateAuthHeader(request);
    }
    if (subject == null) {
        subject = authenticateBasicHeader(request);
    }
    if (subject == null) {
        subject = authenticateCookie(request);
    }
    if (subject == null) {
        subject = authenticateTicket(request);
    }
    if (subject == null) {
        subject = authenticateBearerHeader(request);
    }

    if (subject != null) {
        Session session = subject.getSession();
        log.trace("Binding subject {} session {} to executing thread {}", subject.getPrincipal(),
                session.getId(), Thread.currentThread().getId());
        ThreadContext.bind(subject);
        session.touch();
        log.debug("Successfully authenticated subject {}", SecurityUtils.getSubject().getPrincipal());
    }
}