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 File: HttpRequestSessionManager.java    From usergrid with 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 File: ShiroExceptionHandler.java    From gazpachoquest with 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 #3
Source File: JPARealm.java    From gazpachoquest with 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 File: ShiroInterceptor.java    From shiro-jwt with 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 #5
Source File: SimpleAuthorizingRealm.java    From NutzSite with 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 #6
Source File: AllowAllRealm.java    From airpal with 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 File: ShiroRealm.java    From layui-admin with 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 #8
Source File: RawSecurityFacetTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEnsurePermitted_permitted() throws Exception {
  when(contentPermissionChecker.isPermitted(eq("RawSecurityFacetTest"), eq("raw"), eq(READ), any()))
      .thenReturn(true);

  try {
    rawSecurityFacet.ensurePermitted(request);
  }
  catch (AuthorizationException e) {
    fail("expected permitted operation to succeed");
  }
}
 
Example #9
Source File: GolangSecurityFacetTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEnsurePermitted_notPermitted() throws Exception {
  when(contentPermissionChecker.isPermitted(eq("GoSecurityFacetTest"), eq("go"), eq(READ), any()))
      .thenReturn(false);
  try {
    golangSecurityFacet.ensurePermitted(request);
    fail("AuthorizationException should have been thrown");
  }
  catch (AuthorizationException e) {
    //expected
  }

  verify(contentPermissionChecker).isPermitted(eq("GoSecurityFacetTest"), eq("go"), eq(READ), any());
}
 
Example #10
Source File: MaintenanceServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = AuthorizationException.class)
public void testDeleteAsset_notPermitted() {
  when(contentPermissionChecker.isPermitted("maven-releases", "maven2", BreadActions.DELETE, variableSource))
      .thenReturn(false);

  underTest.deleteAsset(mavenReleases, assetOne);
}
 
Example #11
Source File: SecurityFacetSupportTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEnsurePermitted_notPermitted() throws Exception {
  when(contentPermissionChecker.isPermitted(eq("SecurityFacetSupportTest"), eq("test"), eq(READ), any()))
      .thenReturn(false);

  try {
    testSecurityFacetSupport.ensurePermitted(request);
    fail("AuthorizationException should have been thrown");
  }
  catch (AuthorizationException e) {
    //expected
  }

  verify(contentPermissionChecker).isPermitted(eq("SecurityFacetSupportTest"), eq("test"), eq(READ), any());
}
 
Example #12
Source File: SecurityFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void ensurePermitted(final Request request) {
  checkNotNull(request);

  // determine permission action from request
  String action = action(request);

  Repository repo = getRepository();

  VariableSource variableSource = variableResolverAdapter.fromRequest(request, getRepository());
  if (!contentPermissionChecker.isPermitted(repo.getName(), repo.getFormat().getValue(), action, variableSource)) {
    throw new AuthorizationException();
  }
}
 
Example #13
Source File: DefaultSecuritySystemTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testChangePassword_AfterUserLogin() throws UserNotFoundException, NoSuchUserManagerException {
  expectedException.expect(AuthorizationException.class);
  expectedException.expectMessage("jcoder is not permitted to change the password for fakeuser");

  SecuritySystem securitySystem = this.getSecuritySystem();
  Subject subject = securitySystem.getSubject();
  subject.login(new UsernamePasswordToken("jcoder", "jcoder"));

  // change my own
  securitySystem.changePassword("jcoder", "newpassword");

  // change another user's password
  securitySystem.changePassword("fakeuser", "newpassword");
}
 
