Java Code Examples for org.apache.shiro.web.util.WebUtils#toHttp()
The following examples show how to use
org.apache.shiro.web.util.WebUtils#toHttp() .
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: KeycloakHttpHeaderAuthTokenFactory.java From nexus3-keycloak-plugin with Apache License 2.0 | 6 votes |
@Override public AuthenticationToken createToken(ServletRequest request, ServletResponse response) { // Try to create auth token with the header X-Keycloak-Sec-Auth. AuthenticationToken token = super.createToken(request, response); // If the token is null, then try to create a new one with the header X-Auth-Token and X-Auth-Username if (token == null) { // See https://github.com/flytreeleft/nexus3-keycloak-plugin/pull/37 HttpServletRequest httpRequest = WebUtils.toHttp(request); String username = httpRequest.getHeader(KeycloakHttpHeaderAuthToken.HTTP_HEADER_USERNAME); String authToken = httpRequest.getHeader(KeycloakHttpHeaderAuthToken.HTTP_HEADER_AUTH_TOKEN); if (username != null && authToken != null) { String headerValue = username + ":" + authToken; token = createToken(KeycloakHttpHeaderAuthToken.HTTP_HEADER_NAME, headerValue, request.getRemoteHost()); } } return token; }
Example 2
Source File: RcCaptchaValidateFilter.java From roncoo-pay with Apache License 2.0 | 6 votes |
@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 3
Source File: RcCaptchaValidateFilter.java From mumu with Apache License 2.0 | 6 votes |
@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 4
Source File: BearerAuthenticationFilter.java From onedev with MIT License | 6 votes |
@Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { HttpServletRequest httpRequest = WebUtils.toHttp(request); String authzHeader = httpRequest.getHeader(HttpHeaders.AUTHORIZATION); if (authzHeader != null && authzHeader.startsWith(KubernetesHelper.BEARER + " ")) { String tokenValue = StringUtils.substringAfter(authzHeader, " "); User user = userManager.findByAccessToken(tokenValue); if (user != null) subject.login(new BearerAuthenticationToken(user)); } } return true; }
Example 5
Source File: JWTFilter.java From permission with MIT License | 6 votes |
/** * 防止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 6
Source File: HttpHeaderAuthenticationTokenFactorySupport.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override @Nullable public AuthenticationToken createToken(ServletRequest request, ServletResponse response) { List<String> headerNames = getHttpHeaderNames(); if (headerNames != null) { HttpServletRequest httpRequest = WebUtils.toHttp(request); for (String headerName : headerNames) { String headerValue = httpRequest.getHeader(headerName); if (headerValue != null) { return createToken(headerName, headerValue, request.getRemoteHost()); } } } return null; }
Example 7
Source File: RcFormAuthenticationFilter.java From mumu with Apache License 2.0 | 5 votes |
@Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { HttpServletRequest httpServletRequest = WebUtils.toHttp(request); if(getLoginUrl().equals(httpServletRequest.getServletPath())&&"get".equalsIgnoreCase(httpServletRequest.getMethod())){ return true; } if (request.getAttribute(getFailureKeyAttribute()) != null) { return true; } request.setAttribute("shiroLoginFailure", "用户未登录"); return super.onAccessDenied(request, response, mappedValue); }
Example 8
Source File: JWTOrFormAuthenticationFilter.java From shiro-jwt with MIT License | 5 votes |
@Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { HttpServletResponse httpResponse = WebUtils.toHttp(response); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return false; }
Example 9
Source File: ShiroAjaxSessionFilter.java From xmanager with Apache License 2.0 | 5 votes |
@Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest req = WebUtils.toHttp(request); String xmlHttpRequest = req.getHeader("X-Requested-With"); if (StringUtils.isNotBlank(xmlHttpRequest)) { if (xmlHttpRequest.equalsIgnoreCase("XMLHttpRequest")) { HttpServletResponse res = WebUtils.toHttp(response); // 采用res.sendError(401);在Easyui中会处理掉error,$.ajaxSetup中监听不到 res.setHeader("oauthstatus", "401"); return false; } } return super.onAccessDenied(request, response); }
Example 10
Source File: JwtFilter.java From watchdog-framework with MIT License | 5 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { log.info("PermissionAuthorizationFilter执行"); HttpServletResponse res = WebUtils.toHttp(response); if (!isLoginAttempt(request, response)) { writerResponse(res,ResponseCode.NOT_SING_IN.code,"无身份认证权限标示"); return false; } try { executeLogin(request, response); }catch (RequestException e){ writerResponse(res,e.getStatus(),e.getMsg()); return false; } Subject subject = getSubject(request, response); if(null != mappedValue){ String[] value = (String[])mappedValue; for (String permission : value) { if(permission==null || "".equals(permission.trim())){ continue; } if(subject.isPermitted(permission)){ return true; } } } if (null == subject.getPrincipal()) {//表示没有登录,返回登录提示 writerResponse(res,ResponseCode.NOT_SING_IN.code,ResponseCode.NOT_SING_IN.msg); }else{ writerResponse(res,ResponseCode.FAIL.code,"无权限访问"); } return false; }
Example 11
Source File: BearerAuthenticationFilter.java From onedev with MIT License | 5 votes |
@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 12
Source File: BasicAuthenticationFilter.java From onedev with MIT License | 5 votes |
@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 13
Source File: JwtFilter.java From ShiroJwt with MIT License | 5 votes |
/** * 无需转发,直接返回Response信息 */ private void response401(ServletResponse response, String msg) { HttpServletResponse httpServletResponse = WebUtils.toHttp(response); httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setContentType("application/json; charset=utf-8"); try (PrintWriter out = httpServletResponse.getWriter()) { String data = JsonConvertUtil.objectToJson(new ResponseBean(HttpStatus.UNAUTHORIZED.value(), "无权访问(Unauthorized):" + msg, null)); out.append(data); } catch (IOException e) { logger.error("直接返回Response信息出现IOException异常:{}", e.getMessage()); throw new CustomException("直接返回Response信息出现IOException异常:" + e.getMessage()); } }
Example 14
Source File: JwtFilter.java From ShiroJwt with MIT License | 5 votes |
/** * 此处为AccessToken刷新,进行判断RefreshToken是否过期,未过期就返回新的AccessToken且继续正常访问 */ private boolean refreshToken(ServletRequest request, ServletResponse response) { // 拿到当前Header中Authorization的AccessToken(Shiro中getAuthzHeader方法已经实现) String token = this.getAuthzHeader(request); // 获取当前Token的帐号信息 String account = JwtUtil.getClaim(token, Constant.ACCOUNT); // 判断Redis中RefreshToken是否存在 if (JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account)) { // Redis中RefreshToken还存在,获取RefreshToken的时间戳 String currentTimeMillisRedis = JedisUtil.getObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account).toString(); // 获取当前AccessToken中的时间戳,与RefreshToken的时间戳对比,如果当前时间戳一致,进行AccessToken刷新 if (JwtUtil.getClaim(token, Constant.CURRENT_TIME_MILLIS).equals(currentTimeMillisRedis)) { // 获取当前最新时间戳 String currentTimeMillis = String.valueOf(System.currentTimeMillis()); // 读取配置文件,获取refreshTokenExpireTime属性 PropertiesUtil.readProperties("config.properties"); String refreshTokenExpireTime = PropertiesUtil.getProperty("refreshTokenExpireTime"); // 设置RefreshToken中的时间戳为当前最新时间戳,且刷新过期时间重新为30分钟过期(配置文件可配置refreshTokenExpireTime属性) JedisUtil.setObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account, currentTimeMillis, Integer.parseInt(refreshTokenExpireTime)); // 刷新AccessToken,设置时间戳为当前最新时间戳 token = JwtUtil.sign(account, currentTimeMillis); // 将新刷新的AccessToken再次进行Shiro的登录 JwtToken jwtToken = new JwtToken(token); // 提交给UserRealm进行认证,如果错误他会抛出异常并被捕获,如果没有抛出异常则代表登入成功,返回true this.getSubject(request, response).login(jwtToken); // 最后将刷新的AccessToken存放在Response的Header中的Authorization字段返回 HttpServletResponse httpServletResponse = WebUtils.toHttp(response); httpServletResponse.setHeader("Authorization", token); httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization"); return true; } } return false; }
Example 15
Source File: ApiKeyAuthenticationFilter.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) { final HttpServletRequest http = WebUtils.toHttp(request); for (final Map.Entry<String, ApiKeyExtractor> apiKeyEntry : apiKeys.entrySet()) { final String apiKey = apiKeyEntry.getValue().extract(http); if (null != apiKey) { log.trace("ApiKeyExtractor {} detected presence of API Key", apiKeyEntry.getKey()); request.setAttribute(NX_APIKEY_PRINCIPAL, apiKeyEntry.getKey()); request.setAttribute(NX_APIKEY_TOKEN, apiKey); return true; } } return super.isLoginAttempt(request, response); }
Example 16
Source File: OriginFilter.java From ShiroJwt with MIT License | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = WebUtils.toHttp(request); HttpServletResponse httpServletResponse = WebUtils.toHttp(response); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Max-Age", "3600"); httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); filterChain.doFilter(request, response); }
Example 17
Source File: GunsUserFilter.java From WebStack-Guns with MIT License | 5 votes |
/** * This default implementation simply calls * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse) saveRequestAndRedirectToLogin} * and then immediately returns <code>false</code>, thereby preventing the chain from continuing so the redirect may * execute. */ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = WebUtils.toHttp(request); HttpServletResponse httpServletResponse = WebUtils.toHttp(response); /** * 如果是ajax请求则不进行跳转 */ if (httpServletRequest.getHeader("x-requested-with") != null && httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { httpServletResponse.setHeader("sessionstatus", "timeout"); return false; } else { /** * 第一次点击页面 */ String referer = httpServletRequest.getHeader("Referer"); if (referer == null) { saveRequestAndRedirectToLogin(request, response); return false; } else { /** * 从别的页面跳转过来的 */ if (ShiroKit.getSession().getAttribute("sessionFlag") == null) { httpServletRequest.setAttribute("tips", "session超时"); httpServletRequest.getRequestDispatcher("/login").forward(request, response); return false; } else { saveRequestAndRedirectToLogin(request, response); return false; } } } }
Example 18
Source File: JwtFilter.java From spring-boot-plus with Apache License 2.0 | 5 votes |
/** * 登录成功处理 * * @param token * @param subject * @param request * @param response * @return * @throws Exception */ @Override protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { String url = WebUtils.toHttp(request).getRequestURI(); log.debug("鉴权成功,token:{},url:{}", token, url); // 刷新token JwtToken jwtToken = (JwtToken) token; HttpServletResponse httpServletResponse = WebUtils.toHttp(response); shiroLoginService.refreshToken(jwtToken, httpServletResponse); return true; }
Example 19
Source File: GunsUserFilter.java From MeetingFilm with Apache License 2.0 | 5 votes |
/** * This default implementation simply calls * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse) saveRequestAndRedirectToLogin} * and then immediately returns <code>false</code>, thereby preventing the chain from continuing so the redirect may * execute. */ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = WebUtils.toHttp(request); HttpServletResponse httpServletResponse = WebUtils.toHttp(response); /** * 如果是ajax请求则不进行跳转 */ if (httpServletRequest.getHeader("x-requested-with") != null && httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { httpServletResponse.setHeader("sessionstatus", "timeout"); return false; } else { /** * 第一次点击页面 */ String referer = httpServletRequest.getHeader("Referer"); if (referer == null) { saveRequestAndRedirectToLogin(request, response); return false; } else { /** * 从别的页面跳转过来的 */ if (ShiroKit.getSession().getAttribute("sessionFlag") == null) { httpServletRequest.setAttribute("tips", "session超时"); httpServletRequest.getRequestDispatcher("/login").forward(request, response); return false; } else { saveRequestAndRedirectToLogin(request, response); return false; } } } }
Example 20
Source File: JWTOrFormAuthenticationFilter.java From shiro-jwt with MIT License | 4 votes |
protected String getAuthzHeader(ServletRequest request) { HttpServletRequest httpRequest = WebUtils.toHttp(request); return httpRequest.getHeader(AUTHORIZATION_HEADER); }