org.apache.shiro.authz.AuthorizationException Java Examples

The following examples show how to use org.apache.shiro.authz.AuthorizationException. 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: usergrid   Author: apache   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 #2
Source Project: NutzSite   Author: TomYule   File: SimpleAuthorizingRealm.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	// null usernames are invalid
	if (principals == null) {
		throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
	}
	User user = (User) principals.getPrimaryPrincipal();
	if (user == null) {
		return null;
	}
	// 角色列表
	Set<String> roles =userService.getRoleCodeList(user.getId());
	// 功能列表
	Set<String> menus = userService.getPermsByUserId(user.getId());

	SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
	auth.setRoles(roles);
	auth.setStringPermissions(menus);
	return auth;
}
 
Example #3
Source Project: gazpachoquest   Author: antoniomaria   File: JPARealm.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // null usernames are invalid
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }
    User user = (User) getAvailablePrincipal(principals);

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    Set<Role> roles = userService.getRoles(user.getId());
    for (Role role : roles) {
        info.addRole(role.getName());
    }
    Set<Permission<?>> permissions = userService.getPermissions(user.getId());

    for (Permission<?> permission : permissions) {
        info.addStringPermission(permission.getLiteral());
    }
    return info;
}
 
Example #4
Source Project: gazpachoquest   Author: antoniomaria   File: ShiroExceptionHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Response toResponse(ShiroException exception) {

    Status status = Status.FORBIDDEN; // Invalid api key
    if (exception instanceof AccountException) {
        // API key missing
        status = Status.BAD_REQUEST;
        logger.warn(exception.getMessage());
    } else if (exception instanceof AuthorizationException) {
        // Not enough permissions
        status = Status.UNAUTHORIZED;
        logger.warn(exception.getMessage());
    } else {
        logger.error(exception.getMessage(), exception);
    }
    return Response.status(status).type(MediaType.APPLICATION_JSON)
            .entity(ErrorEntity.with().message(exception.getMessage()).build()).build();
}
 
Example #5
Source Project: layui-admin   Author: gameloft9   File: ShiroRealm.java    License: MIT License 6 votes vote down vote up
/**
 * 获取授权信息方法,返回用户角色信息
 * */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
		PrincipalCollection principals) {
	if (principals == null) {
		throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
	}

	UserTest user = (UserTest) principals.getPrimaryPrincipal();
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	if (user != null) {//获取用户角色信息
		List<String> roles = userServiceImpl.getRoleNames(user.getId());
		info.addRoles(roles);
	} else {
		SecurityUtils.getSubject().logout();
	}
	return info;
}
 
Example #6
Source Project: airpal   Author: airbnb   File: AllowAllRealm.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
{
    Set<String> roles = Sets.newHashSet("user");
    Set<Permission> permissions = Sets.newHashSet();
    Collection<AllowAllUser> principalsCollection = principals.byType(AllowAllUser.class);

    if (principalsCollection.isEmpty()) {
        throw new AuthorizationException("No principals!");
    }

    for (AllowAllUser user : principalsCollection) {
        for (UserGroup userGroup : groups) {
            if (userGroup.representedByGroupStrings(user.getGroups())) {
                permissions.addAll(userGroup.getPermissions());
                break;
            }
        }
    }

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(roles);
    authorizationInfo.setObjectPermissions(permissions);

    return authorizationInfo;
}
 
Example #7
Source Project: shiro-jwt   Author: panchitoboy   File: ShiroInterceptor.java    License: MIT License 6 votes vote down vote up
@AroundInvoke
public Object around(final InvocationContext ic) throws Exception {
    try {
        assertAuthorized(new InvocationContextToMethodInvocationConverter(ic));
    } catch (AuthorizationException exception) {
        Method m = ic.getMethod();
        String message = m.getAnnotation(SecurityChecked.class).message();

        if ("".equals(message)) {
            throw exception;
        } else {
            throw new ShiroException(message, exception);
        }

    }
    return ic.proceed();
}
 
Example #8
Source Project: dts-shop   Author: qiguliuxing   File: AdminAuthorizingRealm.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	if (principals == null) {
		throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
	}

	DtsAdmin admin = (DtsAdmin) getAvailablePrincipal(principals);
	Integer[] roleIds = admin.getRoleIds();
	Set<String> roles = roleService.queryByIds(roleIds);
	Set<String> permissions = permissionService.queryByRoleIds(roleIds);
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	info.setRoles(roles);
	info.setStringPermissions(permissions);
	return info;
}
 
