An authorization library that supports access control models like ACL, RBAC, ABAC in Java

Overview

jCasbin

codebeat badge GitHub Actions codecov Javadocs Maven Central Release Gitter

News: still worry about how to write the correct jCasbin policy? Casbin online editor is coming to help! Try it at: http://casbin.org/editor/

casbin Logo

jCasbin is a powerful and efficient open-source access control library for Java projects. It provides support for enforcing authorization based on various access control models.

All the languages supported by Casbin:

golang java nodejs php
Casbin jCasbin node-Casbin PHP-Casbin
production-ready production-ready production-ready production-ready
python dotnet c++ rust
PyCasbin Casbin.NET Casbin-CPP Casbin-RS
production-ready production-ready beta-test production-ready

Table of contents

Supported models

  1. ACL (Access Control List)
  2. ACL with superuser
  3. ACL without users: especially useful for systems that don't have authentication or user log-ins.
  4. ACL without resources: some scenarios may target for a type of resources instead of an individual resource by using permissions like write-article, read-log. It doesn't control the access to a specific article or log.
  5. RBAC (Role-Based Access Control)
  6. RBAC with resource roles: both users and resources can have roles (or groups) at the same time.
  7. RBAC with domains/tenants: users can have different role sets for different domains/tenants.
  8. ABAC (Attribute-Based Access Control): syntax sugar like resource.Owner can be used to get the attribute for a resource.
  9. RESTful: supports paths like /res/*, /res/:id and HTTP methods like GET, POST, PUT, DELETE.
  10. Deny-override: both allow and deny authorizations are supported, deny overrides the allow.
  11. Priority: the policy rules can be prioritized like firewall rules.

How it works?

In jCasbin, an access control model is abstracted into a CONF file based on the PERM metamodel (Policy, Effect, Request, Matchers). So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules.

The most basic and simplest model in jCasbin is ACL. ACL's model CONF is:

# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

An example policy for ACL model is like:

p, alice, data1, read
p, bob, data2, write

It means:

  • alice can read data1
  • bob can write data2

Features

What jCasbin does:

  1. enforce the policy in the classic {subject, object, action} form or a customized form as you defined, both allow and deny authorizations are supported.
  2. handle the storage of the access control model and its policy.
  3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC).
  4. support built-in superuser like root or administrator. A superuser can do anything without explict permissions.
  5. multiple built-in operators to support the rule matching. For example, keyMatch can map a resource key /foo/bar to the pattern /foo*.

What jCasbin does NOT do:

  1. authentication (aka verify username and password when a user logs in)
  2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and jCasbin is not designed as a password container. However, jCasbin stores the user-role mapping for the RBAC scenario.

Installation

For Maven:

<dependency>
  <groupId>org.casbin</groupId>
  <artifactId>jcasbin</artifactId>
  <version>1.6.3</version>
</dependency>

Documentation

https://casbin.org/docs/en/overview

Online editor

You can also use the online editor (http://casbin.org/editor/) to write your jCasbin model and policy in your web browser. It provides functionality such as syntax highlighting and code completion, just like an IDE for a programming language.

Tutorials

https://casbin.org/docs/en/tutorials

Get started

  1. New a jCasbin enforcer with a model file and a policy file:

    Enforcer enforcer = new Enforcer("path/to/model.conf", "path/to/policy.csv");

Note: you can also initialize an enforcer with policy in DB instead of file, see Policy persistence section for details.

  1. Add an enforcement hook into your code right before the access happens:

    String sub = "alice"; // the user that wants to access a resource.
    String obj = "data1"; // the resource that is going to be accessed.
    String act = "read"; // the operation that the user performs on the resource.
    
    if (enforcer.enforce(sub, obj, act) == true) {
        // permit alice to read data1
    } else {
        // deny the request, show an error
    }
  2. Besides the static policy file, jCasbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:

    Roles roles = enforcer.getRoles("alice");

See Policy management APIs for more usage.

  1. Please refer to the src/test package for more usage.

Policy management

jCasbin provides two sets of APIs to manage permissions:

  • Management API: the primitive API that provides full support for jCasbin policy management. See here for examples.
  • RBAC API: a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code. See here for examples.

We also provide a web-based UI for model management and policy management:

model editor

policy editor

Policy persistence

https://casbin.org/docs/en/adapters

Role manager

https://casbin.org/docs/en/role-managers

Examples

Model Model file Policy file
ACL basic_model.conf basic_policy.csv
ACL with superuser basic_model_with_root.conf basic_policy.csv
ACL without users basic_model_without_users.conf basic_policy_without_users.csv
ACL without resources basic_model_without_resources.conf basic_policy_without_resources.csv
RBAC rbac_model.conf rbac_policy.csv
RBAC with resource roles rbac_model_with_resource_roles.conf rbac_policy_with_resource_roles.csv
RBAC with domains/tenants rbac_model_with_domains.conf rbac_policy_with_domains.csv
ABAC abac_model.conf N/A
RESTful keymatch_model.conf keymatch_policy.csv
Deny-override rbac_model_with_deny.conf rbac_policy_with_deny.csv
Priority priority_model.conf priority_policy.csv

Middlewares

Authz middlewares for web frameworks: https://casbin.org/docs/en/middlewares

Our adopters

https://casbin.org/docs/en/adopters

Spring Boot support

We provide Spring Boot support, you can use casbin-spring-boot-starter to quickly develop in SpringBoot

In casbin-spring-boot-starter, we made the following adjustments:

  1. Rewrite JDBCAdapter to support a variety of commonly used JDBC databases
  2. Implement RedisWatcher
  3. IDEA Editor Configuration Tips
  4. Provide default configuration, automatic assembly
  5. SpringSecurity integration (future)
  6. Shiro integration (future)

https://github.com/jcasbin/casbin-spring-boot-starter

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

This project is licensed under the Apache 2.0 license.

Contact

If you have any issues or feature requests, please contact us. PR is welcomed.

Comments
  • Question: Is there a way to escape comma in policy rule?

    Question: Is there a way to escape comma in policy rule?

    Hi,

    I noticed that jcasbin is using aviator as its evaluator, and I'm trying to use some of its builtin functions ( to be specific, function "include" ) which takes in more than one parameter (so there will be comma in expression).

    If the expression is written in matcher, everything works fine. But if It is written in policy rule, the parser is unhappy and throws an exception

    https://github.com/casbin/jcasbin/blob/4227edc637aace211983976032c0cec824afe67e/src/main/java/org/casbin/jcasbin/util/Util.java#L201-L214

    The code above seems to split the line directly by comma, which breaks the expression.

    So I'd like to question if there is any plan on the support of escaping comma?

    P.S. I've also tried to use SQL adapter, but with no luck. It seems that lines being read from database still gets concated and goes into this function

    enhancement released 
    opened by young-zy 26
  • The automated release is failing 🚨

    The automated release is failing 🚨

    :rotating_light: The automated release from the master branch failed. :rotating_light:

    I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

    You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

    Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

    Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

    If you are not sure how to resolve this, here is some links that can help you:

    If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


    Deployment to maven failed.

    The deployment to maven failed for an unknown reason.

    Please check the logs on the CI server to see what happened.


    Good luck with your project ✨

    Your semantic-release bot :package::rocket:

    semantic-release 
    opened by hsluoyz 18
  • Group with domain model not working

    Group with domain model not working

    Hi guys, with the latest code chage. you guys change the unit test case directly as following:

    Model:

    [request_definition]
    r = sub, dom, obj, act
    
    [policy_definition]
    p = sub, dom, obj, act
    
    [role_definition]
    g = _,_
    g2 = _, _, _
    
    [policy_effect]
    e = some(where (p.eft == allow))
    
    [matchers]
    m = (g(r.sub, p.sub) || g2(r.sub, p.sub, r.dom)) && r.obj == p.obj && r.act == p.act
    

    Test case expression:

    p, admin, domain1, data1, read
    g, alice, group1
    g2, group1, admin, domain1
    

    Test case

    public void testGroupRoleManager() {
            Enforcer e = new Enforcer("examples/group_with_domain_model.conf", "examples/group_with_domain_policy.csv");
            testDomainEnforce(e, "alice", "domain1", "data1", "read", false);
        }
    

    So, what alice can access ?

    question 
    opened by doctormacky 17
  • eval() doesn't work for java.util functions, need to switch from bsh to aviator

    eval() doesn't work for java.util functions, need to switch from bsh to aviator

    Hello, I am trying to do a POC on using ABAC via "jcasbin" and I am facing an issue related to the "eval" function. The eval function in the jcasbin library prior to the 1.7.1 version allowed using java expressions whereas a change was added in version 1.7.1 (https://github.com/casbin/jcasbin/compare/v1.7.0...v1.7.1) which broke this functionality. When I used "casbin-spring-boot-starter" dependency, the jcasbin library included was of version 1.6.4 and I was able to evaluate the following policy definition:

    "\"test\".equals(r.sub) && java.util.regex.Pattern.compile(\"/*/url1/url2/*\", java.util.regex.Pattern.CASE_INSENSITIVE).matcher(r.obj).find()","r.obj","PUT"

    with the below model definition:

    [request_definition]
    r = sub, obj, act
    
    [policy_definition]
    p = sub_rule, obj, act
    
    [policy_effect]
    e = some(where (p.eft == allow))
    
    [matchers]
    m = eval(p.sub_rule) && r.act == p.act
    

    Please note that I had to use the enforcer.addPolicy() method for adding the above policy definition because the csv parser with the file adapter was splitting the definition with comma. Then I found that the comma issue was fixed in version 1.8.1 (https://github.com/casbin/jcasbin/issues/158). So, I upgraded the jcasbin library to 1.8.1 but then the above stopped working because the eval function is changing the above expression to:

    "test1".getEquals(r_sub)() && java.getUtil().getRegex().getgetPattern()().getCompile("/*/approve/expense/*",() java.getUtil().getRegex().getgetPattern()().getCASE_INSENSITIVE)().getMatcher(r_obj)().find()

    i.e., its appending get for all the attributes and is not working as java expression.

    I know that we can use functions (and even write our own customized function) in the model definition. But my requirement is to define a function in the policy definition. The reason being, I don't want to use the function for all the use cases and so the use case for which I need, I can define that in the policy definition.

    Could you please suggest how can we achieve that?

    bug 
    opened by rachnaaggarwal 17
  • GetImplicitPermissionsForUser only takes into account subject grouping

    GetImplicitPermissionsForUser only takes into account subject grouping

    Would it be feasible to extend this method so it takes into account any grouping, not just the subject grouping? e.g. with the following model:

    [request_definition]
    r = sub, obj, act
    
    [policy_definition]
    p = sub, obj, act
    
    [role_definition]
    g = _, _
    g2 = _, _
    g3 = _, _
    
    [policy_effect]
    e = some(where (p.eft == allow))
    
    [matchers]
    m = g(r.sub, p.sub) && g2(r.obj, p.obj) && g3(r.act, p.act)
    

    getImplicitPermissionsForUser will take into account g, but not g2 or g3.

    enhancement released 
    opened by lanmarti 15
  • Rename all

    Rename all "jcasbin"s to "casbin" except this GitHub repo name

    We will rename to "casbin" for everywhere including the Maven package manager, except this GitHub repo name to differentiate with Go's Casbin.

    enhancement 
    opened by hsluoyz 15
  • Delete the group API interface bug

    Delete the group API interface bug

    When using this interface enforcer. RemoveNameGroupingPolicy (" g ", "role1") to delete group, database data deleted successfully, but cached data is still there.

    POM

    <dependency>  
          <groupId>org.casbin</groupId>
          <artifactId>jcasbin</artifactId>
          <version>1.21.0</version>
    </dependency>
    <dependency>
          <groupId>org.casbin</groupId>
          <artifactId>jdbc-adapter</artifactId>
          <version>2.2.1</version>
    </dependency>
    

    Execute Code

    image

    Adapter

    image

    Datebase & Cache

    image bug 
    opened by Memory63 14
  • @arti0798 please open a new issue for your Redis problem. This issue is only for resolving the issue for @young-zy

    @arti0798 please open a new issue for your Redis problem. This issue is only for resolving the issue for @young-zy

    @arti0798 please open a new issue for your Redis problem. This issue is only for resolving the issue for @young-zy

    Originally posted by @hsluoyz in https://github.com/casbin/jcasbin/issues/158#issuecomment-812269848

    question 
    opened by arti0798 14
  • How to define new matcher function?

    How to define new matcher function?

    I've written a function but now how should add it to function map?

    public class InCollectionFunc extends AbstractFunction {
        public InCollectionFunc() {
        }
    
        public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
            String value = FunctionUtils.getStringValue(arg1, env);
            String collection = FunctionUtils.getStringValue(arg3, env);
            return AviatorBoolean.valueOf(isInCollection(value, collection));
        }
    
        private boolean isInCollection(String value,String collection) {
            System.out.println("value:" + value + " isIn collection:" + collection);
            return true;
        }
    
        public String getName() {
            return getNameStatic();
        }
    
        public static String getNameStatic() {
            return "isIn";
        }
    }
    
    enforcer = new Enforcer("erole.conf", "policy.csv");
    enforcer.addFunction(InCollectionFunc.getNameStatic(),new InCollectionFunc());
    
    question 
    opened by M-Razavi 13
  • Add keyGet() and keyGet2() functions to jCasbin

    Add keyGet() and keyGet2() functions to jCasbin

    StackOverflow question: https://stackoverflow.com/questions/66046585/casbin-user-may-only-call-path-with-their-own-username/66049093?noredirect=1#comment116801013_66049093

    Go code: https://github.com/casbin/casbin/pull/675

    enhancement released 
    opened by hsluoyz 12
  • Not able to use loadFilteredPolicy with JdbcAdatper in Jcasbin

    Not able to use loadFilteredPolicy with JdbcAdatper in Jcasbin

    i think theres an issue in Jcasbin java version 1.6.3 and older , it does not support filtering on jdbc adapter, when i try to use https://github.com/jcasbin/casbin-spring-boot-starter with jcasbin, i see that in CoreEnforcer , it expects FilterAdapter only from file_adapter package, else throws this eroor.in short cannot use any jdbc adapter with Jcasbin

    * loadFilteredPolicy reloads a filtered policy from file/database.
     *
     * @param filter the filter used to specify which type of policy should be loaded.
     */
    public void loadFilteredPolicy(Object filter) {
        model.clearPolicy();
        FilteredAdapter filteredAdapter;
        if (adapter instanceof FilteredAdapter) {
            filteredAdapter = (FilteredAdapter) adapter;
        } else {
            throw new CasbinAdapterException("Filtered policies are not supported by this adapter.");
        }
    

    in above code FilteredAdapter should be referenced from org.casbin.jcasbin.persist package which is a parent interface. Due to this when i try to use any jdbcadapter to filter policies i get an error "Filtered policies are not supported by this adapter."

    bug 
    opened by shreyasGit 12
  • Android Support Below API 26 (Oreo)

    Android Support Below API 26 (Oreo)

    Hello,

    I am using the jCasbin library on Android, and it looks like one of the dependencies of the project AviatorScript is using a Java 8 Language method only supported in Android 26 and above. This makes the jCasbin library unusable for a large portion of devices (~20%).

    The Java method in question is invokeExact(Object... args) and invoke(Object... args)

    And while Android does support backwards compatibility for most Java 8 language features, you will notice in this documentation that it does not include the two methods mentioned above.

    Thanks!

    enhancement 
    opened by JeffPereyma 6
Releases(v1.31.3)
Owner
Casbin
Casbin authorization library and the official middlewares
Casbin
Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...

pac4j is an easy and powerful security engine for Java to authenticate users, get their profiles and manage authorizations in order to secure web appl

PAC4J 2.2k Dec 30, 2022
Password4j is a user-friendly cryptographic library that supports Argon2, Bcrypt, Scrypt, PBKDF2 and various cryptographic hash functions.

Password4j is a Java user-friendly cryptographic library for hashing and checking passwords with different Key derivation functions (KDFs) and Cryptog

Password4J 246 Jan 5, 2023
Open Source Identity and Access Management For Modern Applications and Services

Keycloak Keycloak is an Open Source Identity and Access Management solution for modern Applications and Services. This repository contains the source

Keycloak 14.6k Jan 5, 2023
Auto reply app helping you move away from less private messengers like WhatsApp and Facebook Messenger

Watomatic - Auto reply for WhatsApp so you can stop using it Watomatic sends an automated reply to everyone contacting you on WhatsApp. This is especi

Deekshith Allamaneni 335 Dec 28, 2022
Java binding to the Networking and Cryptography (NaCl) library with the awesomeness of libsodium

kalium - Java binding to the Networking and Cryptography (NaCl) library A Java binding to Networking and Cryptography library by Daniel J. Bernstein.

Bruno Oliveira da Silva 206 Oct 5, 2022
A small and easy-to-use one-time password generator library for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP).

