org.apache.shiro.web.util.WebUtils Java Examples

The following examples show how to use org.apache.shiro.web.util.WebUtils. 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: OverlySimpleCsrfFilter.java    From okta-auth-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

    HttpSession session = WebUtils.toHttp(request).getSession(true);
    String expectedCsrf = (String) session.getAttribute(CSRF_KEY);

    // figure out the next CSRF token
    String nextCSRF = UUID.randomUUID().toString();
    request.setAttribute(CSRF_KEY, nextCSRF);

    if (shouldFilter(request)) {
        String actualCsrf = request.getParameter(CSRF_KEY);

        // if the csrf token does not match stop processing the filter
        if (Strings.isEmpty(expectedCsrf) || !expectedCsrf.equals(actualCsrf)) {
            request.getServletContext().log("CSRF token did not match");
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    }
    chain.doFilter(request, response);

    // next key
    session.setAttribute(CSRF_KEY, nextCSRF);
}
 
Example #2
Source File: HmacAuthcFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	if(isHmacSubmission(request)){
		AuthenticationToken token = createHmacToken(request, response);
		try {
			Subject subject = getSubject(request, response);
			subject.login(token);
			return true;
		} catch (AuthenticationException e) {
			LOGGER.error(request.getRemoteHost()+" HMAC认证  "+e.getMessage());
			CommonUtils.restFailed(WebUtils.toHttp(response)
								,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage());
		}
	}
	return false;
}
 
Example #3
Source File: JwtRolesFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
	Subject subject = getSubject(request, response); 
	if ((null == subject || !subject.isAuthenticated()) && isJwtSubmission(request)) {
		AuthenticationToken token = createJwtToken(request, response);
		try {
			subject = getSubject(request, response);
			subject.login(token);
			return this.checkRoles(subject,mappedValue);
		} catch (AuthenticationException e) {
			LOGGER.error(request.getRemoteHost()+" JWT鉴权  "+e.getMessage());
			CommonUtils.restFailed(WebUtils.toHttp(response)
									,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage());
		}	
	}
	return false;
}
 
Example #4
Source File: HttpRequestSessionManager.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public Session start( SessionContext context ) throws AuthorizationException {
    if ( !WebUtils.isHttp( context ) ) {
        String msg = "SessionContext must be an HTTP compatible implementation.";
        throw new IllegalArgumentException( msg );
    }

    HttpServletRequest request = WebUtils.getHttpRequest( context );

    String host = getHost( context );

    Session session = createSession( request, host );
    request.setAttribute( REQUEST_ATTRIBUTE_KEY, session );

    return session;
}
 
Example #5
Source File: JcaptchaFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletResponse httpResponse = WebUtils.toHttp(response);
	httpResponse.setHeader("Cache-Control", "no-store");
	httpResponse.setHeader("Pragma", "no-cache");
	httpResponse.setDateHeader("Expires", 0);
	httpResponse.setContentType("image/jpeg");
	ServletOutputStream output = httpResponse.getOutputStream();
	try {
		BufferedImage image = this.captchaProvider.generateCaptcha(WebUtils.toHttp(request));
		ImageIO.write(image, "jpg", output);
		output.flush();
	} finally {
		output.close();
	}
}
 
Example #6
Source File: JWTFilter.java    From permission with MIT License 6 votes vote down vote up
/**
 * 防止token过期前端弹出登录框
 * 返回401错误码  前端跳转到登录页
 * @param request
 * @param response
 * @return
 */
@Override
protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
    log.debug("Authentication required: sending 401 Authentication challenge response.");
    HttpServletResponse httpResponse = WebUtils.toHttp(response);
    httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
    httpResponse.setCharacterEncoding("utf-8");
    httpResponse.setContentType("application/json; charset=utf-8");
    final String message = "未认证,请在前端系统进行认证";
    try (PrintWriter out = httpResponse.getWriter()) {
        String responseJson = "{\"message\":\"" + message + "\"}";
        out.print(responseJson);
    } catch (IOException e) {
        log.error("sendChallenge error:", e);
    }
    return false;
}
 