Example #9
Source Project: shiro-jersey   Author: silb   File: ShiroExceptionMapper.java    License: Apache License 2.0 5 votes vote down vote up
@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 #10
Source Project: ZTuoExchange_framework   Author: sengeiou   File: AdminMyControllerAdvice.java    License: MIT License 5 votes vote down vote up
/**
 * 拦截捕捉无权限异常
 *
 * @param ex
 * @return
 */
@ResponseBody
@ExceptionHandler(value = AuthorizationException.class)
public MessageResult handleAuthorizationError(AuthorizationException ex) {
    ex.printStackTrace();
    MessageResult result = MessageResult.error(5000, "unauthorized");
    return result;
}
 
Example #11
Source Project: ZTuoExchange_framework   Author: sengeiou   File: AdminMyControllerAdvice.java    License: MIT License 5 votes vote down vote up
@ResponseBody
@ExceptionHandler({AuthenticationException.class,UnauthenticatedException.class})
public MessageResult handleAuthenticationError(AuthorizationException ex) {
    ex.printStackTrace();
    MessageResult result = MessageResult.error(4000, "please login");
    return result;
}
 
Example #12
Source Project: ruoyiplus   Author: kongshanxuelin   File: DefaultExceptionHandler.java    License: MIT License 5 votes vote down vote up
/**
 * 权限校验失败
 */
@ExceptionHandler(AuthorizationException.class)
public AjaxResult handleAuthorizationException(AuthorizationException e)
{
    log.error(e.getMessage(), e);
    return AjaxResult.error(PermissionUtils.getMsg(e.getMessage()));
}
 
Example #13
Source Project: ZTuoExchange_framework   Author: homeyanmi   File: AdminRealm.java    License: MIT License 5 votes vote down vote up
/**
 * 授权
 *
 * @param principals
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String currentUsername = (String) getAvailablePrincipal(principals);
    log.info("doGetAuthorizationInfo,user:" + currentUsername);
    List<String> permissionList = new ArrayList<>();
    Admin admin = (Admin) getSession(SysConstant.SESSION_ADMIN);
    if (null == admin) {
        throw new AuthorizationException();
    }
    try {
        List<SysPermission> list;
        if ("root".equalsIgnoreCase(admin.getUsername())) {
            list = sysPermissionService.findAll();
        } else {
            SysRole sysRole = sysRoleService.findOne(admin.getRoleId());
            list = sysRole.getPermissions();
        }
        //获取当前用户权限列表
        list.forEach(x -> {
            if (!StringUtils.isEmpty(x.getName())) {
                permissionList.add(x.getName());
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthorizationException();
    }
    log.info("permission list {}", permissionList);
    SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
    simpleAuthorInfo.addStringPermissions(permissionList);
    return simpleAuthorInfo;
}
 
Example #14
Source Project: ZTuoExchange_framework   Author: homeyanmi   File: AdminMyControllerAdvice.java    License: MIT License 5 votes vote down vote up
/**
 * 拦截捕捉无权限异常
 *
 * @param ex
 * @return
 */
@ResponseBody
@ExceptionHandler(value = AuthorizationException.class)
public MessageResult handleAuthorizationError(AuthorizationException ex) {
    ex.printStackTrace();
    MessageResult result = MessageResult.error(5000, "unauthorized");
    return result;
}
 
Example #15
Source Project: ZTuoExchange_framework   Author: homeyanmi   File: AdminMyControllerAdvice.java    License: MIT License 5 votes vote down vote up
@ResponseBody
@ExceptionHandler({AuthenticationException.class,UnauthenticatedException.class})
public MessageResult handleAuthenticationError(AuthorizationException ex) {
    ex.printStackTrace();
    MessageResult result = MessageResult.error(4000, "please login");
    return result;
}
 
Example #16
Source Project: shiro-jersey   Author: silb   File: AuthorizationFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    try {
        for (Map.Entry<AuthorizingAnnotationHandler, Annotation> authzCheck : authzChecks.entrySet()) {
            AuthorizingAnnotationHandler handler = authzCheck.getKey();
            Annotation authzSpec = authzCheck.getValue();
            handler.assertAuthorized(authzSpec);
        }
    } catch (AuthorizationException e) {
        throw new MappableException(e); // TODO Try without wrapping
    }
}
 