OTP-Java A small and easy-to-use one-time password generator for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP). Table of Contents Features Ins

Bastiaan Jansen 106 Dec 30, 2022
A library for bypassing all of Java's security mechanisms, visibility checks, and encapsulation measures via the JNI API

Narcissus: thwart strong encapsulation in JDK 16+ Narcissus is a JNI native code library that provides a small subset of the Java reflection API, whil

ToolFactory 29 Nov 3, 2022
A small and easy-to-use one-time password generator library for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP).

OTP-Java A small and easy-to-use one-time password generator for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP). Table of Contents Features Ins

Bastiaan Jansen 106 Dec 30, 2022
A Twitter-API library JAVA

Tweety A Twitter-API library for JAVA. Code for Authorization (Oauth 1) can be found here :Authorization This api conta

Rohit Kumar 2 Apr 26, 2022
Java Secure Cookie Library

Java library for security cookies, client-side pieces of data protected from reading and modifications by client with strong cryptography

Sergey Vladimirov 1 Oct 9, 2022
Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.

Tink A multi-language, cross-platform library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse. Ubuntu

Google 12.9k Jan 3, 2023
The react-native Baidu voice library provides voice recognition, voice wake-up and voice synthesis interfaces. react-native百度语音库,提供语音识别,语音唤醒以及语音合成接口。