Example #7
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 #8
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 #9
Source File: UpmsAuthenticationFilter.java    From zheng with MIT License 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    StringBuffer ssoServerUrl = new StringBuffer(PropertiesFileUtil.getInstance("zheng-upms-client").get("zheng.upms.sso.server.url"));
    // server需要登录
    String upmsType = PropertiesFileUtil.getInstance("zheng-upms-client").get("zheng.upms.type");
    if ("server".equals(upmsType)) {
        WebUtils.toHttp(response).sendRedirect(ssoServerUrl.append("/sso/login").toString());
        return false;
    }
    ssoServerUrl.append("/sso/index").append("?").append("appid").append("=").append(PropertiesFileUtil.getInstance("zheng-upms-client").get("zheng.upms.appID"));
    // 回跳地址
    HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
    StringBuffer backurl = httpServletRequest.getRequestURL();
    String queryString = httpServletRequest.getQueryString();
    if (StringUtils.isNotBlank(queryString)) {
        backurl.append("?").append(queryString);
    }
    ssoServerUrl.append("&").append("backurl").append("=").append(URLEncoder.encode(backurl.toString(), "utf-8"));
    WebUtils.toHttp(response).sendRedirect(ssoServerUrl.toString());
    return false;
}
 
Example #10
Source File: CookieRememberMeManager.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
@Override
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {
    if (!WebUtils.isHttp(subject)) {
        if (LOGGER.isDebugEnabled()) {
            String msg = "Subject argument is not an HTTP-aware instance.  This is required to obtain a servlet " +
                    "request and response in order to set the rememberMe cookie. Returning immediately and " +
                    "ignoring rememberMe operation.";
            LOGGER.debug(msg);
        }
        
        return;
    }


    HttpServletRequest request = WebUtils.getHttpRequest(subject);
    HttpServletResponse response = WebUtils.getHttpResponse(subject);

    // base 64 encode it and store as a cookie:
    String base64 = Base64.encodeToString(serialized);

    // the class attribute is really a template for the outgoing cookies
    Cookie cookie = getCookie(); 
    cookie.setValue(base64);
    cookie.saveTo(request, response);
}
 
Example #11
Source File: DefaultWebSessionManager.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
@Override
protected void onStart(final Session session, final SessionContext context) {
    if (!WebUtils.isHttp(context)) {
        LOGGER.debug("SessionContext argument is not HTTP compatible or does not have an HTTP request/response " +
                "pair. No session ID cookie will be set.");
        return;
    }
    
    final HttpServletRequest request = WebUtils.getHttpRequest(context);
    final HttpServletResponse response = WebUtils.getHttpResponse(context);

    if (isSessionIdCookieEnabled()) {
        final Serializable sessionId = session.getId();
        storeSessionId(sessionId, request, response);
    } else {
        LOGGER.debug("Session ID cookie is disabled.  No cookie has been set for new session with id {}", session.getId());
    }

    request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
    request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
}
 
Example #12
Source File: SessionManager.java    From easyweb with Apache License 2.0 6 votes vote down vote up
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
	// 如果参数中包含“__sid”参数,则使用此sid会话。 例如:http://localhost/project?__sid=xxx&__cookie=true
	String sid = request.getParameter("__sid");
	if (StringUtils.isNotBlank(sid)) {
		// 是否将sid保存到cookie,浏览器模式下使用此参数。
		if (WebUtils.isTrue(request, "__cookie")){
	        HttpServletRequest rq = (HttpServletRequest)request;
	        HttpServletResponse rs = (HttpServletResponse)response;
			Cookie template = getSessionIdCookie();
	        Cookie cookie = new SimpleCookie(template);
			cookie.setValue(sid); cookie.saveTo(rq, rs);
		}
		// 设置当前session状态
           request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                   ShiroHttpServletRequest.URL_SESSION_ID_SOURCE); // session来源与url
           request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sid);
           request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
       	return sid;
	}else{
		return super.getSessionId(request, response);
	}
}
 
