Reputation: 313
I'm newer in Apache Shiro, and I want to make a simple example using programmatic configuration. When using the file.INI it is simple to create users and grant them roles and permissons, now, I want to make the same thing but with using simple java objects. So how can I do that please?
Here is my code:
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." );
}
}
}
I need your help and thank you in advance.
Upvotes: 1
Views: 614
Reputation: 3638
Have you already tryed this?
Ini ini=new Ini();
Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME);
section.put("guest", "guest, guest");
section.put("lonestarr", "vespa, goodguy");
I got it from here.
Upvotes: 3