Example usage for org.apache.shiro.mgt DefaultSecurityManager DefaultSecurityManager

List of usage examples for org.apache.shiro.mgt DefaultSecurityManager DefaultSecurityManager

Introduction

In this page you can find the example usage for org.apache.shiro.mgt DefaultSecurityManager DefaultSecurityManager.

Prototype

public DefaultSecurityManager(Collection<Realm> realms) 

Source Link

Document

Supporting constructor for multiple #setRealms realms .

Usage

From source file:b4f.seguridad.SecurityAuthenticator.java

@Override
public AuthenticationInfo authenticate(AuthenticationToken at) throws AuthenticationException {

    if (DEBUG) {//w w w  .j  a  v a2  s  . c om
        System.out.println("[SECURITY AUTHENTICATOR] Autenticando: " + at);
    }

    //SE ACCEDI CON UN JWT TOKEN
    if (at instanceof JwtToken) {
        JwtToken authToken = (JwtToken) at;
        if (authToken.getToken() != null && !authToken.getToken().equals("")) {

            if (!authToken.validar()) {
                throw new AccountException("Token invalido.");
            }

            try {
                Usuario user = UsersManager.getUser(authToken.getUser());
                if (user == null)
                    throw new Exception("Token invalido");

                SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo();
                authenticationInfo.setPrincipals(new SimplePrincipalCollection(user, user.getUsuario()));
                return authenticationInfo;
            } catch (Exception ex) {
                Logger.getLogger(ShiroAuthorizingRealm.class.getName()).log(Level.SEVERE, null, ex);
                throw new AuthenticationException(ex.getMessage());
            }

        } else {
            throw new AccountException("Token invalido.");
        }
    }

    DefaultSecurityManager dsm = new DefaultSecurityManager(getRealm());
    AuthenticationInfo authenticationInfo = dsm.authenticate(at);
    if (DEBUG) {
        System.out.println("[SECURITY AUTHENTICATOR] " + authenticationInfo);
    }
    return authenticationInfo;

}

From source file:ch.reboundsoft.shinobi.authstore.secman.ShinobiSecurityManagerImpl.java

@Inject
ShinobiSecurityManagerImpl(ShinobiRealm realm) {
    this.securityManager = new DefaultSecurityManager(realm.getRealm());
}

From source file:cnki.shiro.helloworld.JdbcRelamTest.java

public static void main(String[] args) {

    System.out.println("Hello shiro!");

    MysqlDataSource datasource = new MysqlDataSource();

    datasource.setUser("cnki");

    datasource.setPassword("cnki");

    datasource.setServerName("192.168.100.51");

    // datasource.setDriverClassName("com.mysql.jdbc.Driver");

    datasource.setUrl("jdbc:mysql://192.168.100.51:3306/test");

    // datasource.setMaxActive(10);

    org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm = new JdbcRealm();

    jdbcRealm.setDataSource(datasource);

    jdbcRealm.setPermissionsLookupEnabled(true);

    jdbcRealm.setAuthenticationQuery("SELECT PASSWORD FROM account WHERE name = ?");

    jdbcRealm.setUserRolesQuery(/*from  ww  w.ja va 2 s .  c om*/
            "SELECT NAME FROM role WHERE id =(SELECT roleId FROM account_role WHERE userId = (SELECT id FROM account WHERE NAME = ?))");

    jdbcRealm.setPermissionsQuery(
            "SELECT NAME FROM permission WHERE id in (SELECT permissionId FROM permission_role WHERE (SELECT id FROM role WHERE NAME = ?))");

    DefaultSecurityManager security = new DefaultSecurityManager(jdbcRealm);

    SecurityUtils.setSecurityManager(security);
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {

        UsernamePasswordToken token = new UsernamePasswordToken("ynp", "2222");

        token.setRememberMe(true);
        try {
            currentUser.login(token);

            System.out.println("login successfully");

        } catch (UnknownAccountException uae) {

            System.out.println("There is no user with username of " + token.getPrincipal());

        } catch (IncorrectCredentialsException ice) {

            System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");

        } catch (LockedAccountException lae) {

            System.out.println("The account for username " + token.getPrincipal() + " is locked.  " +

                    "Please contact your administrator to unlock it.");

        }

        // ... catch more exceptions here (maybe custom ones specific to
        // your application?

        catch (AuthenticationException ae) {

            // unexpected condition? error?

        }

    }

    // say who they are:

    // print their identifying principal (in this case, a username):

    System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");

    // test a role:

    if (currentUser.hasRole("admin")) {

        System.out.println("May the admin be with you!");

    } else {

        System.out.println("Hello, mere mortal.");

    }

    // test a typed permission (not instance-level)

    if (currentUser.isPermitted("write")) {
        System.out.println("You can write!.");
    } else {

        System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
    }

    // a (very powerful) Instance Level permission:

    if (currentUser.isPermitted("winnebago:drive:eagle5")) {

        System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +

                "Here are the keys - have fun!");

    } else {

        System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");

    }

    // all done - log out!

    currentUser.logout();

}

