Example usage for org.apache.shiro.web.util WebUtils saveRequest

List of usage examples for org.apache.shiro.web.util WebUtils saveRequest

Introduction

In this page you can find the example usage for org.apache.shiro.web.util WebUtils saveRequest.

Prototype

public static void saveRequest(ServletRequest request) 

Source Link

Usage

From source file:br.com.criativasoft.opendevice.wsrest.resource.OAuthRest.java

License:Open Source License

@GET
@Path("/authorize")
public Response authorize(@Context HttpServletRequest request) throws URISyntaxException, OAuthSystemException {

    Subject subject = SecurityUtils.getSubject();

    // Save request and go to login page
    if (!subject.isAuthenticated()) {
        WebUtils.saveRequest(request);
        URI uri = UriBuilder.fromUri("/login").build();
        return Response.seeOther(uri).build();
    }//from  w ww  .  jav  a  2  s.co  m

    OAuthAuthzRequest oauthRequest;

    OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

    try {
        oauthRequest = new OAuthAuthzRequest(request);

        // build response according to response_type
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);

        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);

        String authCode = oauthIssuerImpl.authorizationCode();

        if (responseType.equals(ResponseType.CODE.toString())) {
            builder.setCode(authCode);
        } else {
            throw new IllegalArgumentException("responseType not allowed = " + responseType);
        }

        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
        URI url = new URI(response.getLocationUri());

        // Store autentication code in Token cache to validade in next phase (method: tokenPost)
        DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
        Cache<Object, Object> cache = securityManager.getCacheManager()
                .getCache(AuthenticationFilter.TOKEN_CACHE);

        AccountPrincipal principal = (AccountPrincipal) subject.getPrincipal();
        cache.put(authCode, principal.getUserAccountID());

        return Response.status(response.getResponseStatus()).location(url).build();

    } catch (OAuthProblemException e) {

        final Response.ResponseBuilder responseBuilder = Response.status(HttpServletResponse.SC_FOUND);

        String redirectUri = e.getRedirectUri();

        if (OAuthUtils.isEmpty(redirectUri)) {
            throw new WebApplicationException(
                    responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build());
        }

        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(redirectUri).buildQueryMessage();

        final URI location = new URI(response.getLocationUri());

        return responseBuilder.location(location).build();
    }
}

From source file:cn.dreampie.common.plugin.shiro.MyAccessControlFilter.java

License:Apache License

/**
 * Convenience method merely delegates to
 * {@link org.apache.shiro.web.util.WebUtils#saveRequest(javax.servlet.ServletRequest) WebUtils.saveRequest(request)} to save the request
 * state for reuse later.  This is mostly used to retain user request state when a redirect is issued to
 * return the user to their originally requested url/resource.
 * <p/>/*from   ww  w .  j  a  va2s .com*/
 * If you need to save and then immediately redirect the user to login, consider using
 * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
 * saveRequestAndRedirectToLogin(request,response)} directly.
 *
 * @param request the incoming ServletRequest to save for re-use later (for example, after a redirect).
 */
protected void saveRequest(ServletRequest request) {
    WebUtils.saveRequest(request);
}

From source file:cn.dreampie.common.plugin.shiro.plugin.ShiroInterceptor.java

License:Apache License

/**
 * ??/*w  w w.ja va  2  s  .c o  m*/
 *
 * @param ai
 * @param ahs
 * @return
 */