Example #14
Source File: ExternalRoleMappedTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testUserHasPermissionFromExternalRole() throws Exception {
  SecuritySystem securitySystem = this.lookup(SecuritySystem.class);

  Map<String, String> properties = new HashMap<String, String>();
  properties.put(WildcardPrivilegeDescriptor.P_PATTERN, "permissionOne:read");

  securitySystem.getAuthorizationManager("default").addPrivilege(new Privilege(
      "randomId",
      "permissionOne",
      "permissionOne",
      WildcardPrivilegeDescriptor.TYPE,
      properties,
      false));

  securitySystem.getAuthorizationManager("default").addRole(new Role("mockrole1", "mockrole1", "mockrole1",
      "default", false, null,
      Collections.singleton("randomId")));

  // add MockRealm to config
  RealmManager realmManager = lookup(RealmManager.class);
  RealmConfiguration realmConfiguration = new TestRealmConfiguration();
  realmConfiguration.setRealmNames(ImmutableList.of("Mock", AuthorizingRealmImpl.NAME));
  realmManager.setConfiguration(realmConfiguration);

  // jcohen has the role mockrole1, there is also test role with the same ID, which means jcohen automaticly has
  // this test role

  PrincipalCollection jcohen = new SimplePrincipalCollection("jcohen", MockRealm.NAME);

  try {
    securitySystem.checkPermission(jcohen, "permissionOne:invalid");
    Assert.fail("Expected AuthorizationException");
  }
  catch (AuthorizationException e) {
    // expected
  }

  securitySystem.checkPermission(jcohen, "permissionOne:read"); // throws on error, so this is all we need to do
}
 
Example #15
Source File: NexusBasicHttpAuthenticationFilter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Permissive {@link AuthorizationException} 401 and 403 handling.
 */
@Override
protected void cleanup(final ServletRequest request, final ServletResponse response, Exception failure)
    throws ServletException, IOException
{
  // decode target exception
  Throwable cause = failure;
  if (cause instanceof ServletException) {
    cause = cause.getCause();
  }

  // special handling for authz failures due to permissive
  if (cause instanceof AuthorizationException) {
    // clear the failure
    failure = null;

    Subject subject = getSubject(request, response);
    boolean authenticated = subject.getPrincipal() != null && subject.isAuthenticated();

    if (authenticated) {
      // authenticated subject -> 403 forbidden
      WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    else {
      // unauthenticated subject -> 401 inform to authenticate
      try {
        // TODO: Should we build in browser detecting to avoid sending 401, should that be its own filter?

        onAccessDenied(request, response);
      }
      catch (Exception e) {
        failure = e;
      }
    }
  }

  super.cleanup(request, response, failure);
}
 
Example #16
Source File: ShiroRealm.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals ) {
    try {
        if ( principals == null ) {
            throw new AuthorizationException( "PrincipalCollection method argument cannot be null." );
        }

        Collection<String> principalsList = principals.byType( String.class );

        if ( principalsList.isEmpty() ) {
            throw new AuthorizationException( "Empty principals list!" );
        }

        String username = ( String ) principals.getPrimaryPrincipal();

        Set<String> roles = new HashSet<String>();
        roles.add( "role1" );

        LOG.info( String.format( "Authorizing user %s with roles %s", username, roles ) );

        return new SimpleAuthorizationInfo( roles );

    } catch ( Exception e ) {
        LOG.error( "Error while authorizing", e );
        throw new AuthorizationException( "Authorization failed", e );
    }
}
 
Example #17
Source File: SecurityHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Ensure subject has any of the given permissions.
 *
 * @throws AuthorizationException
 */
public void ensureAnyPermitted(final Subject subject, final Permission... permissions) {
  checkNotNull(subject);
  checkNotNull(permissions);
  checkArgument(permissions.length != 0);

  if (log.isTraceEnabled()) {
    log.trace("Ensuring subject '{}' has any of the following permissions: {}", subject.getPrincipal(), Arrays.toString(permissions));
  }

  if (!anyPermitted(subject, permissions)) {
    throw new AuthorizationException("User is not permitted.");
  }
}
 
Example #18
Source File: MaintenanceServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = AuthorizationException.class)
public void testDeleteComponent_NotAuthorized() {
  when(storageTx.browseAssets(component)).thenReturn(singletonList(assetOne));
  when(contentPermissionChecker.isPermitted("maven-releases", "maven2", BreadActions.DELETE, variableSource))
      .thenReturn(false);

  underTest.deleteComponent(mavenReleases, component);
}
 
