如何切换禁用/启用shiro身份验证?

时间:2017-02-28 11:19:11

标签: rest dropwizard shiro

有没有办法在我的REST服务中切换开关认证? 我目前正在使用带有shiro的dropwizard来进行我的REST服务? 另外我如何确认shiro被禁用?

我也有一个shiro.ini文件,但是我可以包含哪些设置来切换shiro身份验证吗?

@Override
protected ShiroConfiguration narrow(T configuration) {
    return configuration.getShiroConfiguration();
}

@Override
protected Filter createFilter(T configuration) {
    IniWebEnvironment shiroEnv = new IniWebEnvironment();
    shiroEnv.setConfigLocations(this.narrow(configuration).iniConfigs());
    shiroEnv.init();

    return new AbstractShiroFilter() {
        public void init() throws Exception {
            Collection<Realm> realms = MyShiroBundle.this.createRealms(configuration);

            DefaultWebSecurityManager webSecurityManager =
                    (DefaultWebSecurityManager)shiroEnv.getWebSecurityManager();

            if (webSecurityManager.getRealms() != null) {
                webSecurityManager.setRealms(mergeRealms(webSecurityManager.getRealms(), realms));
            } else {
                webSecurityManager.setRealms(realms);
            }

            this.setSecurityManager(webSecurityManager);
            this.setFilterChainResolver(shiroEnv.getFilterChainResolver());
        }
    };
}

@Override
protected Collection<Realm> createRealms(T configuration) {
    return mergeRealms(super.createRealms(configuration), Collections.singleton(createJdbcRealm(configuration)));
}

private static Collection<Realm> mergeRealms(Collection<Realm> realms, Collection<Realm> realms2) {
    return ImmutableList.<Realm>builder().addAll(realms).addAll(realms2).build();
}

private static Realm createJdbcRealm(ReferenceDataConfiguration configuration) {
    DataSource ds = configuration.getMyDatabaseDataSourceFactory().build(new MetricRegistry(), "my-shiro");
    JdbcRealm realm = new JdbcRealm();
    realm.setDataSource(ds);
    realm.setPermissionsLookupEnabled(false);
    realm.setCredentialsMatcher(new AllowAllCredentialsMatcher());
    realm.setAuthenticationQuery(
            "select UserId from AppUser where IsActive = 1 and UserId = ?");
    realm.setUserRolesQuery("select Role from UserRoles where UserId = ? and ValidToTime = " + VALID_TIME);
    realm.setPermissionsQuery(
            "select Permission from RolesPermissions where Role = ? and ValidToTime = " + VALID_TIME);
    return realm;
}

0 个答案:

没有答案