Example #13
Source File: RestFormAuthenticationFilter.java    From Shiro-Action with MIT License 6 votes vote down vote up
@Override
protected boolean pathsMatch(String path, ServletRequest request) {
    boolean flag;
    String requestURI = this.getPathWithinApplication(request);

    String[] strings = path.split("==");

    if (strings.length <= 1) {
        // 普通的 URL, 正常处理
        flag = this.pathsMatch(strings[0], requestURI);
    } else {
        // 获取当前请求的 http method.
        String httpMethod = WebUtils.toHttp(request).getMethod().toUpperCase();
        // 匹配当前请求的 url 和 http method 与过滤器链中的的是否一致
        flag = httpMethod.equals(strings[1].toUpperCase()) && this.pathsMatch(strings[0], requestURI);
    }

    if (flag) {
        log.debug("URL : [{}] matching authc filter : [{}]", requestURI, path);
    }
    return flag;
}
 
Example #14
Source File: JsetsLogoutFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
       Subject subject = getSubject(request, response);

       // Check if POST only logout is enabled
       if (isPostOnlyLogout()) {
           // check if the current request's method is a POST, if not redirect
           if (!WebUtils.toHttp(request).getMethod().toUpperCase(Locale.ENGLISH).equals("POST")) {
              return onLogoutRequestNotAPost(request, response);
           }
       }

       String redirectUrl = getRedirectUrl(request, response, subject);
       //try/catch added for SHIRO-298:
       try {
       	String account = (String) subject.getPrincipal();
           subject.logout();
           this.authListenerManager.onLogout(request, account);
       } catch (SessionException ise) {
       	LOGGER.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
       }
       issueRedirect(request, response, redirectUrl);
       return false;
}
 
Example #15
Source File: RcCaptchaValidateFilter.java    From roncoo-pay with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
	// 1、设置验证码是否开启属性,页面可以根据该属性来决定是否显示验证码
	request.setAttribute("captchaEbabled", captchaEbabled);

	HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
	// 2、判断验证码是否禁用 或不是表单提交(允许访问)
	if (captchaEbabled == false || !"post".equalsIgnoreCase(httpServletRequest.getMethod())) {
		return true;
	}
	// 3、此时是表单提交,验证验证码是否正确
	// 获取页面提交的验证码
	String submitCaptcha = httpServletRequest.getParameter(captchaParam);
	// 获取session中的验证码
	String captcha = (String) httpServletRequest.getSession().getAttribute("rcCaptcha");
	if (submitCaptcha.equals(captcha)) {
		return true;
	}
	return false;
}
 
Example #16
Source File: AbstractIamSessionManager.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
protected void onStart(Session session, SessionContext context) {
	if (!WebUtils.isHttp(context)) {
		throw new IllegalStateException(String.format("IAM currently only supports HTTP protocol family!"));
	}

	HttpServletRequest request = WebUtils.getHttpRequest(context);
	HttpServletResponse response = WebUtils.getHttpResponse(context);
	if (isSessionIdCookieEnabled()) {
		if (StringUtils2.isEmpty(session.getId())) {
			throw new IllegalArgumentException("sessionId cannot be null when persisting for subsequent requests.");
		}
		// Storage session token
		saveSessionIdCookieIfNecessary(request, response, session.getId().toString());
	} else {
		log.debug("Session ID cookie is disabled.  No cookie has been set for new session with id {}", session.getId());
	}
	request.removeAttribute(REFERENCED_SESSION_ID_SOURCE);
	request.setAttribute(REFERENCED_SESSION_IS_NEW, TRUE);
}
 
Example #17
Source File: AbstractPathMatchingFilter.java    From bootshiro with MIT License 6 votes vote down vote up
/**
 * description 重写URL匹配  加入httpMethod支持
 *
 * @param path 1
 * @param request 2
 * @return boolean
 */
@Override
protected boolean pathsMatch(String path, ServletRequest request) {
    String requestURI = this.getPathWithinApplication(request);
    if (requestURI != null && requestURI.endsWith(DEFAULT_PATH_SEPARATOR)) {
        requestURI = requestURI.substring(0, requestURI.length() - 1);
    }
    // path: url==method eg: http://api/menu==GET   需要解析出path中的url和httpMethod
    String[] strings = path.split("==");
    if (strings[0] != null && strings[0].endsWith(DEFAULT_PATH_SEPARATOR)) {
        strings[0] = strings[0].substring(0 , strings[0].length() - 1);
    }
    if (strings.length <= 1) {
        // 分割出来只有URL
        return this.pathsMatch(strings[0], requestURI);
    } else {
        // 分割出url+httpMethod,判断httpMethod和request请求的method是否一致,不一致直接false
        String httpMethod = WebUtils.toHttp(request).getMethod().toUpperCase();
        return httpMethod.equals(strings[1].toUpperCase()) && this.pathsMatch(strings[0], requestURI);
    }
}
 