Example #19
Source File: BaseExceptionHandler.java    From yyblog with MIT License 5 votes vote down vote up
@ExceptionHandler(AuthorizationException.class)
public Object handleAuthorizationException(AuthorizationException e, HttpServletRequest request) {
    logger.error(e.getMessage(), e);
    if (AjaxUtils.jsAjax(request)) {
        return YYBlogResult.build(ResultEnum.UN_AUTHORIZED.getCode(), ResultEnum.UN_AUTHORIZED.getValue());
    }
    return new ModelAndView("error/403");
}
 
Example #20
Source File: CondaSecurityFacetTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEnsurePermittedNotPermitted() {
  when(contentPermissionChecker.isPermitted(eq(CONDA_SECURITY_FACET_TEST), eq(CondaFormat.NAME), eq(READ), any()))
      .thenReturn(false);
  try {
    condaSecurityFacet.ensurePermitted(request);
    fail("AuthorizationException should have been thrown");
  }
  catch (AuthorizationException e) {
    //expected
  }

  verify(contentPermissionChecker).isPermitted(eq(CONDA_SECURITY_FACET_TEST), eq(CondaFormat.NAME), eq(READ), any());
}
 
Example #21
Source File: CondaSecurityFacetTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEnsurePermittedPermitted() {
  when(contentPermissionChecker.isPermitted(eq(CONDA_SECURITY_FACET_TEST), eq(CondaFormat.NAME), eq(READ), any()))
      .thenReturn(true);
  try {
    condaSecurityFacet.ensurePermitted(request);
  }
  catch (AuthorizationException e) {
    fail("expected operation to be permitted");
  }
}
 
Example #22
Source File: ShiroExceptionMapper.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(ShiroException exception) {
  if (AuthorizationException.class.isAssignableFrom(exception.getClass())
      || AuthenticationException.class.isAssignableFrom(exception.getClass())) {
    LOG.info("Authentication failed", exception);
    return Response.status(Response.Status.FORBIDDEN).entity(exception.getMessage()).build();
  }

  LOG.error("Unexpected ShiroException", exception);
  return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
 
Example #23
Source File: AuthorizationResourceFilter.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes the client for the annotated permissions.  If any authorizations fail an {@link AuthorizationException}
 * will be thrown, otherwise the original request is returned.
 */
@Override
public ContainerRequest filter(ContainerRequest request) {
    Subject subject = ThreadContext.getSubject();

    String[] permissions = resolvePermissions(request);

    if (permissions.length == 1 || _logical == Logical.AND) {
        // Shortcut call to check all permissions at once
        subject.checkPermissions(permissions);
    } else {
        // Check each permission until any passes
        boolean anyPermitted = false;
        int p = 0;
        while (!anyPermitted) {
            try {
                subject.checkPermission(permissions[p]);
                anyPermitted = true;
            } catch (AuthorizationException e) {
                // If this is the last permission then pass the exception along
                if (++p == permissions.length) {
                    throw e;
                }
            }
        }
    }

    return request;
}
 
Example #24
Source File: AuthorizationExceptionHandler.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(AuthorizationException exception) {
    // AuthorizationException is only used internally to propagate authorization errors.  Convert the
    // exception to the equivalent public-facing exception from the API.
    UnauthorizedException apiException = new UnauthorizedException();
    return _providers.getExceptionMapper(UnauthorizedException.class).toResponse(apiException);
}
 
Example #25
Source File: ControllerAOP.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 5 votes vote down vote up
private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
    ResultBean<?> result = new ResultBean();

    // 已知异常
    if (e instanceof CheckException) {
        result.setMsg(e.getLocalizedMessage());
        result.setCode(ResultBean.FAIL);
    }
    // 自己抛出的
    else if (e instanceof UnloginException ) {
        result.setMsg("Unlogin");
        result.setCode(ResultBean.NO_LOGIN);
    }
    //shiro异常: 登陆失败,如密码错误
    else if (e instanceof IncorrectCredentialsException) {
        result.setMsg("Login failed. Try xwjie/123456");
        result.setCode(ResultBean.FAIL);
    }
    // shiro异常:没有权限
    else if (e instanceof UnauthorizedException) {
        result.setMsg("NO PERMISSION: " + e.getMessage());
        result.setCode(ResultBean.NO_PERMISSION);
    }
    //  shiro抛出
    else if (e instanceof AuthorizationException) {
        result.setMsg("Unlogin");
        result.setCode(ResultBean.NO_LOGIN);
    }
    else {
        logger.error(pjp.getSignature() + " error ", e);

        //TODO 未知的异常,应该格外注意,可以发送邮件通知等
        result.setMsg(e.toString());
        result.setCode(ResultBean.FAIL);
    }

    return result;
}
 
