skip to Main Content

I am developing a web-based application in Spring boot and Mongo DB. Now I want to use Apache Shiro for Authentication and Authorisation. Can somebody explain to me the procedure and how to establish a mongo db realm and where to mention the permission-user mapping? Thank You.

2

Answers


  1. There are a few MongoDB realms up on GitHub. I don’t want to link to them as haven’t tried them out, but that would be your best place to start.

    Login or Signup to reply.
  2. Basically you need three component

    @Component
    public class YourMongoConfiguration {
        @Bean(name = "mongoTemplate")
        @DependsOn({ "lifecycleBeanPostProcessor" })
        public MongoTemplate mongoTemplate() throws Exception {
            MongoTemplate mt = new MongoTemplate(YOUR_CONFIGURATIOP_HERE);
            return mt;
        }
    }
    

    Then a MongoRealm

    @Component("mongoRealm")
    public class MongoRealm extends AuthorizingRealm {
        private final MongoTemplate mongoTemplate;
    
        @Autowired
        public MongoRealm(MongoTemplate mongoTemplate) {
            this.mongoTemplate = mongoTemplate;
            HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
            credentialsMatcher.setHashAlgorithmName(Sha512Hash.ALGORITHM_NAME);
            credentialsMatcher.setHashIterations(53);
            setCredentialsMatcher(credentialsMatcher);
        }
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
          // YOUR IMPLEMENTATION
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) 
    throws AuthenticationException {
        // YOUR IMPLEMENTATION
        }
    }
    

    and finally a security manager

    @Component("securityManager")
    public class SecurityManager extends DefaultWebSecurityManager {
        @Autowired
        public SecurityManager(Realm mongoRealm, SessionDAO mongoSessionDAO) {
            super(mongoRealm);
            setRealm(mongoRealm);
            SessionManager sessionManager = new SessionManager();
            setSessionManager(sessionManager);
            sessionManager.setSessionDAO(mongoSessionDAO);
        }
    }
    

    From now on either Shiro will call your MongoRealm to validate login and permission and you will be able to hadle your collection with classes like

    @Service
    public class ONE_OF_YOUR_Services  {
        @Autowired
        private MongoTemplate mongoTemplate;
    
        protected List<T> getDocuments(Class<T> clazz, String collection) {
            return mongoTemplate.findAll(clazz, collection);
        }
    }
    

    I hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search