当前位置: 首页>>代码示例>>Java>>正文


Java UnauthorizedException类代码示例

本文整理汇总了Java中org.apache.shiro.authz.UnauthorizedException的典型用法代码示例。如果您正苦于以下问题:Java UnauthorizedException类的具体用法?Java UnauthorizedException怎么用?Java UnauthorizedException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


UnauthorizedException类属于org.apache.shiro.authz包,在下文中一共展示了UnauthorizedException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: save

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{projectName}/statuses/{commit}")
   @POST
   public Response save(@PathParam("projectName") String projectName, @PathParam("commit") String commit, 
   		Map<String, String> commitStatus, @Context UriInfo uriInfo) {

	Project project = getProject(projectName);
   	if (!SecurityUtils.canWrite(project))
   		throw new UnauthorizedException();
   	
   	String state = commitStatus.get("state").toUpperCase();
   	if (state.equals("PENDING"))
   		state = "RUNNING";
   	Verification verification = new Verification(Verification.Status.valueOf(state), 
   			new Date(), commitStatus.get("description"), commitStatus.get("target_url"));
   	String context = commitStatus.get("context");
   	if (context == null)
   		context = "default";
   	verificationManager.saveVerification(project, commit, context, verification);
   	UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
   	uriBuilder.path(context);
   	commitStatus.put("id", "1");
   	
   	return Response.created(uriBuilder.build()).entity(commitStatus).type(RestConstants.JSON_UTF8).build();
   }
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:26,代码来源:CommitStatusResource.java

示例2: exceptionHandler

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
/**
 * 统一异常处理
 * @param request
 * @param response
 * @param exception
 */
@ExceptionHandler
public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
	_log.error("统一异常处理:", exception);
	request.setAttribute("ex", exception);
	if (null != request.getHeader("X-Requested-With") && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
		request.setAttribute("requestHeader", "ajax");
	}
	// shiro没有权限异常
	if (exception instanceof UnauthorizedException) {
		return "/403.jsp";
	}
	// shiro会话已过期异常
	if (exception instanceof InvalidSessionException) {
		return "/error.jsp";
	}
	return "/error.jsp";
}
 
开发者ID:youngMen1,项目名称:-Spring-SpringMVC-Mybatis-,代码行数:24,代码来源:BaseController.java

示例3: updatePassword

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
@ApiOperation(value = "修改密码")
@PostMapping(value = "/update/password")
public Object updatePassword(ModelMap modelMap, @RequestBody SysUser param) {
	Assert.isNotBlank(param.getOldPassword(), "OLDPASSWORD");
	Assert.isNotBlank(param.getPassword(), "PASSWORD");
	Long userId = getCurrUser();
	String encryptPassword = SecurityUtil.encryptPassword(param.getOldPassword());
	Parameter parameter = new Parameter(getService(), "queryById").setId(userId);
	logger.info("{} execute queryById start...", parameter.getNo());
	SysUser sysUser = (SysUser) provider.execute(parameter).getModel();
	logger.info("{} execute queryById end.", parameter.getNo());
	Assert.notNull(sysUser, "USER", param.getId());
	if (!sysUser.getPassword().equals(encryptPassword)) {
		throw new UnauthorizedException("原密码错误.");
	}
	param.setPassword(encryptPassword);
	param.setUpdateBy(getCurrUser());
	return super.update(modelMap, param);
}
 
开发者ID:guokezheng,项目名称:automat,代码行数:20,代码来源:SysUserController.java

