Java Code Examples for org.apache.shiro.web.util.WebUtils#issueRedirect()

The following examples show how to use org.apache.shiro.web.util.WebUtils#issueRedirect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GreenStepMobileFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {  	
	if (isAjaxRequest((HttpServletRequest)request)) {
		response.setCharacterEncoding( Constants.BASE_ENCODING );
		response.setContentType("application/json");
		response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
		return;
	}
	if (this.isIframeMode((HttpServletRequest)request)) { // iframe 不要導向 login.action 因為畫面會怪怪的    		
		WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
		return;
	}    	
	if (this.isDojoxContentPane((HttpServletRequest)request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    		
		WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
		return;
	}
	WebUtils.issueRedirect(request, response, getLoginUrl());
}
 
Example 2
Source File: FormAuthenticationFilter.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * 登录成功调用事件
 */
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {

	// 登录成功后初始化授权信息并处理登录后的操作
	authorizingRealm.onLoginSuccess((LoginInfo)subject.getPrincipal(), (HttpServletRequest) request);
	
	// 登录操作如果是Ajax操作,直接返回登录信息字符串。
	if (ServletUtils.isAjaxRequest((HttpServletRequest) request)) {
		request.getRequestDispatcher(getSuccessUrl()).forward(request, response); // AJAX不支持Redirect改用Forward
	}
	// 登录成功直接返回到首页
	else {
		String url = request.getParameter("__url");
		if (StringUtils.isNotBlank(url)) {
			WebUtils.issueRedirect(request, response, url, null, true);
		} else {
			WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
		}
	}
	return false;
}
 
Example 3
Source File: OAuth2AuthenticationFilter.java    From mumu with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {


    String error = request.getParameter("error");
    String errorDescription = request.getParameter("error_description");
    if(!StringUtils.isEmpty(error)) {//如果服务端返回了错误
        WebUtils.issueRedirect(request, response, failureUrl + "?error=" + error + "error_description=" + errorDescription);
        return false;
    }

    Subject subject = getSubject(request, response);
    if(!subject.isAuthenticated()) {
        if(StringUtils.isEmpty(request.getParameter(authcCodeParam))) {
            //如果用户没有身份验证,且没有auth code,则重定向到服务端授权
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }
    }

    return executeLogin(request, response);
}
 
Example 4
Source File: OAuth2AuthenticationFilter.java    From Shiro-Action with MIT License 6 votes vote down vote up
/**
    * 当 isAccessAllowed 不允许访问时, 判断 oauth2 服务提供商是否返回了错误信息 <p>
*     如果没有返回错误信息, 则判断
    */
   @Override
   protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
       String error = request.getParameter("error");
       String errorDescription = request.getParameter("error_description");

       if (!StringUtils.isEmpty(error)) { // 如果服务端返回了错误
           WebUtils.issueRedirect(request, response, "/error?error=" + error + "error_description=" + errorDescription);
           return false;
       }

       if (StringUtils.isEmpty(request.getParameter(AUTHC_CODE_PARAM))) {
           // 如果用户没有身份验证, 且没有 auth code, 则重定向到登录页面.
           saveRequestAndRedirectToLogin(request, response);
           return false;
       }

       // 执行登录操作.
       return executeLogin(request, response);
   }
 
