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

The following examples show how to use org.apache.shiro.web.util.WebUtils. These examples are extracted from open source projects. 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 Project: permission   Source File: JWTFilter.java    License: 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 2
Source Project: frpMgr   Source File: FormAuthenticationFilter.java    License: 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 Project: easyweb   Source File: SessionManager.java    License: 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 4
Source Project: faster-framework-project   Source File: ShiroFilter.java    License: 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 5
Source Project: bootshiro   Source File: AccountController.java    License: 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 6
Source Project: bootshiro   Source File: AbstractPathMatchingFilter.java    License: 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 7
Source Project: roncoo-pay   Source File: RcCaptchaValidateFilter.java    License: 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 8
Source Project: okta-auth-java   Source File: OverlySimpleCsrfFilter.java    License: 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 9
Source Project: super-cloudops   Source File: AbstractIamSessionManager.java    License: 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 10
/**
 * 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 11
Source Project: Shiro-Action   Source File: OAuth2AuthenticationFilter.java    License: 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 12
Source Project: Shiro-Action   Source File: RestAuthorizationFilter.java    License: 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 13
Source Project: Shiro-Action   Source File: RestFormAuthenticationFilter.java    License: 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 Project: mblog   Source File: AuthenticatedFilter.java    License: 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 15
@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 16
Source Project: nano-framework   Source File: DefaultWebSessionManager.java    License: 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 17
@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 18
@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 19
Source Project: usergrid   Source File: HttpRequestSessionManager.java    License: 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 20
@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 21
Source Project: mumu   Source File: OAuth2AuthenticationFilter.java    License: 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 22
Source Project: zheng   Source File: UpmsAuthenticationFilter.java    License: 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 23
Source Project: nano-framework   Source File: CookieRememberMeManager.java    License: 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 24
Source Project: supplierShop   Source File: KickoutSessionFilter.java    License: 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 25
Source Project: spring-boot-shiro   Source File: MySessionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
    String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
    //如果请求头中有 Authorization 则其值为sessionId
    if (!StringUtils.isEmpty(id)) {
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        return id;
    } else {
        //否则按默认规则从cookie取sessionId
        return super.getSessionId(request, response);
    }
}
 
Example 26
Source Project: SENS   Source File: URLPathMatchingFilter.java    License: 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 27
Source Project: easyweb   Source File: AjaxSessionManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取sessionId从请求中
 *
 * @param request
 * @param response
 * @return
 */
private Serializable getReferencedSessionId(ServletRequest request, ServletResponse response) {
    String id = this.getSessionIdCookieValue(request, response);
    if (id != null) {
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "cookie");
    } else {
        id = this.getUriPathSegmentParamValue(request, "JSESSIONID");
        if (id == null) {
            // 获取请求头中的session
            id = WebUtils.toHttp(request).getHeader(this.authorization);
            if (id == null) {
                String name = this.getSessionIdName();
                id = request.getParameter(name);
                if (id == null) {
                    id = request.getParameter(name.toLowerCase());
                }
            }
        }
        if (id != null) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "url");
        }
    }

    if (id != null) {
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
    }

    return id;
}
 
Example 28
Source Project: Shop-for-JavaWeb   Source File: AppUserController.java    License: MIT License 5 votes vote down vote up
/**
 * 注册 - 提交手机号码
 */
@RequestMapping(value = "/register-step1-post")
public String registerStep1(HttpServletRequest request, HttpServletResponse response) {
    if (!isValidApp(request)) {
        return renderInvalidApp(response);
    }

    boolean result;
    String message;
    Map<String, Object> data = Maps.newHashMap();
    String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
    data.put("userLoginName", username);

    if (ValidateUtils.isMobile(username)) {
        result = true;
        message = "";
    } else {
        result = false;
        message = ValidateUtils.getErrMsg();
    }

    User user = userService.getByLoginName2(username);
    if (user != null && StringUtils.isNotBlank(user.getId())) {
        result = false;
        message = "电话号码已存在";
    } else {
        //发送手机验证码
        SmsUtils.sendRegisterCode(username);
    }

    return renderString(response, result, message, data);
}
 
Example 29
/**
 * Permissive {@link AuthorizationException} 401 and 403 handling.
 */
@Override
protected void cleanup(final ServletRequest request, final ServletResponse response, Exception failure)
    throws ServletException, IOException
{
  // decode target exception
  Throwable cause = failure;
  if (cause instanceof ServletException) {
    cause = cause.getCause();
  }

  // special handling for authz failures due to permissive
  if (cause instanceof AuthorizationException) {
    // clear the failure
    failure = null;

    Subject subject = getSubject(request, response);
    boolean authenticated = subject.getPrincipal() != null && subject.isAuthenticated();

    if (authenticated) {
      // authenticated subject -> 403 forbidden
      WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    else {
      // unauthenticated subject -> 401 inform to authenticate
      try {
        // TODO: Should we build in browser detecting to avoid sending 401, should that be its own filter?

        onAccessDenied(request, response);
      }
      catch (Exception e) {
        failure = e;
      }
    }
  }

  super.cleanup(request, response, failure);
}
 
Example 30
Source Project: frpMgr   Source File: CasAuthenticationFilter.java    License: 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;
}