示例4: updatePassword

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
@ApiOperation(value = "修改密码")
@PostMapping(value = "/update/password")
public Object updatePassword(ModelMap modelMap, @RequestBody SysUser param) {
	Assert.notNull(param.getId(), "USER_ID");
	Assert.isNotBlank(param.getOldPassword(), "OLDPASSWORD");
	Assert.isNotBlank(param.getPassword(), "PASSWORD");
	String encryptPassword = SecurityUtil.encryptPassword(param.getOldPassword());
	SysUser sysUser = ((SysUserService) service).queryById(param.getId());
	Assert.notNull(sysUser, "USER", param.getId());
	Long userId = WebUtil.getCurrentUser();
	if (!param.getId().equals(userId)) {
		SysUser user = ((SysUserService) service).queryById(userId);
		if (user.getUserType() == 1) {
			throw new UnauthorizedException("您没有权限修改用户密码.");
		}
	} else {
		if (!sysUser.getPassword().equals(encryptPassword)) {
			throw new UnauthorizedException("原密码错误.");
		}
	}
	param.setPassword(encryptPassword);
	param.setUpdateBy(WebUtil.getCurrentUser());
	return super.update(modelMap, param);
}
 
开发者ID:tb544731152,项目名称:iBase4J,代码行数:25,代码来源:SysUserController.java

示例5: get

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
@Path("/{name}")
 @GET
 public Response get(@PathParam("name") String name) {
 	Project project = projectManager.find(name);
 	
 	if (!SecurityUtils.canRead(project)) {
throw new UnauthorizedException("Unauthorized access to project " + project.getName());
 	} else {
 		Map<String, Object> entity = new HashMap<>();
 		Map<String, String> permissionsMap = new HashMap<>();
 		entity.put("name", project.getName());
 		permissionsMap.put("admin", String.valueOf(SecurityUtils.canManage(project)));
 		permissionsMap.put("push", String.valueOf(SecurityUtils.canWrite(project)));
 		permissionsMap.put("pull", "true");
 		entity.put("permissions", permissionsMap);
 		
 		Map<String, String> ownerMap = new HashMap<>();
 		ownerMap.put("login", "projects");
 		ownerMap.put("id", "1000000");
 		
 		entity.put("owner", ownerMap);
 		
 		return Response.ok(entity, RestConstants.JSON_UTF8).build();
 	}
 }
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:26,代码来源:RepositoryResource.java

示例6: processRefs

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
protected void processRefs(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String pathInfo = request.getRequestURI().substring(request.getContextPath().length());
	pathInfo = StringUtils.stripStart(pathInfo, "/");

	String projectInfo = pathInfo.substring(0, pathInfo.length() - INFO_REFS.length());
	ProjectFacade project = getProject(request, response, projectInfo);
	String service = request.getParameter("service");
	
	File gitDir = storageManager.getProjectGitDir(project.getId());

	if (service.contains("upload")) {
		if (!SecurityUtils.canRead(project)) 
			throw new UnauthorizedException("You do not have permission to pull from this project.");
		writeInitial(response, service);
		new AdvertiseUploadRefsCommand(gitDir).output(response.getOutputStream()).call();
	} else {
		if (!SecurityUtils.canWrite(project)) {
			throw new UnauthorizedException("You do not have permission to push to this project.");
		}
		writeInitial(response, service);
		new AdvertiseReceiveRefsCommand(gitDir).output(response.getOutputStream()).call();
	}
}
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:24,代码来源:GitFilter.java

示例7: exceptionHandler

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
/**
 * 统一异常处理
 * @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";
}
 
开发者ID:ChangyiHuang,项目名称:shuzheng,代码行数:24,代码来源:BaseController.java

示例8: checkPermissions

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
/**
 * Checks if the subject permissions grant all the required permissions.
 * <p>
 * The first collection contains the set of permissions held by the subject.
 * The second collection contains the permissions that are required.
 * This returns true if the set of subject permissions grants all the required permissions.
 * 
 * @param subjectPermissions  the set of permissions held by the subject, not null
 * @param requiredPermissions  the permissions that are required, not null
 * @throws UnauthenticatedException if permission was denied due to invalid user authentication
 * @throws UnauthorizedException if the user does not have the requested permission
 * @throws AuthorizationException if permission was denied due to some other issue
 */