private boolean assertNoAuthorized(ActionInvocation ai, List<AuthzHandler> ahs) {

    // ?
    if (ahs != null && ahs.size() > 0) {

        // ??
        if (!SubjectUtils.me().wasLogin()) {
            WebUtils.saveRequest(ai.getController().getRequest());
        }

        //rememberMe
        Subject subject = SubjectUtils.me().getSubject();
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            Object principal = subject.getPrincipal();
            Session session = SubjectUtils.me().getSession();
            if (null != principal) {
                if (session.getAttribute(AppConstants.CURRENT_USER) == null) {
                    session.setAttribute(AppConstants.CURRENT_USER, (User) principal);
                }
            } else {
                SubjectUtils.me().getSubject().logout();
            }
        }

        try {
            // ??
            for (AuthzHandler ah : ahs) {
                ah.assertAuthorized();
            }
        } catch (UnauthenticatedException lae) {
            // RequiresGuestRequiresAuthenticationRequiresUser??
            // ?HTTP401??
            ai.getController().renderError(401);
            return true;
        } catch (AuthorizationException ae) {
            // RequiresRolesRequiresPermissions?
            // ???HTTP??403
            ai.getController().renderError(403);
            return true;
        } catch (Exception e) {
            // 
            ai.getController().renderError(401);
            return true;
        }
    }
    return false;
}

From source file:cn.dreampie.shiro.core.ShiroInterceptor.java

License:Apache License

/**
 * ??/*from  w  w w.  jav a  2  s .c  o m*/
 *
 * @param ai
 * @param ahs
 * @return
 */
private boolean assertNoAuthorized(ActionInvocation ai, List<AuthzHandler> ahs) {

    // ?
    if (ahs != null && ahs.size() > 0) {

        // ??
        if (!SubjectKit.isAuthed()) {
            WebUtils.saveRequest(ai.getController().getRequest());
        }

        //rememberMe
        Subject subject = SubjectKit.getSubject();
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            Object principal = subject.getPrincipal();
            if (principal == null) {
                SubjectKit.getSubject().logout();
            }
        }

        try {
            // ??
            for (AuthzHandler ah : ahs) {
                ah.assertAuthorized();
            }
        } catch (UnauthenticatedException lae) {
            // RequiresGuestRequiresAuthenticationRequiresUser??
            // ?HTTP401??
            ai.getController().renderError(401);
            return true;
        } catch (AuthorizationException ae) {
            // RequiresRolesRequiresPermissions?
            // ???HTTP??403
            ai.getController().renderError(403);
            return true;
        } catch (Exception e) {
            // 
            ai.getController().renderError(401);
            return true;
        }
    }
    return false;
}

From source file:com.dbumama.market.web.core.plugin.shiro.ShiroInterceptor.java

License:Apache License

/**
 * ??//from  w  w w  . j a  v a 2 s .co m
 *
 * @param ai
 * @param ahs
 * @return
 */
private boolean assertNoAuthorized(Invocation ai, List<AuthzHandler> ahs) {
    // ?
    if (ahs != null && ahs.size() > 0) {
        // ??
        if (!SubjectKit.isAuthed()) {
            WebUtils.saveRequest(ai.getController().getRequest());
        }
        // rememberMe
        Subject subject = SubjectKit.getSubject();
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            Object principal = subject.getPrincipal();
            if (principal == null) {
                SubjectKit.getSubject().logout();
            }
        }

        try {
            // ??
            for (AuthzHandler ah : ahs) {
                ah.assertAuthorized();
            }
        } catch (UnauthenticatedException lae) {
            // RequiresGuestRequiresAuthenticationRequiresUser??
            // ?HTTP401??
            ai.getController().renderError(401);
            return true;
        } catch (AuthorizationException ae) {
            // RequiresRolesRequiresPermissions?
            // ???HTTP??403
            ai.getController().renderError(403);
            return true;
        } catch (Exception e) {
            // 
            ai.getController().renderError(401);
            return true;
        }
    }
    return false;
}

From source file:com.ftww.basic.plugin.shiro.core.ShiroInterceptor.java

License:Apache License

/**
 * ??//ww  w  . ja  v  a 2s  .  co  m
 *
 * @param ai
 * @param ahs
 * @return
 */
