shiroapi-key

API Key implementation in Apache Shiro


I have Java web application which implemented Apache shiro Authentication & Authorization.

Now i need to implement API Key to the existing project (which has apache shiro). Please help me on implementation part. Even i could not find any documentation

PS:: We have already implemented 3 different types of Custom Realm(jdbc,ldap,Pac4jRealm) but now struggling to implement the API key concept with Apache Shiro.


Solution

  • I resolved the above issue by extending the JDBCRealm,see the below example code

    public class APIRealm extends JdbcRealm {
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    
            SimpleAuthorizationInfo info = null;
            AuthAPIInfo authInfo = null;
            try {
            String apiKey= (String) principals.getPrimaryPrincipal();
            authInfo=fetchAPIKeyInfo(apiName);
    
            // Do all the other stuff like checking for Authorization and setting it to token
    
            } catch (Exception e) {
                insertAPILogActivity(authInfo, "User not authorized");
            }
            return info;
    
        }
    
    private AuthAPIInfo fetchAPIKeyInfo(String apiKeyName) {
        //Connect to Database using JDBC connection and validate the API Key and return the AuthAPIInfo
    }
    
    }
    

    Add the above realm in shiro.ini

    apiRealm=com.example.APIRealm
    securityManager.realms=$apiRealm