當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。