【问题标题】:How to create a new Account using programmatic configuration in Apache Shiro?如何在 Apache Shiro 中使用编程配置创建新帐户?
【发布时间】:2015-11-19 18:49:50
【问题描述】:

我是 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." ); 
        } 

    } 
} 

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

【问题讨论】:

    标签: java apache jakarta-ee ini shiro


    【解决方案1】:

    你试过了吗?

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

    我是从here 那里得到的。

    【讨论】:

      猜你喜欢
      • 2019-06-29
      • 2016-03-07
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      • 2020-05-13
      • 2011-08-18
      • 1970-01-01
      相关资源
      最近更新 更多