public void checkPermissions(Collection<Permission> subjectPermissions, Collection<Permission> requiredPermissions) {
  // try bulk check
  for (Permission subjectPermission : subjectPermissions) {
    if (subjectPermission instanceof ExtendedPermission) {
      ExtendedPermission subjectPerm = (ExtendedPermission) subjectPermission;
      Boolean implied = subjectPerm.checkImpliesAll(requiredPermissions, true);
      if (implied != null) {
        if (implied) {
          return;
        }
        throw new UnauthorizedException("Permission denied: " + requiredPermissions);
      }
    }
  }
  // normal non-bulk check
  for (Permission requiredPermission : requiredPermissions) {
    checkImplies(subjectPermissions, requiredPermission);
  }
}
 
开发者ID:DevStreet,项目名称:FinanceAnalytics,代码行数:33,代码来源:ShiroPermissionResolver.java

示例9: hide

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
/**
 * Mark one symbol as hidden.
 *
 * @param projectId The ID of the project.
 * @param id        The ID of the symbol to hide.
 * @return On success no content will be returned; an error message on failure.
 * @throws NotFoundException If the requested Symbol or the related Project or Group could not be found.
 * @successResponse 204 OK & no content
 * @errorResponse   404 not found `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError
 */
@POST
@Path("/{id}/hide")
@Produces(MediaType.APPLICATION_JSON)
public Response hide(@PathParam("project_id") Long projectId, @PathParam("id") Long id) throws NotFoundException {
    User user = ((UserPrincipal) securityContext.getUserPrincipal()).getUser();
    LOGGER.traceEntry("hide({}, {}) for user {}.", projectId, id, user);

    try {
        symbolDAO.hide(user, projectId, Collections.singletonList(id));
        Symbol symbol = symbolDAO.get(user, projectId, id);

        LOGGER.traceExit(symbol);
        return Response.ok(symbol).build();
    } catch (UnauthorizedException e) {
        LOGGER.traceExit(e);
        return ResourceErrorHandler.createRESTErrorMessage("SymbolResource.hide", Status.UNAUTHORIZED, e);
    }
}
 
开发者ID:LearnLib,项目名称:alex,代码行数:29,代码来源:SymbolResource.java

示例10: delete

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
/**
 * Delete a specific project.
 *
 * @param projectId
 *            The ID of the project.
 * @return On success no content will be returned; an error message on failure.
 * @throws NotFoundException If the given Project could not be found.
 * @successResponse 204 OK & no content
 * @errorResponse   404 not found `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError
 */
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") long projectId) throws NotFoundException {
    User user = ((UserPrincipal) securityContext.getUserPrincipal()).getUser();
    LOGGER.traceEntry("delete({}) for user {}.", projectId, user);

    try {
        Project project = projectDAO.getByID(user.getId(), projectId);

        if ((project.getUser() != null && !user.equals(project.getUser()))
                || (project.getUser().getId() != 0 && !Objects.equals(project.getUser().getId(), user.getId()))) {
            throw new UnauthorizedException("You are not allowed to delete this project");
        }

        project.setUser(user);
        projectDAO.delete(user, projectId);
        LOGGER.traceExit("Project {} deleted", projectId);
        return Response.status(Status.NO_CONTENT).build();
    } catch (UnauthorizedException e) {
        LOGGER.traceExit(e);
        return ResourceErrorHandler.createRESTErrorMessage("ProjectResource.delete", Status.UNAUTHORIZED, e);
    }
}
 
开发者ID:LearnLib,项目名称:alex,代码行数:35,代码来源:ProjectResource.java

示例11: delete

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
/**
 * Delete an user.
 * This is only allowed for your own account or if you are an administrator.
 *
 * @param userId
 *         The ID of the user to delete.
 * @return Nothing if the user was deleted.
 * @throws NotFoundException If the given User could not be found.
 *
 * @successResponse 204 No Content
 * @errorResponse 400 bad request `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError
 * @errorResponse 404 not found   `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError
 */
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({"REGISTERED"})
public Response delete(@PathParam("id") long userId) throws NotFoundException {
    User user = ((UserPrincipal) securityContext.getUserPrincipal()).getUser();
    LOGGER.traceEntry("delete({}) for user {}.", userId, user);

    if (!user.getId().equals(userId) && !user.getRole().equals(UserRole.ADMIN)) {
        UnauthorizedException e = new UnauthorizedException("You are not allowed to delete this user");
        LOGGER.traceExit(e);
        return ResourceErrorHandler.createRESTErrorMessage("UserResource.delete", Status.FORBIDDEN, e);
    }

    userDAO.delete(userId);

    LOGGER.traceExit("User {} deleted.", userId);
    return Response.status(Status.NO_CONTENT).build();
}
 
