org.apache.shiro.authz.UnauthorizedException Java Examples
The following examples show how to use
org.apache.shiro.authz.UnauthorizedException.
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: UserResource.java From onedev with MIT License | 7 votes |
@ValidQueryParams @GET public Response query(@QueryParam("name") String name, @Email @QueryParam("email") String email, @QueryParam("offset") Integer offset, @QueryParam("count") Integer count, @Context UriInfo uriInfo) { if (!SecurityUtils.isAdministrator()) throw new UnauthorizedException("Unauthorized access to user profiles"); EntityCriteria<User> criteria = EntityCriteria.of(User.class); if (name != null) criteria.add(Restrictions.eq("name", name)); if (email != null) criteria.add(Restrictions.eq("email", email)); if (offset == null) offset = 0; if (count == null || count > RestConstants.PAGE_SIZE) count = RestConstants.PAGE_SIZE; Collection<User> users = userManager.query(criteria, offset, count); return Response.ok(users, RestConstants.JSON_UTF8).build(); }
Example #2
Source File: ExceptionUtils.java From onedev with MIT License | 6 votes |
public static void handle(HttpServletResponse response, Exception exception) { try { if (ExceptionUtils.find(exception, UnauthenticatedException.class) != null) { requireAuthentication(response); } else if (find(exception, UnauthorizedException.class) != null) { if (!SecurityUtils.getSubject().isAuthenticated()) requireAuthentication(response); else response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied."); } else if (find(exception, IncorrectCredentialsException.class) != null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Incorrect credentials."); } else if (find(exception, UnknownAccountException.class) != null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unknown user name."); } else { logger.warn("Error serving request", exception); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage()); } } catch (IOException e) { throw new RuntimeException(e); } }
Example #3
Source File: GlobalExceptionHandler.java From mysiteforme with Apache License 2.0 | 6 votes |
@ExceptionHandler(UnauthorizedException.class) public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, UnauthorizedException unauthorizedException) { if (ToolUtil.isAjax(request)) { try { response.setContentType("application/json;charset=UTF-8"); PrintWriter writer = response.getWriter(); RestResponse failResponse = RestResponse.failure("您无此权限,请联系管理员!"); writer.write(JSONObject.toJSONString(failResponse)); writer.flush(); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } }else { RestResponse restResponse = RestResponse.failure(unauthorizedException.getMessage()); return new ModelAndView("admin/error/500",restResponse); } return null; }
Example #4
Source File: JWTFilter.java From SpringAll with MIT License | 6 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; SystemProperties properties = SpringContextUtil.getBean(SystemProperties.class); String[] anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ","); boolean match = false; for (String u : anonUrl) { if (pathMatcher.match(u, httpServletRequest.getRequestURI())) match = true; } if (match) return true; if (isLoginAttempt(request, response)) { return executeLogin(request, response); } return false; }
Example #5
Source File: PermissionList.java From es with Apache License 2.0 | 6 votes |
public void assertHasAllPermission(String[] permissions, String errorCode) { if (StringUtils.isEmpty(errorCode)) { errorCode = getDefaultErrorCode(); } if (permissions == null || permissions.length == 0) { throw new UnauthorizedException(MessageUtils.message(errorCode, resourceIdentity + ":" + Arrays.toString(permissions))); } Subject subject = SecurityUtils.getSubject(); for (String permission : permissions) { String resourcePermission = resourcePermissions.get(permission); if (resourcePermission == null) { resourcePermission = this.resourceIdentity + ":" + permission; } if (!subject.isPermitted(resourcePermission)) { throw new UnauthorizedException(MessageUtils.message(errorCode, resourceIdentity + ":" + Arrays.toString(permissions))); } } }
Example #6
Source File: MyExceptionHandler.java From easyweb-shiro with MIT License | 6 votes |
@ResponseBody @ExceptionHandler(Exception.class) public Map<String, Object> errorHandler(Exception ex) { Map<String, Object> map = new HashMap<>(); // 根据不同错误获取错误信息 if (ex instanceof IException) { map.put("code", ((IException) ex).getCode()); map.put("msg", ex.getMessage()); } else if (ex instanceof UnauthorizedException) { map.put("code", 403); map.put("msg", "没有访问权限"); } else { String message = ex.getMessage(); map.put("code", 500); //map.put("msg", "系统繁忙"); // 开发阶段建议错误信息直接放在msg中,生产版本建议把错误信息放在details中,msg提示系统繁忙即可 map.put("msg", message == null || message.trim().isEmpty() ? "系统繁忙" : message); map.put("details", message); logger.error(ex.getMessage(), ex); ex.printStackTrace(); } return map; }
Example #7
Source File: LoginController.java From SpringBootBucket with MIT License | 6 votes |
@PostMapping("/login") public BaseResponse<String> login(@RequestHeader(name="Content-Type", defaultValue = "application/json") String contentType, @RequestBody LoginParam loginParam) { _logger.info("用户请求登录获取Token"); String username = loginParam.getUsername(); String password = loginParam.getPassword(); ManagerInfo user = managerInfoService.findByUsername(username); //随机数盐 String salt = user.getSalt(); //原密码加密(通过username + salt作为盐) String encodedPassword = ShiroKit.md5(password, username + salt); if (user.getPassword().equals(encodedPassword)) { return new BaseResponse<>(true, "Login success", JWTUtil.sign(username, encodedPassword)); } else { throw new UnauthorizedException(); } }
Example #8
Source File: ProjectResource.java From onedev with MIT License | 6 votes |
@ValidQueryParams @GET public Response query(@QueryParam("name") String projectName, @QueryParam("offset") Integer offset, @QueryParam("count") Integer count, @Context UriInfo uriInfo) { EntityCriteria<Project> criteria = projectManager.newCriteria(); if (projectName != null) criteria.add(Restrictions.eq("name", projectName)); if (offset == null) offset = 0; if (count == null || count > RestConstants.PAGE_SIZE) count = RestConstants.PAGE_SIZE; Collection<Project> projects = projectManager.query(criteria, offset, count); for (Project project: projects) { if (!SecurityUtils.canAccess(project)) throw new UnauthorizedException("Unable to access project '" + project.getName() + "'"); } return Response.ok(projects, RestConstants.JSON_UTF8).build(); }
Example #9
Source File: BaseController.java From zheng with MIT License | 6 votes |
/** * 统一异常处理 * @param request * @param response * @param exception */ @ExceptionHandler public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) { LOGGER.error("统一异常处理:", exception); request.setAttribute("ex", exception); if (null != request.getHeader("X-Requested-With") && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) { request.setAttribute("requestHeader", "ajax"); } // shiro没有权限异常 if (exception instanceof UnauthorizedException) { return "/403.jsp"; } // shiro会话已过期异常 if (exception instanceof InvalidSessionException) { return "/error.jsp"; } return "/error.jsp"; }
Example #10
Source File: ExceptionResponse.java From es with Apache License 2.0 | 6 votes |
private static String convertMessage(Throwable e) { String errorMessage = e.getMessage(); //验证失败 if (e instanceof UnauthorizedException) { if (errorMessage.startsWith("Subject does not have permission")) { errorMessage = errorMessage.replaceAll("Subject does not have permission", "您没有操作权限,请联系管理员添加权限"); } if (errorMessage.startsWith("User is not permitted")) { errorMessage = errorMessage.replaceAll("User is not permitted", "您没有操作权限,请联系管理员添加权限"); } if (errorMessage.startsWith("Subject does not have role")) { errorMessage = errorMessage.replaceAll("Subject does not have role", "您没有操作权限,请联系管理员添加角色"); } } return errorMessage; }
Example #11
Source File: DefaultExceptionHandler.java From White-Jotter with MIT License | 6 votes |
@ExceptionHandler(value = Exception.class) public Result exceptionHandler(Exception e) { String message = null; if (e instanceof IllegalArgumentException) { message = "传入了错误的参数"; } if (e instanceof MethodArgumentNotValidException) { message = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage(); } if (e instanceof UnauthorizedException) { message = "权限认证失败"; } return ResultFactory.buildFailResult(message); }
Example #12
Source File: IamErrorConfiguring.java From super-cloudops with Apache License 2.0 | 6 votes |
@Override public Integer getStatus(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model, Exception ex) { // IAM Unauthenticated? if ((ex instanceof UnauthenticatedException) || (ex instanceof com.wl4g.devops.common.exception.iam.UnauthenticatedException)) { return UNAUTHC.getErrcode(); } // IAM Unauthorized? else if ((ex instanceof UnauthorizedException) || (ex instanceof com.wl4g.devops.common.exception.iam.UnauthorizedException)) { return UNAUTHZ.getErrcode(); } // see: IamSecurityHolder else if (ex instanceof UnknownSessionException) { return PARAM_ERR.getErrcode(); } // Using next chain configuring. return null; }
Example #13
Source File: PermissionsAuthorizationFilter.java From frpMgr with MIT License | 6 votes |
/** * 无访问权限时,跳转到403页面 * @param request * @param response * @return * @throws IOException * @author ThinkGem */ public static boolean redirectTo403Page(ServletRequest request, ServletResponse response) throws IOException { Subject subject = SecurityUtils.getSubject(); // If the subject isn't identified, redirect to login URL if (subject.getPrincipal() == null) { redirectToDefaultPath(request, response); } else { try { // 如果访问的是未授权页面,则直接转到403页面(2016-11-3) request.getRequestDispatcher("/error/403").forward(request, response); } catch (ServletException e) { throw new UnauthorizedException(e); } } return false; }
Example #14
Source File: JwtFilter.java From Moss with Apache License 2.0 | 6 votes |
/** * 如果带有 token,则对 token 进行检查,否则直接通过 */ @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException { //判断请求的请求头是否带上 "Token" if (isLoginAttempt(request, response)) { //如果存在,则进入 executeLogin 方法执行登入,检查 token 是否正确 try { executeLogin(request, response); return true; } catch (Exception e) { //token 错误 onAccessFailure(response, e); } } //如果请求头不存在 Token,则可能是执行登陆操作或者是游客状态访问,无需检查 token,直接返回 true return true; }
Example #15
Source File: JWTFilter.java From permission with MIT License | 6 votes |
/** * 执行登录认证 * * @param request * @param response * @param mappedValue * @return */ @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String anonUrl = SpringContextUtil.getBean(PermissionProperties.class).getAnonUrl(); String[] anonUrls = anonUrl.split(StringPool.COMMA); boolean match = false; for (String u : anonUrls) { if (pathMatcher.match(u, httpServletRequest.getRequestURI())) match = true; } if (match) { return true; } if (isLoginAttempt(request, response)) { return executeLogin(request, response); } return false; }
Example #16
Source File: ApplicationResource.java From usergrid with Apache License 2.0 | 6 votes |
@GET @Path("credentials") @RequireApplicationAccess @JSONP @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public ApiResponse getKeys( @Context UriInfo ui, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { if (logger.isTraceEnabled()) { logger.trace("AuthResource.keys"); } if ( !isApplicationAdmin( Identifier.fromUUID( applicationId ) ) ) { throw new UnauthorizedException(); } ClientCredentialsInfo kp = new ClientCredentialsInfo( management.getClientIdForApplication( services.getApplicationId() ), management.getClientSecretForApplication( services.getApplicationId() ) ); return createApiResponse().withCredentials( kp ).withAction( "get application keys" ).withSuccess(); }
Example #17
Source File: PermissionList.java From es with Apache License 2.0 | 6 votes |
public void assertHasAnyPermission(String[] permissions, String errorCode) { if (StringUtils.isEmpty(errorCode)) { errorCode = getDefaultErrorCode(); } if (permissions == null || permissions.length == 0) { throw new UnauthorizedException(MessageUtils.message(errorCode, resourceIdentity + ":" + Arrays.toString(permissions))); } Subject subject = SecurityUtils.getSubject(); for (String permission : permissions) { String resourcePermission = resourcePermissions.get(permission); if (resourcePermission == null) { resourcePermission = this.resourceIdentity + ":" + permission; } if (subject.isPermitted(resourcePermission)) { return; } } throw new UnauthorizedException(MessageUtils.message(errorCode, resourceIdentity + ":" + Arrays.toString(permissions))); }
Example #18
Source File: AntiCsrfHelper.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
/** * Validate that the token passed as an argument matches the cookie in the request (if the request requires * validation) * * @throws UnauthorizedException when the provided token is missing or does not match the request */ public void requireValidToken(final HttpServletRequest httpRequest, @Nullable final String token) { Optional<String> optToken = token == null ? Optional.ofNullable(httpRequest.getHeader(ANTI_CSRF_TOKEN_NAME)) : Optional.of(token); if (!enabled || isNotBrowserRequest(httpRequest) || isAntiCsrfTokenValid(httpRequest, optToken)) { return; } throw new UnauthorizedException(ERROR_MESSAGE_TOKEN_MISMATCH); }
Example #19
Source File: TestWebController.java From jeecg-boot with Apache License 2.0 | 5 votes |
@PostMapping("/login") public ResponseBean login(@RequestParam("username") String username, @RequestParam("password") String password) { SysUser user = userService.getUserByName(username); if(user==null) { return new ResponseBean(200, "用户不存在!", JwtUtil.sign(username, user.getPassword())); } String passwordEncode = PasswordUtil.encrypt(username, password, user.getSalt()); if (passwordEncode.equals(user.getPassword())) { return new ResponseBean(200, "Login success", JwtUtil.sign(username, user.getPassword())); } else { throw new UnauthorizedException(); } }
Example #20
Source File: ShiroExceptionMapper.java From shiro-jersey with Apache License 2.0 | 5 votes |
@Override public Response toResponse(AuthorizationException exception) { Status status; if (exception instanceof UnauthorizedException) { status = Status.FORBIDDEN; } else { status = Status.UNAUTHORIZED; } return Response.status(status).build(); }
Example #21
Source File: OrganizationResource.java From usergrid with Apache License 2.0 | 5 votes |
private ApplicationResource appResourceFor( UUID applicationId ) throws Exception { if ( applicationId.equals( emf.getManagementAppId() ) && !SubjectUtils.isServiceAdmin() ) { throw new UnauthorizedException(); } return getSubResource( ApplicationResource.class ).init( applicationId ); }
Example #22
Source File: AntiCsrfHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test(expected = UnauthorizedException.class) public void testRequireValidToken_tokenMismatch() { when(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(BROWSER_UA); when(httpServletRequest.getCookies()) .thenReturn(new Cookie[] { new Cookie(AntiCsrfHelper.ANTI_CSRF_TOKEN_NAME, "a-value") }); underTest.requireValidToken(httpServletRequest, "a-different-value"); }
Example #23
Source File: CustomExceptionAdvice.java From EasyReport with Apache License 2.0 | 5 votes |
/** * 401 - Unauthorized */ @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(UnauthorizedException.class) public ResponseResult handleUnauthorizedException(final UnauthorizedException e) { log.error("没有权限", e); return ResponseResult.failure(401, "对不起!您没有权限,访问拒绝", e.toString()); }
Example #24
Source File: DefaultExceptionHandler.java From mumu with Apache License 2.0 | 5 votes |
/** * 没有权限 异常 * <p/> * 后续根据不同的需求定制即可 */ @ExceptionHandler({UnauthorizedException.class}) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e); mv.setViewName("unauthorized"); return mv; }
Example #25
Source File: AdviceController.java From seezoon-framework-all with Apache License 2.0 | 5 votes |
/** * 未授权,权限不足 * * @throws IOException */ @ResponseBody @ExceptionHandler(UnauthorizedException.class) public ResponeModel exceptionHandler(HttpServletResponse response) { response.setStatus(HttpStatus.NEED_PERMISSION.getValue()); return ResponeModel.error(ExceptionCode.PERMISSION_DENIED, "权限不足,请联系管理员"); }
Example #26
Source File: MyExceptionResolver.java From SpringBootBucket with MIT License | 5 votes |
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //如果是shiro无权操作,因为shiro 在操作auno等一部分不进行转发至无权限url if (ex instanceof UnauthorizedException) { return new ModelAndView("error/shiro_403"); } return null; }
Example #27
Source File: UserService.java From Shiro-Action with MIT License | 5 votes |
@Transactional public void delete(Integer userId) { // 检查删除的是否是超级管理员, 如果是, 则不允许删除. User user = userMapper.selectByPrimaryKey(userId); if (shiroActionProperties.getSuperAdminUsername().equals(user.getUsername())) { throw new UnauthorizedException("试图删除超级管理员, 被禁止."); } userAuthsService.deleteByUserId(userId); userMapper.deleteByPrimaryKey(userId); userRoleMapper.deleteUserRoleByUserId(userId); }
Example #28
Source File: MyException.java From DouBiNovel with Apache License 2.0 | 5 votes |
@ExceptionHandler(value = Exception.class) public Object defaultErrorHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws Exception { String msg = "未知错误"; if (!StringUtils.isBlank(e.getMessage())) { msg = e.getMessage(); } if (!isAjax(req)) { ModelAndView modelAndView = new ModelAndView(); if (e instanceof UnauthorizedException) { modelAndView.addObject("msg", "无访问权限"); modelAndView.setViewName("public/403"); } else { modelAndView.addObject("msg", msg); modelAndView.setViewName("public/error"); } modelAndView.addObject("systemInfo", systemSettingService.getSetting()); return modelAndView; } else { MvcResult result = null; if (e instanceof UnauthorizedException) { result = MvcResult.createFail(403, "无访问权限"); } else { result = MvcResult.createFail(500, msg); } return result; } }
Example #29
Source File: WebExceptionHandler.java From Shiro-Action with MIT License | 5 votes |
@ExceptionHandler(value = {UnauthorizedException.class}) public String unauthorized(Exception e) { if (log.isDebugEnabled()) { log.debug("无权限"); } return generateErrorInfo(ResultBean.FAIL, "无权限"); }
Example #30
Source File: JwtFilter.java From notes with Apache License 2.0 | 5 votes |
/** * 这里我们详细说明下为什么最终返回的都是true,即允许访问 * 例如我们提供一个地址 GET /article * 登入用户和游客看到的内容是不同的 * 如果在这里返回了false,请求会被直接拦截,用户看不到任何东西 * 所以我们在这里返回true,Controller中可以通过 subject.isAuthenticated() 来判断用户是否登入 * 如果有些资源只有登入用户才能访问,我们只需要在方法上面加上 @RequiresAuthentication 注解即可 * 但是这样做有一个缺点,就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法),但实际上对应用影响不大 */ @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { if (isLoginAttempt(request, response)) { try { executeLogin(request, response); } catch (Exception e) { throw new UnauthorizedException(); } } // if(null !=getSubject(request,response) && getSubject(request,response).isAuthenticated()){ // return true; // } return false; }