From source file:com.esha.dropwizard.stormpath.shiro.StormpathShiroBundle.java

License:Apache License

private SecurityManager buildSecurityManager(final StormpathShiroConfiguration config,
        final Optional<GroupPermissionResolver> groupPermissionResolver,
        final Optional<GroupRoleResolver> groupRoleResolver) {

    final ApplicationRealm applicationRealm = new ApplicationRealm();
    applicationRealm.setApplicationRestUrl(config.getApplicationRestUrl());
    applicationRealm.setClient(getClient());

    if (groupPermissionResolver.isPresent()) {
        applicationRealm.setGroupPermissionResolver(groupPermissionResolver.get());
    }//from www  .  j  a va2 s  .c o m

    if (groupRoleResolver.isPresent()) {
        applicationRealm.setGroupRoleResolver(groupRoleResolver.get());
    }

    final DefaultSecurityManager securityManager = new DefaultSecurityManager(applicationRealm);
    ((DefaultSessionStorageEvaluator) ((DefaultSubjectDAO) securityManager.getSubjectDAO())
            .getSessionStorageEvaluator()).setSessionStorageEnabled(config.isSessionStorageEnabled());
    return securityManager;
}

From source file:com.gemstone.gemfire.internal.security.GeodeSecurityUtil.java

License:Apache License

/**
 * initialize Shiro's Security Manager and Security Utilities
 *//* w  w w .  j a  va 2  s  .  c o m*/
public static void initSecurity(Properties securityProps) {
    if (securityProps == null) {
        return;
    }

    String shiroConfig = securityProps.getProperty(SECURITY_SHIRO_INIT);
    String securityConfig = securityProps.getProperty(SECURITY_MANAGER);
    String clientAuthenticatorConfig = securityProps.getProperty(SECURITY_CLIENT_AUTHENTICATOR);
    String peerAuthenticatorConfig = securityProps.getProperty(SECURITY_PEER_AUTHENTICATOR);

    if (!StringUtils.isBlank(shiroConfig)) {
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:" + shiroConfig);

        // we will need to make sure that shiro uses a case sensitive permission resolver
        Section main = factory.getIni().addSection("main");
        main.put("geodePermissionResolver",
                "com.gemstone.gemfire.internal.security.shiro.GeodePermissionResolver");
        if (!main.containsKey("iniRealm.permissionResolver")) {
            main.put("iniRealm.permissionResolver", "$geodePermissionResolver");
        }

        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        isIntegratedSecurity = true;
    }
    // only set up shiro realm if user has implemented SecurityManager
    else if (!StringUtils.isBlank(securityConfig)) {
        securityManager = getObjectOfTypeFromClassName(securityConfig, SecurityManager.class);
        securityManager.init(securityProps);
        Realm realm = new CustomAuthRealm(securityManager);
        org.apache.shiro.mgt.SecurityManager shiroManager = new DefaultSecurityManager(realm);
        SecurityUtils.setSecurityManager(shiroManager);
        isIntegratedSecurity = true;
    } else if (!StringUtils.isBlank(clientAuthenticatorConfig)) {
        isClientAuthenticator = true;
    } else if (!StringUtils.isBlank(peerAuthenticatorConfig)) {
        isPeerAuthenticator = true;
    } else {
        isIntegratedSecurity = false;
        isClientAuthenticator = false;
        isPeerAuthenticator = false;
    }

    // this initializes the post processor
    String customPostProcessor = securityProps.getProperty(SECURITY_POST_PROCESSOR);
    if (!StringUtils.isBlank(customPostProcessor)) {
        postProcessor = getObjectOfTypeFromClassName(customPostProcessor, PostProcessor.class);
        postProcessor.init(securityProps);
    } else {
        postProcessor = null;
    }
}

From source file:com.monkeyk.os.web.ShiroTest.java

License:Open Source License

@Test(enabled = false)
public void login() {
    String username = "abc";
    //init SecurityManager
    SimpleAccountRealm realm = new SimpleAccountRealm("simple-realm");
    realm.addAccount(username, "abc", "USER");

    SimpleAccountRealm realm2 = new SimpleAccountRealm("simple-realm2");
    realm2.addAccount(username, "abc", "USER", "ADMIN");

    List<Realm> realmList = new ArrayList<>();
    realmList.add(realm);//  w  w  w .  j  av  a  2 s  .c  o m
    realmList.add(realm2);

    SecurityManager securityManager = new DefaultSecurityManager(realmList);
    SecurityUtils.setSecurityManager(securityManager);

    UsernamePasswordToken token = new UsernamePasswordToken(username, "abcdd");

    final Subject subject = SecurityUtils.getSubject();
    subject.login(token);

    final Subject subject1 = SecurityUtils.getSubject();
    assertTrue(subject1.isAuthenticated());

    assertFalse(subject1.isPermitted("OK"));
    assertTrue(subject1.hasRole("USER"));

    //        assertTrue(subject1.isPermitted("USER:c,u"));

}

