Blog do projektu Open Source JavaHotel

niedziela, 26 maja 2013

Shiro, customized realm

Introduction
Shiro is very flexible and easy to extend security framework. But creating a custom realm is not  an easy task for the beginners. After some research I created a simple Shiro project to get the gist of the problem.
  1. Authentication using standard text based realm.
  2. The same using customized realm.
  3. The same using injected realm
The source code is available here (in shape of JUnit test case)
JUnit test case
The purpose is to run the same test case but using different realms. Source code.
 private void testShiro(String realM) {
        Factory factory = new IniSecurityManagerFactory(
                realM);
        org.apache.shiro.mgt.SecurityManager securityManager = factory
                .getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        ...........
        test scenario
        ...........


    @Test
    public void test() {
        testShiro("classpath:shiro.ini");
    }

    @Test
    public void test1() {
        testShiro("classpath:custom.ini");
    }

    @Test
    public void test2() {
        testShiro("classpath:inject.ini");
    }

Important: Although test, test1 and test2 are included in one test suite every test should be performed independently. This is because the next test utilize the realm created in the previous test if run inside the same JVM. I did not find a simple way to overcome it.
Standard text based realm
shiro.ini
[users]
root = secret, admin
guest = secret, welcome
Customized realm
custom.ini
[main]
myRealm=com.custom.realm.MyRealm
com.custom.realm.MyRealm
Customized realm with injection
This example is a little more complicated because mini framework has been created. The "framework" contains custom realm and interface.

package com.custom.nextrealm;

import java.util.List;

public interface InjectCredentials {

    String getPerson();
    
    String getPassword();
    
    List getRoles();

}
The user can customize this customized realm by implementing this interface and providing login name, password and list of roles without bothering about all others details. The example of this customization for the purpose of the test :
inject.ini
[main]
myRealm=com.custom.nextrealm.MyRealm
inject=com.custominject.CustomCredentials
myRealm.iCrede=$inject
com.custominject.CustomCredentials

package com.custominject;
import java.util.ArrayList;
import java.util.List;

import com.custom.nextrealm.InjectCredentials;

public class CustomCredentials implements InjectCredentials {

    @Override
    public String getPerson() {
        return "guest";
    }

    @Override
    public String getPassword() {
        return "secret";
    }

    @Override
    public List<String> getRoles() {
        List<String> roles = new ArrayList<String>();
        roles.add("welcome");
        return roles;
    }

}

Brak komentarzy:

Prześlij komentarz