react-native-baidu-asr react-native-baidu-asr It is a Baidu speech library under React Native, which can perform speech recognition, speech wake-up an

dengweibin 11 Oct 12, 2022
This is an android library to represent password strength.

PasswordStrengthView This is an android library to represent password strength. Preview How to use? Add maven to your project gradle file allprojects

null 33 Jan 3, 2022
Library to easily configure API Key authentication in (parts of) your Spring Boot Application

42 API Key Authentication A library to easily configure API Key authentication in (parts of) your Spring Boot Application. Features Easily configure A

null 2 Dec 8, 2021
ByteSkriptQuery - A library for deploying ByteSkript as a backend web technology.

ByteSkriptQuery A language library for ByteSkript that allows it to be deployed as a backend web language. Not only does this allow the creation of ad

null 1 Jan 4, 2022
Java JWT: JSON Web Token for Java and Android

Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand library for creating and verifying JSON Web Tokens (JW

null 8.8k Dec 30, 2022
Java Project based on Java and Encryption using Cryptography algorithms

Symmetric-Encryption-Cryptography-in-Java Java Project based on Java and Encryption using Cryptography algorithms Project Aim Develop Java program to

Muhammad Asad 6 Feb 3, 2022
A mitigation for CVE-2021-44228 (log4shell) that works by patching the vulnerability at runtime. (Works with any vulnerable java software, tested with java 6 and newer)

Log4jPatcher A Java Agent based mitigation for Log4j2 JNDI exploits. This agent employs 2 patches: Disabling all Lookup conversions (on supported Log4

null 45 Dec 16, 2022
Bouncy Castle Java Distribution (Mirror)

The Bouncy Castle Crypto Package For Java The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms, it was developed by t

Legion of the Bouncy Castle Inc 1.8k Dec 30, 2022