From source file:com.ning.billing.server.security.TestKillbillJdbcRealm.java

License:Apache License

@Override
@BeforeMethod(groups = "slow")
public void beforeMethod() throws Exception {

    super.beforeMethod();

    // Create the tenant
    final CacheControllerDispatcher controllerDispatcher = new CacheControllerDispatcher();
    final DefaultTenantDao tenantDao = new DefaultTenantDao(getDBI(), clock, controllerDispatcher,
            new DefaultNonEntityDao(getDBI()));
    tenant = new DefaultTenant(UUID.randomUUID(), null, null, UUID.randomUUID().toString(),
            UUID.randomUUID().toString(), UUID.randomUUID().toString());
    tenantDao.create(new TenantModelDao(tenant), internalCallContext);

    // Setup the security manager
    final BoneCPConfig dbConfig = new BoneCPConfig();
    dbConfig.setJdbcUrl(getDBTestingHelper().getJdbcConnectionString());
    dbConfig.setUsername(MysqlTestingHelper.USERNAME);
    dbConfig.setPassword(MysqlTestingHelper.PASSWORD);

    final KillbillJdbcRealm jdbcRealm;
    jdbcRealm = new KillbillJdbcRealm();
    jdbcRealm.setDataSource(new BoneCPDataSource(dbConfig));

    securityManager = new DefaultSecurityManager(jdbcRealm);
}

From source file:com.snail.controller.test.JdbcReamTest.java

public static void main(String[] args) {

    System.out.println("Hello shiro!");

    MysqlDataSource datasource = new MysqlDataSource();
    datasource.setUser("root");
    datasource.setPassword("12345");
    datasource.setServerName("localhost");
    // datasource.setDriverClassName("com.mysql.jdbc.Driver");
    datasource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8");
    // datasource.setMaxActive(10);

    org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm = new JdbcRealm();
    jdbcRealm.setDataSource(datasource);
    jdbcRealm.setPermissionsLookupEnabled(true);
    jdbcRealm.setAuthenticationQuery("SELECT password FROM users WHERE username = ?");
    jdbcRealm.setUserRolesQuery("SELECT rolename FROM user_roles WHERE username= ?");
    jdbcRealm.setPermissionsQuery("SELECT permission FROM user_permissions WHERE rolename= ?");
    //      jdbcRealm
    //            .setPermissionsQuery("SELECT NAME FROM permission WHERE id in (SELECT permissionId FROM permission_role WHERE (SELECT id FROM role WHERE NAME = ?))");
    DefaultSecurityManager security = new DefaultSecurityManager(jdbcRealm);
    SecurityUtils.setSecurityManager(security);
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {
        //lilei//from  w ww.j  ava  2s.c  o m
        UsernamePasswordToken token = new UsernamePasswordToken("lilei", "1234");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
            System.out.println("login successfully");
        } catch (UnknownAccountException uae) {
            System.out.println("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            System.out.println("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to
        // your application?
        catch (AuthenticationException ae) {
            // unexpected condition? error?
        }
    }
    // say who they are:
    // print their identifying principal (in this case, a username):
    System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    // test a role:
    if (currentUser.hasRole("admin")) {
        System.out.println("May the admin be with you!");
    } else {
        System.out.println("Hello, mere mortal.");
    }

    // test a typed permission (not instance-level)

    if (currentUser.isPermitted("write")) {
        System.out.println("You can write!.");
    } else {

        System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
    }
    // a (very powerful) Instance Level permission: TODO
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }
    // all done - log out!
    currentUser.logout();
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

License:Open Source License

private DefaultSecurityManager buildSecurityManager() {
    DefaultSecurityManager newSecurityManager = new DefaultSecurityManager(new WTRealm());
    newSecurityManager.setCacheManager(new MemoryConstrainedCacheManager());
    DefaultSessionManager sessionManager = (DefaultSessionManager) newSecurityManager.getSessionManager();
    sessionManager.setGlobalSessionTimeout(-1);
    sessionManager.setDeleteInvalidSessions(false);
    sessionManager.setSessionValidationSchedulerEnabled(false);
    return newSecurityManager;
}

From source file:com.vectorization.server.node.AppInjector.java

License:Open Source License

@Singleton
@Provides
SecurityManager provideSecurityManager(Realm realm) {
    return new DefaultSecurityManager(realm);
}