Example #17
Source Project: arcusplatform   Author: arcus-smart-home   File: IrisRealm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This implementation of the interface expects the principals collection to return a String username keyed off of
 * this realm's {@link #getName() name}
 *
 * @see #getAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   //null usernames are invalid
   if (principals == null) {
      throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
   }

   String username = (String) getAvailablePrincipal(principals);

   Set<String> roleNames;
   Set<String> permissions = null;
   try {
      // Retrieve roles and permissions from database
      roleNames = getRoleNamesForUser(cassandraSession, username);
      if (permissionsLookupEnabled) {
         permissions = getPermissions(cassandraSession, roleNames);
      }
   } catch (SQLException e) {
      final String message = "There was a SQL error while authorizing user [" + username + "]";
      if (log.isErrorEnabled()) {
         log.error(message, e);
      }

      // Rethrow any SQL errors as an authorization exception
      throw new AuthorizationException(message, e);
   }

   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
   info.setStringPermissions(permissions);
   return info;

}
 
Example #18
Source Project: arcusplatform   Author: arcus-smart-home   File: GuicedIrisRealm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This implementation of the interface expects the principals collection to return a String username keyed off of
 * this realm's {@link #getName() name}
 *
 * @see #getAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   //null usernames are invalid
   if (principals == null) {
      throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
   }

   Principal principal = (Principal) getAvailablePrincipal(principals);

   Set<String> roleNames;
   Set<String> permissions = null;
   try {
      // Retrieve roles and permissions from database
      roleNames = getRoleNamesForUser(principal.getUsername());
      if (permissionsLookupEnabled) {
         permissions = getPermissions(roleNames);
      }
   } catch (Exception e) {
      final String message = "There was an error while authorizing user [" + principal.getUsername() + "]";
      log.error(message, e);
      // Rethrow any SQL errors as an authorization exception
      throw new AuthorizationException(message, e);
   }

   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
   info.setStringPermissions(permissions);
   return info;

}
 
Example #19
Source Project: mall   Author: bigspiders   File: AdminAuthorizingRealm.java    License: MIT License 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }

    LitemallAdmin admin = (LitemallAdmin) getAvailablePrincipal(principals);
    Integer[] roleIds = admin.getRoleIds();
    Set<String> roles = roleService.queryByIds(roleIds);
    Set<String> permissions = permissionService.queryByRoleIds(roleIds);
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.setRoles(roles);
    info.setStringPermissions(permissions);
    return info;
}
 
Example #20
Source Project: nexus-public   Author: sonatype   File: AuthorizingRepositoryManagerTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void invalidateCacheShouldThrowExceptionIfInsufficientPermissions() throws Exception {
  when(repository.getType()).thenReturn(new GroupType());
  doThrow(new AuthorizationException("User is not permitted."))
      .when(repositoryPermissionChecker)
      .ensureUserCanAdmin(any(), any());
  expectedException.expect(AuthorizationException.class);

  authorizingRepositoryManager.invalidateCache("repository");

  verify(repositoryManager).get(eq("repository"));
  verify(repositoryPermissionChecker).ensureUserCanAdmin(eq(EDIT), eq(repository));
  verifyNoMoreInteractions(repositoryManager, repositoryPermissionChecker, taskScheduler);
}
 
Example #21
Source Project: litemall   Author: linlinjava   File: AdminAuthorizingRealm.java    License: MIT License 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }

    LitemallAdmin admin = (LitemallAdmin) getAvailablePrincipal(principals);
    Integer[] roleIds = admin.getRoleIds();
    Set<String> roles = roleService.queryByIds(roleIds);
    Set<String> permissions = permissionService.queryByRoleIds(roleIds);
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.setRoles(roles);
    info.setStringPermissions(permissions);
    return info;
}
 
Example #22
Source Project: nexus-public   Author: sonatype   File: AuthorizingRepositoryManagerTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void rebuildIndexShouldThrowExceptionIfInsufficientPermissions() throws Exception {
  when(repository.getType()).thenReturn(new HostedType());
  doThrow(new AuthorizationException("User is not permitted."))
      .when(repositoryPermissionChecker)
      .ensureUserCanAdmin(any(), any());
  expectedException.expect(AuthorizationException.class);

  authorizingRepositoryManager.rebuildSearchIndex("repository");

  verify(repositoryManager).get(eq("repository"));
  verify(repositoryPermissionChecker).ensureUserCanAdmin(eq(EDIT), eq(repository));
  verifyNoMoreInteractions(repositoryManager, repositoryPermissionChecker, taskScheduler);
}
 