Example #26
Source File: ConanSecurityFacetTest.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEnsurePermitted_notPermitted() {
  when(contentPermissionChecker.isPermitted(eq("ConanSecurityFacetTest"), eq("conan"), eq(READ), any()))
      .thenReturn(false);
  try {
    conanSecurityFacet.ensurePermitted(request);
    fail("AuthorizationException should have been thrown");
  }
  catch (AuthorizationException e) {
    //expected
  }

  verify(contentPermissionChecker).isPermitted(eq("ConanSecurityFacetTest"), eq("conan"), eq(READ), any());
}
 
Example #27
Source File: ShiroRequiresRolesProcesser.java    From jboot with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizeResult authorize() {
    String[] roles = requiresRoles.value();
    try {
        if (roles.length == 1) {
            SecurityUtils.getSubject().checkRole(roles[0]);
            return AuthorizeResult.ok();
        }
        if (Logical.AND.equals(requiresRoles.logical())) {
            SecurityUtils.getSubject().checkRoles(Arrays.asList(roles));
            return AuthorizeResult.ok();
        }
        if (Logical.OR.equals(requiresRoles.logical())) {
            // Avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasRole first
            boolean hasAtLeastOneRole = false;
            for (String role : roles) if (SecurityUtils.getSubject().hasRole(role)) hasAtLeastOneRole = true;
            // Cause the exception if none of the role match, note that the exception message will be a bit misleading
            if (!hasAtLeastOneRole) SecurityUtils.getSubject().checkRole(roles[0]);
        }
        
        return AuthorizeResult.ok();

    } catch (AuthorizationException e) {
        return AuthorizeResult.fail(AuthorizeResult.ERROR_CODE_UNAUTHORIZATION);
    }

}
 
Example #28
Source File: ShiroRequiresPermissionsProcesser.java    From jboot with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizeResult authorize() {
    try {
        String[] perms = requiresPermissions.value();
        Subject subject = SecurityUtils.getSubject();

        if (perms.length == 1) {
            subject.checkPermission(perms[0]);
            return AuthorizeResult.ok();
        }
        if (Logical.AND.equals(requiresPermissions.logical())) {
            subject.checkPermissions(perms);
            return AuthorizeResult.ok();
        }
        if (Logical.OR.equals(requiresPermissions.logical())) {
            // Avoid processing exceptions unnecessarily - "delay" throwing the
            // exception by calling hasRole first
            boolean hasAtLeastOnePermission = false;
            for (String permission : perms)
                if (subject.isPermitted(permission))
                    hasAtLeastOnePermission = true;
            // Cause the exception if none of the role match, note that the
            // exception message will be a bit misleading
            if (!hasAtLeastOnePermission)
                subject.checkPermission(perms[0]);

        }

        return AuthorizeResult.ok();

    } catch (AuthorizationException e) {
        return AuthorizeResult.fail(AuthorizeResult.ERROR_CODE_UNAUTHORIZATION);
    }
}
 
Example #29
Source File: ShiroUtils.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 当前用户是否拥有权限
 * 
 * @param permName
 *            权限名称
 */
public static boolean hasPerms(String permission) {
	try {
		SecurityUtils.getSubject().checkPermission(permission);
		return true;
	} catch (AuthorizationException e) {
		// 不处理
	}
	return false;
}
 
Example #30
Source File: AdminAuthorizingRealm.java    From dts-shop with 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;
}