Example 5
Source File: AccessControlFilter.java    From tapestry-security with Apache License 2.0 6 votes vote down vote up
/**
     * Convenience method for subclasses that merely acquires the {@link #getLoginUrl() getLoginUrl} and redirects
     * the request to that url.
     * <p/>
     * <b>N.B.</b>  If you want to issue a redirect with the intention of allowing the user to then return to their
     * originally requested URL, don't use this method directly.  Instead you should call
     * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
     * saveRequestAndRedirectToLogin(request,response)}, which will save the current request state so that it can
     * be reconstructed and re-used after a successful login.
     *
     * @param request  the incoming <code>ServletRequest</code>
     * @param response the outgoing <code>ServletResponse</code>
     * @throws IOException if an error occurs.
     */
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
//        String loginUrl = getLoginUrl();
    	String localeName = loginContextService.getLocaleFromPath(WebUtils.getPathWithinApplication(WebUtils.toHttp(request)));
    	String loginUrl = localeName == null ? '/' + loginContextService.getLoginPage() : '/' + localeName + '/' + loginContextService.getLoginPage();
    	
    	// We are not in the response pipeline yet, and it's possible that Tapestry isn't handling this response, but it's still probably 
    	// better than sending a 302 and the full the page
    	if ("XMLHttpRequest".equals(WebUtils.toHttp(request).getHeader("X-Requested-With"))) {
    		WebUtils.toHttp(response).setContentType("application/json;charset=UTF-8");
    		OutputStream os = WebUtils.toHttp(response).getOutputStream();
		    if (TAPESTRY_VERSION.startsWith("5.4")) {
			    os.write(("{\"_tapestry\":{\"redirectURL\":\"" + WebUtils.toHttp(request).getContextPath() + loginUrl + "\"}}").getBytes());
		    } else {
			    os.write(("{\"redirectURL\":\"" + WebUtils.toHttp(request).getContextPath() + loginUrl + "\"}").getBytes());
		    }
		    os.close();
    	}
    	else WebUtils.issueRedirect(request, response, loginUrl);
    }
 
Example 6
Source File: KickoutSessionFilter.java    From supplierShop with MIT License 5 votes vote down vote up
private boolean isAjaxResponse(ServletRequest request, ServletResponse response) throws IOException
{
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (ServletUtils.isAjaxRequest(req))
    {
        AjaxResult ajaxResult = AjaxResult.error("您已在别处登录,请您修改密码或重新登录");
        ServletUtils.renderString(res, objectMapper.writeValueAsString(ajaxResult));
    }
    else
    {
        WebUtils.issueRedirect(request, response, kickoutUrl);
    }
    return false;
}
 
Example 7
Source File: GreenStepBaseFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
 	if ( !Constants.getSystem().equals( Constants.getMainSystem() ) && !isAjaxRequest((HttpServletRequest)request) ) { // 非 core-web
 		try {
	if ( this.loginUseCurrentCookieForGeneralPackage(request, response) ) { // no need to login-page
		String url = SimpleUtils.getHttpRequestUrl( (HttpServletRequest)request );
		logger.warn("URL = " + url );					
		WebUtils.issueRedirect(request, response, url);
		return;
	}
} catch (Exception e) {
	e.printStackTrace();
}
 	}    	
 	if (isAjaxRequest((HttpServletRequest)request)) {
 		response.setCharacterEncoding( Constants.BASE_ENCODING );
 		response.setContentType("application/json");
 		response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
 		return;
 	}
 	if (this.isIframeMode((HttpServletRequest)request)) { // iframe 不要導向 login.action 因為畫面會怪怪的    		
 		WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
 		return;
 	}    	
 	if (this.isDojoxContentPane((HttpServletRequest)request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    		
 		WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
 		return;
 	}
 	WebUtils.issueRedirect(request, response, getLoginUrl());
 }
 
Example 8
Source File: FormAuthenticationFilter.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
@Override
	protected void issueSuccessRedirect(ServletRequest request,
			ServletResponse response) throws Exception {
//		Principal p = UserUtils.getPrincipal();
//		if (p != null && !p.isMobileLogin()){
			 WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
//		}else{
//			super.issueSuccessRedirect(request, response);
//		}
	}
 
Example 9
Source File: FormAuthenticationFilter.java    From easyweb with Apache License 2.0 5 votes vote down vote up
@Override
	protected void issueSuccessRedirect(ServletRequest request,
			ServletResponse response) throws Exception {
//		Principal p = UserUtils.getPrincipal();
//		if (p != null && !p.isMobileLogin()){
			 WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
//		}else{
//			super.issueSuccessRedirect(request, response);
//		}
	}
 