private boolean assertNoAuthorized(ActionInvocation ai, List<AuthzHandler> ahs) {

    // ?
    if (ahs != null && ahs.size() > 0) {

        // ??
        if (!SubjectKit.isAuthed()) {
            WebUtils.saveRequest(ai.getController().getRequest());
        }

        // rememberMe
        Subject subject = SubjectKit.getSubject();
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            Object principal = subject.getPrincipal();
            if (principal == null) {
                SubjectKit.getSubject().logout();
            }
        }

        try {
            // ??
            for (AuthzHandler ah : ahs) {
                ah.assertAuthorized();
            }
        } catch (UnauthenticatedException lae) {
            // RequiresGuestRequiresAuthenticationRequiresUser??
            // ?HTTP401??
            ai.getController().renderError(401);
            return true;
        } catch (AuthorizationException ae) {
            // RequiresRolesRequiresPermissions?
            // ???HTTP??403
            ai.getController().renderError(403);
            return true;
        } catch (Exception e) {
            // 
            ai.getController().renderError(401);
            return true;
        }
    }
    return false;
}

From source file:com.parallax.server.blocklyprop.utils.OAuthServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    LOG.info("Initating an OAuth request");

    // Authenticate code
    String code = req.getParameter("code");

    if (Strings.isNullOrEmpty(code)) {
        // Save url if provided
        String url = req.getParameter("url");

        if (!Strings.isNullOrEmpty(url)) {
            // Invoke the supplied URL                
            ServletRequest request = new HttpServletRequestImpl(url);
            WebUtils.saveRequest(request);
        }/*from   ww w .  j av  a  2  s. co  m*/

        LOG.info("Sending redirect");
        resp.sendRedirect(getAuthenticator().getAuthorizationUrl());
    } else {
        LOG.info("Received authentication code from OAuth provider");

        try {
            String userEmail = getAuthenticator().handleAuthentication(code);

            // Show confirm or straight redirect
            SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(req);
            if (savedRequest != null) {
                req.setAttribute("redirect", savedRequest.getRequestUrl());
            }
            req.getRequestDispatcher("/WEB-INF/servlet/oauth/success.jsp").forward(req, resp);
        } catch (NewOAuthUserException noaue) {
            // Save info in session
            // Show oauth user creation screen
            HttpSession session = req.getSession();
            session.setAttribute("oauth-email", noaue.getEmail());
            session.setAttribute("oauth-authenticator", noaue.getAuthenticator());
            req.setAttribute("screenname", "");
            req.getRequestDispatcher("/WEB-INF/servlet/oauth/new-oauth-user.jsp").forward(req, resp);
        } catch (WrongAuthenticationSourceException wase) {
            // Show error
            if ("local".equalsIgnoreCase(wase.getAuthenticationSource())) {
                req.setAttribute("local", true);
            } else {
                req.setAttribute("local", false);
            }
            req.setAttribute("source", wase.getAuthenticationSource());
            req.getRequestDispatcher("/WEB-INF/servlet/oauth/wrong-authentication-source.jsp").forward(req,
                    resp);
        } catch (ServerException ex) {
            // Show error
            LOG.error("A server exception accured in the oauth authentication process", ex);
            req.getRequestDispatcher("/WEB-INF/servlet/oauth/server-error.jsp").forward(req, resp);
        }
    }
}

From source file:org.tynamo.security.ShiroExceptionHandler.java

License:Apache License

/**
 * TODO: Make configurable strategies objects for ShiroException
 *//*from  w ww  .  ja  v  a2  s.c om*/
public void handle(ShiroException exception) throws IOException {

    if (securityService.isAuthenticated()) {

        String unauthorizedPage = pageService.getUnauthorizedPage();

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (!StringUtils.hasText(unauthorizedPage)) {
            return;
        }

        Component page = componentSource.getPage(unauthorizedPage);

        reportExceptionIfPossible(exception, page);

        renderer.renderPageMarkupResponse(unauthorizedPage);

    } else {
        Subject subject = securityService.getSubject();

        if (subject != null) {
            Session session = subject.getSession();
            if (session != null) {
                WebUtils.saveRequest(requestGlobals.getHTTPServletRequest());
            }
        }

        Component page = componentSource.getPage(pageService.getLoginPage());

        reportExceptionIfPossible(exception, page);

        renderer.renderPageMarkupResponse(pageService.getLoginPage());

    }
}