Example #23
Source Project: faster-framework-project   Author: faster-framework   File: ShiroConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ResponseErrorEntity execute(Exception exception) {
    if (exception instanceof AuthorizationException) {
        return ResponseErrorEntity.error(BasicErrorCode.PERMISSION_ERROR, HttpStatus.UNAUTHORIZED);
    }
    return ResponseErrorEntity.error(BasicErrorCode.SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example #24
Source Project: zeppelin   Author: apache   File: KerberosRealm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Query the Hadoop implementation of {@link Groups} to retrieve groups for
 * provided user.
 */
public Set<String> mapGroupPrincipals(final String mappedPrincipalName)
    throws AuthorizationException {
  /* return the groups as seen by Hadoop */
  Set<String> groups = null;
  try {
    hadoopGroups.refresh();
    final List<String> groupList = hadoopGroups.getGroups(mappedPrincipalName);

    LOG.debug(String.format("group found %s, %s",
          mappedPrincipalName, groupList.toString()));

    groups = new HashSet<>(groupList);

  } catch (final IOException e) {
    if (e.toString().contains("No groups found for user")) {
      /* no groups found move on */
      LOG.info(String.format("No groups found for user %s", mappedPrincipalName));
    } else {
      /* Log the error and return empty group */
      LOG.info(String.format("errorGettingUserGroups for %s", mappedPrincipalName));
      throw new AuthorizationException(e);
    }
    groups = new HashSet();
  }
  return groups;
}
 
Example #25
Source Project: ueboot   Author: ueboot   File: ShiroExceptionHandler.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExceptionHandler(AuthorizationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public Response<Void> handleException(AuthorizationException e) {
    log.error("权限验证未通过 {}",e.getMessage());
    shiroEventListener.afterLogin(currentUserName.get(),false,e.getMessage());
    ShiroExceptionHandler.remove();
    return new Response<>(HttpStatus.FORBIDDEN.value() + "", "当前用户无权限访问", null);
}
 
Example #26
Source Project: mySpringBoot   Author: MyBeany   File: CustomRealm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *  定义如何获取用户的角色和权限的逻辑,给shiro做权限判断
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }
    UserInfo user = (UserInfo) getAvailablePrincipal(principals);
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.setRoles(user.getRoles());
    info.setStringPermissions(user.getPerms());
    return info;
}
 
Example #27
Source Project: notes   Author: menhuan   File: CheckRealm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return org.apache.shiro.authc.AuthenticationInfo
 * @Author fruiqi
 * @Description 默认使用此方法进行用户名正确与否校验,出错抛出异常
 * @Date 2:30 2019/3/9
 * @Param [token]
 **/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    JwtToken jwtToken = (JwtToken) token;
    String tokenContent = (String) jwtToken.getCredentials();
    String name = JwtUtil.getUsername(tokenContent);
    AdminDto adminDto = AdminShiroService.selectAdminByAdminName(name);
    if (adminDto == null) {
        throw new AuthorizationException(ERROR_CHECK_NAME_ERROR100013.getInfo());
    }

    Map<String, Object> map = new HashMap<>();
    map.put("userName", name);
    map.put("userId", adminDto.getAdminId());
    map.put("timestamp", getTimeStamp(tokenContent));
    if (!JwtUtil.verify(tokenContent, map, JWT_SECRET)) {
        throw new AuthenticationException(ERROR_CHECK_NAME_ERROR100014.getInfo());
    }
    ;

    String admin = "admin";
    if (adminDto.getAdminGrade() == 1) {
        admin = "superAdmin";
    }

    if (adminDto.getAdminGrade() == 0) {
        admin = "admin" ;
    }


    return new SimpleAuthenticationInfo(tokenContent, tokenContent, admin);
}
 
Example #28
Source Project: nexus-repository-helm   Author: sonatype-nexus-community   File: HelmSecurityFacetTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEnsurePermitted_notPermitted() throws Exception {
  when(contentPermissionChecker.isPermitted(eq("HelmSecurityFacetTest"), eq("helm"), eq(READ), any()))
      .thenReturn(false);
  try {
    helmSecurityFacet.ensurePermitted(request);
    fail("AuthorizationException should have been thrown");
  }
  catch (AuthorizationException e) {
    //expected
  }

  verify(contentPermissionChecker).isPermitted(eq("HelmSecurityFacetTest"), eq("helm"), eq(READ), any());
}
 
Example #29
Source Project: shiro-jersey   Author: silb   File: ShiroExceptionMapper.java    License: Apache License 2.0 5 votes vote down vote up
@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 #30
Source Project: LuckyFrameWeb   Author: seagull1985   File: DefaultExceptionHandler.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 权限校验失败
 */
@ExceptionHandler(AuthorizationException.class)
public AjaxResult handleAuthorizationException(AuthorizationException e)
{
    log.error(e.getMessage(), e);
    return AjaxResult.error(PermissionUtils.getMsg(e.getMessage()));
}