Example #18
Source File: CentralAuthenticatorEndpoint.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Secondary certification validation
 *
 * @param request
 * @return
 */
@PostMapping(URI_S_SECOND_VALIDATE)
@ResponseBody
public RespBase<SecondAuthcAssertModel> secondaryValidate(HttpServletRequest request) {
	log.info("Secondary validating, sessionId: {} <= {}", getSessionId(), getFullRequestURL(request));

	RespBase<SecondAuthcAssertModel> resp = new RespBase<>();
	// Requires parameters
	String secondAuthCode = WebUtils.getCleanParam(request, config.getParam().getSecondaryAuthCode());
	String fromAppName = WebUtils.getCleanParam(request, config.getParam().getApplication());
	// Secondary authentication assertion.
	resp.setData(authHandler.secondaryValidate(secondAuthCode, fromAppName));

	log.info("Secondary validated. => {}", resp);
	return resp;
}
 
Example #19
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 #20
Source File: RestAuthorizationFilter.java    From Shiro-Action with MIT License 6 votes vote down vote up
@Override
protected boolean pathsMatch(String path, ServletRequest request) {
    boolean flag;
    String requestURI = this.getPathWithinApplication(request);

    String[] strings = path.split("==");

    if (strings.length <= 1) {
        // 普通的 URL, 正常处理
        flag =  this.pathsMatch(strings[0], requestURI);
    } else {
        // 获取当前请求的 http method.
        String httpMethod = WebUtils.toHttp(request).getMethod().toUpperCase();

        // 匹配当前请求的 http method 与 过滤器链中的的是否一致
        flag =  httpMethod.equals(strings[1].toUpperCase()) && this.pathsMatch(strings[0], requestURI);
    }

    if (flag) {
        log.debug("URL : [{}] matching perms filter : [{}]", requestURI, path);
    }
    return flag;
}
 
Example #21
Source File: AccountController.java    From bootshiro with MIT License 6 votes vote down vote up
/**
 * description 登录签发 JWT ,这里已经在 passwordFilter 进行了登录认证
 *
 * @param request 1
 * @param response 2
 * @return com.usthe.bootshiro.domain.vo.Message
 */
@ApiOperation(value = "用户登录", notes = "POST用户登录签发JWT")
@PostMapping("/login")
public Message accountLogin(HttpServletRequest request, HttpServletResponse response) {
    Map<String, String> params = RequestResponseUtil.getRequestBodyMap(request);
    String appId = params.get("appId");
    // 根据appId获取其对应所拥有的角色(这里设计为角色对应资源,没有权限对应资源)
    String roles = accountService.loadAccountRole(appId);
    // 时间以秒计算,token有效刷新时间是token有效过期时间的2倍
    long refreshPeriodTime = 36000L;
    String jwt = JsonWebTokenUtil.issueJWT(UUID.randomUUID().toString(), appId,
            "token-server", refreshPeriodTime >> 1, roles, null, SignatureAlgorithm.HS512);
    // 将签发的JWT存储到Redis: {JWT-SESSION-{appID} , jwt}
    redisTemplate.opsForValue().set("JWT-SESSION-" + appId, jwt, refreshPeriodTime, TimeUnit.SECONDS);
    AuthUser authUser = userService.getUserByAppId(appId);
    authUser.setPassword(null);
    authUser.setSalt(null);

    LogExeManager.getInstance().executeLogTask(LogTaskFactory.loginLog(appId, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 1, "登录成功"));

    return new Message().ok(1003, "issue jwt success").addData("jwt", jwt).addData("user", authUser);
}
 
