如何在Apache Shiro中使用编程配置创建新帐户?

时间:2015-08-25 21:44:15

标签: java apache java-ee ini shiro

我是Apache Shiro的新手,我想用编程配置做一个简单的例子。当使用file.INI时,创建用户并授予他们角色和权限很简单,现在,我想使用简单的java对象做同样的事情。那我该怎么办呢?

这是我的代码:

import org.apache.shiro.SecurityUtils; 
import org.apache.shiro.authc.*; 
import org.apache.shiro.config.Ini; 
import org.apache.shiro.config.Ini.Section; 
import org.apache.shiro.config.IniSecurityManagerFactory; 
import org.apache.shiro.mgt.SecurityManager; 
import org.apache.shiro.session.Session; 
import org.apache.shiro.subject.Subject; 
import org.apache.shiro.util.Factory; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

public class TestShiro { 

    //private static final transient Logger log = LoggerFactory.getLogger(TestShiro.class); 

    public static void main(String[] args) { 
        //Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); 
    Ini ini = new Ini(); 
    //HERE I SHOULD ADD ACCOUNTS TO MY OBJECT ini
    Factory<SecurityManager> factory = new IniSecurityManagerFactory(ini); 
    Factory<SecurityManager> factory = new IniSecurityManagerFactory(ini); 
        SecurityManager securityManager = factory.getInstance(); 
        SecurityUtils.setSecurityManager(securityManager); 
        Subject currentUser = SecurityUtils.getSubject(); 

        if ( !currentUser.isAuthenticated() ) { 
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarrn", "vespaa"); 

            //this is all you have to do to support 'remember me' (no config - built in!): 
            token.setRememberMe(true); 
            try { 
                currentUser.login( token ); 
            } catch ( UnknownAccountException uae ) { 
            } catch ( IncorrectCredentialsException ice ) { 
            } catch ( LockedAccountException lae ) { 
            } 
             catch ( AuthenticationException ae ) { 
            } 

        } 

        if ( currentUser.hasRole( "schwartz" ) ) { 
            System.out.println("May the Schwartz be with you!" ); 
        } else { 
            System.out.println( "Hello, mere mortal." ); 
        } 

    } 
} 

我需要你的帮助,并提前感谢你。

1 个答案:

答案 0 :(得分:3)

你有没有试过这个?

Ini ini=new Ini();
Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME);
section.put("guest", "guest, guest");
section.put("lonestarr", "vespa, goodguy");

我是从here获得的。