Example 10
Source File: SysUserFilter.java    From es with Apache License 2.0 5 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    User user = (User) request.getAttribute(Constants.CURRENT_USER);
    String url = null;
    if (Boolean.TRUE.equals(user.getDeleted())) {
        url = getUserNotfoundUrl();
    } else if (user.getStatus() == UserStatus.blocked) {
        url = getUserBlockedUrl();
    } else {
        url = getUserUnknownErrorUrl();
    }

    WebUtils.issueRedirect(request, response, url);
}
 
Example 11
Source File: JsetsAuthorizationFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    Subject subject = getSubject(request, response);
    //未认证
    if (null == subject.getPrincipal()) {
		if (CommonUtils.isAjax(WebUtils.toHttp(request))) {
			CommonUtils.ajaxFailed(WebUtils.toHttp(response) 
					,HttpServletResponse.SC_UNAUTHORIZED
					,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED
					,ShiroProperties.REST_MESSAGE_AUTH_UNAUTHORIZED);
		}
        saveRequestAndRedirectToLogin(request, response);
    //未授权
    } else {
		if (CommonUtils.isAjax(WebUtils.toHttp(request))) {
			CommonUtils.ajaxFailed(WebUtils.toHttp(response) 
					,HttpServletResponse.SC_FORBIDDEN
					,ShiroProperties.REST_CODE_AUTH_FORBIDDEN
					,ShiroProperties.REST_MESSAGE_AUTH_FORBIDDEN);
		}else{
            String unauthorizedUrl = getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN);
            }
		}
    }
    return false;
}
 
Example 12
Source File: AuthenticationFilter.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
/**
    * Redirects to user to the previously attempted URL after a successful login.  This implementation simply calls
    * <code>{@link org.apache.shiro.web.util.WebUtils WebUtils}.{@link WebUtils#redirectToSavedRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse, String) redirectToSavedRequest}</code>
    * using the {@link #getSuccessUrl() successUrl} as the {@code fallbackUrl} argument to that call.
    *
    * @param request  the incoming request
    * @param response the outgoing response
    * @throws Exception if there is a problem redirecting.
    */
protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
	String requestUri = getSuccessUrl();
	if (!requestUri.startsWith("/")) requestUri = "/" + requestUri;
	if (isRedirectToSavedUrl()) {
		getLoginContextService().redirectToSavedRequest(requestUri);
		return;
	}
	WebUtils.issueRedirect(request, response, requestUri);
}
 
Example 13
Source File: HttpFilter.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
/**
 * Redirects the request to the same exact incoming URL, but with the port listed in the filter's configuration.
 *
 * @param request     the incoming <code>ServletRequest</code>
 * @param response    the outgoing <code>ServletResponse</code>
 * @param mappedValue the config specified for the filter in the matching request's filter chain.
 * @return {@code false} always to force a redirect.
 */
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

    //just redirect to the specified port:
    int port = toPort(mappedValue);

    String scheme = getScheme(request.getScheme(), port);
    
    StringBuilder sb = new StringBuilder();
    sb.append(scheme).append("://");
    sb.append(request.getServerName());
    if (port != DEFAULT_HTTP_PORT && port != SslFilter.DEFAULT_HTTPS_PORT) {
        sb.append(":");
        sb.append(port);
    }
    if (request instanceof HttpServletRequest) {
        sb.append(WebUtils.toHttp(request).getRequestURI());
        String query = WebUtils.toHttp(request).getQueryString();
        if (query != null) {
            sb.append("?").append(query);
        }
    }

    WebUtils.issueRedirect(request, response, sb.toString());

    return false;
}
 
Example 14
Source File: GreenStepBaseFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
	if (isAjaxRequest((HttpServletRequest)request)) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
		return;
	}
	if (this.isDojoxContentPane((HttpServletRequest)request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    		
		WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
		return;
	}
	WebUtils.issueRedirect(request, response, getLoginUrl());
}
 