Example #22
Source File: ShiroFilter.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    httpResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ((HttpServletRequest) request).getHeader("origin"));
    httpResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS,TRACE");
    String accessControlRequestHeaders = httpServletRequest.getHeader("Access-Control-Request-Headers");
    if (!StringUtils.isEmpty(accessControlRequestHeaders)) {
        httpResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, accessControlRequestHeaders);
    }
    httpResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    if (RequestMethod.OPTIONS.name().equals(WebUtils.toHttp(request).getMethod())) {
        httpResponse.setStatus(HttpStatus.OK.value());
        return false;
    }
    return super.preHandle(request, response);
}
 
Example #23
Source File: AuthenticatedFilter.java    From mblog with GNU General Public License v3.0 6 votes vote down vote up
@Override
  protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
          throws ServletException, IOException {

      Subject subject = SecurityUtils.getSubject();
      if (subject.isAuthenticated() || subject.isRemembered()) {
          chain.doFilter(request, response);
      } else {
          WebUtils.saveRequest(request);
          String path = WebUtils.getContextPath((HttpServletRequest) request);
          String url = loginUrl;
          if (StringUtils.isNotBlank(path) && path.length() > 1) {
              url = path + url;
          }

          if (isAjaxRequest((HttpServletRequest) request)) {
              response.setContentType("application/json;charset=UTF-8");
              response.getWriter().print(JSON.toJSONString(Result.failure("您还没有登录!")));
          } else {
response.setContentType("text/html;charset=UTF-8");
              response.getWriter().write(new Formatter().format(JS, url).toString());
          }
      }
  }
 
Example #24
Source File: JbootShiroFilter.java    From jboot with Apache License 2.0 5 votes vote down vote up
@Override
public void init() throws Exception {
    WebEnvironment env = WebUtils.getRequiredWebEnvironment(getServletContext());

    if (env.getServletContext().getContextPath() != null) {
        contextPathLength = env.getServletContext().getContextPath().length();
    }

    setSecurityManager(env.getWebSecurityManager());

    FilterChainResolver resolver = env.getFilterChainResolver();
    if (resolver != null) {
        setFilterChainResolver(resolver);
    }
}
 
Example #25
Source File: BearerAuthenticationFilter.java    From onedev with MIT License 5 votes vote down vote up
@Override
protected void cleanup(ServletRequest request, ServletResponse response, Exception existing) 
		throws ServletException, IOException {

       HttpServletResponse httpResponse = WebUtils.toHttp(response);
	if (existing != null && !httpResponse.isCommitted()) { 
		ExceptionUtils.handle(httpResponse, existing);
		existing = null;
	}
	
	super.cleanup(request, response, existing);
}
 
Example #26
Source File: JsetsFormAuthenticationFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
protected boolean onJcaptchaFailure(ServletRequest request, ServletResponse response,String message) {
	this.authListenerManager.onLoginFailure(request, getUsername(request),message);
	if (CommonUtils.isAjax(WebUtils.toHttp(request))) {
		CommonUtils.ajaxFailed(WebUtils.toHttp(response),HttpServletResponse.SC_UNAUTHORIZED
									, ShiroProperties.REST_CODE_AUTH_LOGIN_ERROR, message);
		return false;// 过滤器链停止
	}
	CommonUtils.setAuthMessage(request,message);
	return true;
}
 
Example #27
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 #28
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 #29
Source File: JsetsAccessControlFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 定位到登陆界面,返回false过滤器链停止
 */
protected boolean respondLogin(ServletRequest request, ServletResponse response) throws IOException{
	if (CommonUtils.isAjax(WebUtils.toHttp(request))) {
		CommonUtils.ajaxFailed(WebUtils.toHttp(response)
							,HttpServletResponse.SC_UNAUTHORIZED
							,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED
							,ShiroProperties.REST_MESSAGE_AUTH_UNAUTHORIZED);
		return false;// 过滤器链停止
	}
	saveRequestAndRedirectToLogin(request, response);
	return false;
}
 
Example #30
Source File: BasicAuthenticationFilter.java    From onedev with MIT License 5 votes vote down vote up
@Override
protected void cleanup(ServletRequest request, ServletResponse response, Exception existing) 
		throws ServletException, IOException {

       HttpServletResponse httpResponse = WebUtils.toHttp(response);
	if (existing != null && !httpResponse.isCommitted()) { 
		ExceptionUtils.handle(httpResponse, existing);
		existing = null;
	}
	
	super.cleanup(request, response, existing);
}