开发者ID:LearnLib,项目名称:alex,代码行数:33,代码来源:UserResource.java

示例12: toResponse

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
@Override
public Response toResponse(ShiroException exception) {

    Response.Status status;

    if (exception instanceof UnauthorizedException) {
        status = Response.Status.UNAUTHORIZED;
    } else {
        status = Response.Status.FORBIDDEN;
    }
    ErrorMessage error = ErrorMessage.fromStatus(status.getStatusCode());
    error.setCode(Hashing.murmur3_32().hashUnencodedChars(exception.getClass().getName()).toString());

    return Response.status(status)
            .type(ExceptionMapperUtils.getResponseType())
            .entity(error)
            .build();
}
 
开发者ID:icode,项目名称:ameba-shiro,代码行数:19,代码来源:ShiroExceptionMapper.java

示例13: filter

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
public void filter(ContainerRequestContext requestContext) throws IOException {
    if ((uris.size() == 0 || FilterUtil.isMatchUri(uris)) && !FilterUtil.isMatchUri(ignoreUris)) {
        Subject subject = subjectProvider.get();
        if (subject == null || (!subject.isAuthenticated() && !subject.isRemembered())) {
            if (FilterUtil.isVisitPage(requestContext)) {
                StringBuilder login = new StringBuilder(loginUrl);
                if (!"disabled".equalsIgnoreCase(callbackParam)) {
                    login.append("?")
                            .append(callbackParam)
                            .append("=")
                            .append(
                                    URLEncoder.encode(
                                            uriInfoProvider.get().getRequestUri().toString(),
                                            Charsets.UTF_8.name()
                                    )
                            );
                }
                URI loginUri = URI.create(login.toString());
                requestContext.abortWith(Response.temporaryRedirect(loginUri).build());
            } else {
                throw new UnauthorizedException();
            }
        }
    }
}
 
开发者ID:icode,项目名称:ameba-shiro,代码行数:26,代码来源:UserFilter.java

示例14: delete

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
/**
 * add calendar event
 * 
 * @param calendarId
 * @param date
 *            -- a string representation of the requested datetime for the
 *            event
 * @param servletRequest
 * @param servletResponse
 * @return
 * @throws IOException
 * @throws ServletException
 * @throws JSONException
 * @throws ParseException
 */
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public String delete(@PathParam("eventId") Integer eventId,
		@Context HttpServletRequest servletRequest,
		@Context HttpServletResponse servletResponse) throws IOException,
		ServletException, JSONException, ParseException {

	SqlSession session = (SqlSession) servletRequest
			.getAttribute(SESSION_VAR_SQLSESSION);
	User ux = (User) servletRequest.getAttribute(SESSION_VAR_USER);
	if (ux == null || ux.getId() == SystemConstants.ANON_USERID) {
		throw new UnauthorizedException(
				"Anonymous Event Creation Prohibited");
	}
	session.insert("io.starter.dao.CalendarEventMapper.delete", eventId);
	session.commit();
	return "{delete:'ok'}";
}
 
开发者ID:StarterInc,项目名称:Ignite,代码行数:34,代码来源:CalendarEventData.java

示例15: getKeys

import org.apache.shiro.authz.UnauthorizedException; //导入依赖的package包/类
@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();
}
 
开发者ID:apache,项目名称:usergrid,代码行数:24,代码来源:ApplicationResource.java


注:本文中的org.apache.shiro.authz.UnauthorizedException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。