Example 15
Source File: CasAuthenticationFilter.java    From frpMgr with MIT License 5 votes vote down vote up
/**
 * 登录成功调用事件
 */
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
	
	// 登录成功后初始化授权信息并处理登录后的操作
	authorizingRealm.onLoginSuccess((LoginInfo)subject.getPrincipal(), (HttpServletRequest)request);
	
	String url = request.getParameter("__url");
	if (StringUtils.isNotBlank(url)) {
		WebUtils.issueRedirect(request, response, url, null, true);
	} else {
		WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
	}
	return false;
}
 
Example 16
Source File: URLPathMatchingFilter.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

    //请求的url
    String requestURL = getPathWithinApplication(request);
    System.out.println("请求的url :" + requestURL);
    Subject subject = SecurityUtils.getSubject();
    if (!subject.isAuthenticated()) {
        // 如果没有登录, 进入登录流程
        WebUtils.issueRedirect(request, response, "/admin/login");
        return false;
    }

    //从session里读取当前用户的权限URL列表
    Set<String> urls = (Set<String>) subject.getSession().getAttribute("permissionUrls");
    if (urls.contains(requestURL)) {
        return true;
    }

    //没有权限
    if (isAjax((HttpServletRequest) request)) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "没有权限访问");
        writer.write(JSONObject.toJSONString(map));
    } else {
        WebUtils.issueRedirect(request, response, "/403");
    }
    return false;
}
 
Example 17
Source File: RestAuthorizationFilter.java    From Shiro-Action with MIT License 4 votes vote down vote up
/**
 * 当没有权限被拦截时:
 *          如果是 AJAX 请求, 则返回 JSON 数据.
 *          如果是普通请求, 则跳转到配置 UnauthorizedUrl 页面.
 */
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    Subject subject = getSubject(request, response);
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    // 如果未登录
    if (subject.getPrincipal() == null) {
        // AJAX 请求返回 JSON
        if (WebHelper.isAjaxRequest(WebUtils.toHttp(request))) {
            if (log.isDebugEnabled()) {
                log.debug("sessionId: [{}], ip: [{}] 请求 restful url : {}, 未登录被拦截.",
                        httpServletRequest.getRequestedSessionId(),
                        IPUtils.getIpAddr(),
                        this.getPathWithinApplication(request));
            }
            WebHelper.writeJson(ResultBean.error("未登录"), response);
        } else {
            // 其他请求跳转到登陆页面
            saveRequestAndRedirectToLogin(request, response);
        }
    } else {
        // 如果已登陆, 但没有权限
        // 对于 AJAX 请求返回 JSON
        if (WebHelper.isAjaxRequest(WebUtils.toHttp(request))) {
            if (log.isDebugEnabled()) {
                log.debug("用户: [{}] 请求 restful url : {}, 无权限被拦截.", subject.getPrincipal(), this.getPathWithinApplication(request));
            }

            WebHelper.writeJson(ResultBean.error("无权限"), response);
        } else {
            // 对于普通请求, 跳转到配置的 UnauthorizedUrl 页面.
            // 如果未设置 UnauthorizedUrl, 则返回 401 状态码
            String unauthorizedUrl = getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }

    }
    return false;
}
 
Example 18
Source File: OnlineSessionFilter.java    From ruoyiplus with MIT License 4 votes vote down vote up
@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException
{
    WebUtils.issueRedirect(request, response, loginUrl);
}
 
Example 19
Source File: OnlineSessionFilter.java    From supplierShop with MIT License 4 votes vote down vote up
@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException
{
    WebUtils.issueRedirect(request, response, loginUrl);
}
 
Example 20
Source File: OnlineSessionFilter.java    From RuoYi with Apache License 2.0 2 votes vote down vote up
/**
 * 跳转到登录页
 * @param request 请求
 * @param response 响应
 * @throws IOException 异常
 */
@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    WebUtils.issueRedirect(request, response, loginUrl);
}