org.apache.shiro.mgt.DefaultSecurityManager Java Examples

The following examples show how to use org.apache.shiro.mgt.DefaultSecurityManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseShiroTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
@DisplayName("基本认证测试例")
public void testAuthentication() {

    // 构建 SecurityManager
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    defaultSecurityManager.setRealm(simpleAccountRealm);

    // Subject 提交认证请求
    SecurityUtils.setSecurityManager(defaultSecurityManager); // 设置 SecurityManager
    Subject subject = SecurityUtils.getSubject(); // 获取当前 Subject

    // 登录
    UsernamePasswordToken token = new UsernamePasswordToken("root", "root");
    subject.login(token);

    // subject.isAuthenticated() 用于判断用户是否认证成功
    System.out.println("isAuthenticated:" + subject.isAuthenticated());
    Assertions.assertTrue(subject.isAuthenticated());

    // 登出
    subject.logout();

    System.out.println("isAuthenticated:" + subject.isAuthenticated());
    Assertions.assertFalse(subject.isAuthenticated());
}
 
Example #2
Source File: TestSecurityProvider.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public PrivateModule provideAdditionalSecurityModule() {
    return new ShiroModule() {
        @Override
        protected void configureShiro() {
            try {
                bind(org.apache.shiro.mgt.SecurityManager.class)
                        .annotatedWith(Names.named("test"))
                        .toConstructor(DefaultSecurityManager.class.getConstructor(Collection.class))
                        .asEagerSingleton();
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Internal error", e);
            }

            expose(SecurityManager.class).annotatedWith(Names.named("test"));
        }
    };
}
 
Example #3
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizationValid() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Principal principal = Mockito.mock(Principal.class);
    Mockito.when(principal.getName()).thenReturn("test-user");
    Mockito.when(req.getUserPrincipal()).thenReturn(principal);
    String jwt = new ShiroJwtProvider(Mockito.mock(AppContext.class)).getJwt(req);
    Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer " + jwt);
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isTrue();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #4
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization3() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);

    Mockito
        .when(req.getHeader("Authorization"))
        .thenReturn(
            "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.neIA5mbTFZsZokqG5CFwK7gIxMiBoGOU0anDZmD7kkU");

    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #5
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization2() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer eyJhbGciOiJIUzI1NiJ9");
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #6
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization1() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer ");
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #7
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization0() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getHeader("Authorization")).thenReturn("junk");
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #8
Source File: ShiroAutoConfiguration.java    From shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Bean(name = "shiroFilter")
@DependsOn("securityManager")
@ConditionalOnMissingBean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultSecurityManager securityManager, Realm realm, ShiroFilterRegistry registry) {
	securityManager.setRealm(realm);

       Map<String, String> filterDef = swapKeyValue(properties.getFilterChainDefinitions());
       log.info("过虑器配置: {}", filterDef);
       log.info("自定义过虑器: {}", registry.getFilterMap());

	ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
	shiroFilter.setSecurityManager(securityManager);
	shiroFilter.setLoginUrl(properties.getLoginUrl());
	shiroFilter.setSuccessUrl(properties.getSuccessUrl());
	shiroFilter.setUnauthorizedUrl(properties.getUnauthorizedUrl());

	shiroFilter.setFilterChainDefinitionMap(filterDef);
       shiroFilter.getFilters().putAll(registry.getFilterMap());

	return shiroFilter;
}
 
Example #9
Source File: ShiroManager.java    From shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Bean(name = "securityManager")
	@ConditionalOnMissingBean
	public DefaultSecurityManager securityManager(CacheManager shiroCacheManager) {
        DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();

        // 用自己的Factory实现替换默认
        // 用于关闭session功能
        dwsm.setSubjectFactory(new StatelessSubjectFactory());
        dwsm.setSessionManager(defaultSessionManager());
        // 关闭session存储
        ((DefaultSessionStorageEvaluator) ((DefaultSubjectDAO)dwsm.getSubjectDAO()).getSessionStorageEvaluator()).setSessionStorageEnabled(false);

//      <!-- 用户授权/认证信息Cache, 采用EhCache 缓存 -->
        dwsm.setCacheManager(shiroCacheManager);

        SecurityUtils.setSecurityManager(dwsm);
        return dwsm;
	}
 
Example #10
Source File: ShiroAuthProvider.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static SecurityManager createSecurityManager(Ini config, Supplier<String> sessionIdGenerator) {
    final Factory<SecurityManager> factory = new IniSecurityManagerFactory(config) {
        @Override
        protected SecurityManager createDefaultInstance() {
            final DefaultSessionManager sessionManager = new DefaultSessionManager();
            // This session DAO is required to cache the session in a very short time, especially while
            // logging in to the Central Dogma server. After that, the general session manager provided
            // by Central Dogma server will be working for the session management.
            sessionManager.setSessionDAO(new LimitedMemorySessionDAO(sessionIdGenerator,
                                                                     64, Duration.ofHours(1)));

            final DefaultSecurityManager securityManager = new DefaultSecurityManager();
            securityManager.setSessionManager(sessionManager);

            return securityManager;
        }
    };
    return factory.getInstance();
}
 
Example #11
Source File: BaseShiroTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
@DisplayName("基本授权测试例")
public void testAuthorization() {

    // 构建 SecurityManager
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    defaultSecurityManager.setRealm(simpleAccountRealm);

    // Subject 提交认证请求
    SecurityUtils.setSecurityManager(defaultSecurityManager); // 设置 SecurityManager
    Subject subject = SecurityUtils.getSubject(); // 获取当前 Subject

    // 登录
    UsernamePasswordToken token = new UsernamePasswordToken("root", "root");
    subject.login(token);

    // subject.isAuthenticated() 用于判断用户是否认证成功
    System.out.println("isAuthenticated:" + subject.isAuthenticated());
    Assertions.assertTrue(subject.isAuthenticated());

    // 判断 subject 是否具有 admin 和 user 两个角色权限,如没有则会报错
    subject.checkRoles("admin", "user");
    Assertions.assertTrue(subject.hasRole("admin"));
    Assertions.assertTrue(subject.hasRole("user"));
    Assertions.assertFalse(subject.hasRole("xxx"));

    Assertions.assertTrue(subject.hasAllRoles(Arrays.asList("admin", "user")));
    Assertions.assertFalse(subject.hasAllRoles(Arrays.asList("admin", "user", "xxx")));
}
 
Example #12
Source File: MongoServer.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public void startServer() {

        if ( ( properties != null ) && ( Boolean
                .parseBoolean( properties.getProperty( "usergrid.mongo.disable", "false" ) ) ) ) {
            logger.info( "Usergrid Mongo Emulation Server Disabled" );
            return;
        }

        logger.info( "Starting Usergrid Mongo Emulation Server" );

        if ( realm != null ) {
            securityManager = new DefaultSecurityManager( realm );
        }

        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool() ) );

        bootstrap.setOption( "child.bufferFactory", HeapChannelBufferFactory.getInstance( ByteOrder.LITTLE_ENDIAN ) );

        // Set up the pipeline factory.
        ExecutionHandler executionHandler =
                new ExecutionHandler( new OrderedMemoryAwareThreadPoolExecutor( 16, 1048576, 1048576 ) );
        // TODO if config'ed for SSL, start the SslMSPF instead, change port as well?
        bootstrap.setPipelineFactory(
                new MongoServerPipelineFactory( emf, smf, management, securityManager, executionHandler ) );

        // Bind and start to accept incoming connections.
        channel = bootstrap.bind( new InetSocketAddress( 27017 ) );

        logger.info( "Usergrid Mongo API Emulation Server accepting connections..." );
    }
 
Example #13
Source File: WebSocketServer.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public void startServer() {
    if ( ( properties != null ) && ( Boolean
            .parseBoolean( properties.getProperty( "usergrid.websocket.disable", "false" ) ) ) ) {
        logger.info( "Usergrid WebSocket Server Disabled" );
        return;
    }

    logger.info( "Starting Usergrid WebSocket Server" );

    if ( realm != null ) {
        securityManager = new DefaultSecurityManager( realm );
    }

    ServerBootstrap bootstrap = new ServerBootstrap(
            new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool() ) );

    // Set up the pipeline factory.
    ExecutionHandler executionHandler =
            new ExecutionHandler( new OrderedMemoryAwareThreadPoolExecutor( 16, 1048576, 1048576 ) );

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(
            new WebSocketServerPipelineFactory( emf, smf, management, securityManager, executionHandler, ssl ) );

    // Bind and start to accept incoming connections.
    channel = bootstrap.bind( new InetSocketAddress( 8088 ) );

    logger.info( "Usergrid WebSocket Server started..." );
}
 
Example #14
Source File: SecurityModule.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void bindSecurityManager(AnnotatedBindingBuilder<? super SecurityManager> bind) {
	try {
		bind.toConstructor(DefaultSecurityManager.class.getConstructor(Collection.class)).asEagerSingleton();
  } catch (NoSuchMethodException e) {
      throw new ConfigurationException("This really shouldn't happen.  Either something has changed in Shiro, or there's a bug in " + ShiroModule.class.getSimpleName(), e);
  }
}
 
Example #15
Source File: ShiroAutoConfiguration.java    From shiro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean(name = "shiroFilter")
@DependsOn("securityManager")
@ConditionalOnMissingBean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultSecurityManager securityManager, Realm realm) {
	securityManager.setRealm(realm);

	ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
	shiroFilter.setSecurityManager(securityManager);
	shiroFilter.setLoginUrl(properties.getLoginUrl());
	shiroFilter.setSuccessUrl(properties.getSuccessUrl());
	shiroFilter.setUnauthorizedUrl(properties.getUnauthorizedUrl());
	shiroFilter.setFilterChainDefinitionMap(properties.getFilterChainDefinitionMap());
	return shiroFilter;
}
 
Example #16
Source File: ShiroManager.java    From shiro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultSecurityManager securityManager) {
	AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
	aasa.setSecurityManager(securityManager);
	return new AuthorizationAttributeSourceAdvisor();
}
 
Example #17
Source File: ShiroManager.java    From shiro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean(name = "securityManager")
@ConditionalOnMissingBean
public DefaultSecurityManager securityManager(CacheManager shiroCacheManager) {
	DefaultSecurityManager sm = new DefaultWebSecurityManager();
	sm.setCacheManager(shiroCacheManager);
	return sm;
}
 
Example #18
Source File: ShiroConfiguration.java    From sso with MIT License 5 votes vote down vote up
/**
 * 对过滤器进行调整
 *
 * @return
 */
@Bean
protected ShiroFilterFactoryBean shiroFilterFactoryBean() {
    //把subject对象设为subjectFactory
    //由于cas代理了用户,所以必须通过cas进行创建对象
    ((DefaultSecurityManager) securityManager).setSubjectFactory(new Pac4jSubjectFactory());

    ShiroFilterFactoryBean filterFactoryBean = super.shiroFilterFactoryBean();
    filterFactoryBean.setFilters(shiroFilters());
    return filterFactoryBean;
}
 
Example #19
Source File: MyShiroRealmTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void testAuthentication() {

    // 构建 SecurityManager
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    defaultSecurityManager.setRealm(myRealm);

    // Subject 提交认证请求
    SecurityUtils.setSecurityManager(defaultSecurityManager); // 设置 SecurityManager
    Subject subject = SecurityUtils.getSubject(); // 获取当前 Subject

    // 登录
    UsernamePasswordToken token = new UsernamePasswordToken("root", "root");
    subject.login(token);

    // subject.isAuthenticated() 用于判断用户是否认证成功
    System.out.println("isAuthenticated:" + subject.isAuthenticated());
    Assertions.assertTrue(subject.isAuthenticated());

    // 判断 subject 是否是指定的一个或多个角色
    subject.checkRoles("admin", "user");
    Assertions.assertTrue(subject.hasRole("admin"));
    Assertions.assertTrue(subject.hasRole("user"));
    Assertions.assertFalse(subject.hasRole("xxx"));
    Assertions.assertTrue(subject.hasAllRoles(Arrays.asList("admin", "user")));
    Assertions.assertFalse(subject.hasAllRoles(Arrays.asList("admin", "user", "xxx")));

    // 判断 subject 是否是拥有指定的一个或多个权限
    subject.checkPermission("user:add");
    subject.checkPermission("user:delete");
    subject.checkPermissions("user:add", "user:delete");
    Assertions.assertTrue(subject.isPermitted("user:add"));
    Assertions.assertTrue(subject.isPermitted("user:delete"));
    Assertions.assertTrue(subject.isPermittedAll("user:add", "user:delete"));
    Assertions.assertFalse(subject.isPermittedAll("user:add", "user:delete", "user:update"));
}
 
Example #20
Source File: ShiroConfig.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 授权管理器
 * 
 * @time 2018年4月10日 下午5:10:02.
 * 
 * @version V1.0
 * @return DefaultSecurityManager
 */
@Bean(name = "securityManager")
@ConditionalOnMissingBean
public DefaultSecurityManager securityManager() {
	DefaultSecurityManager sm = new DefaultWebSecurityManager();
	sm.setCacheManager(cacheManager());
	sm.setRememberMeManager(rememberMeManager());// 注入记住我
	return sm;
}
 
Example #21
Source File: ShiroManager.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 开启shiro aop注解支持. 使用代理方式;所以需要开启代码支持; Controller才能使用
 * @time 2018年4月10日 下午5:11:39.
 * @version V1.0
 * @param securityManager
 * @return AuthorizationAttributeSourceAdvisor
 */
@Bean
@ConditionalOnMissingBean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(
		DefaultSecurityManager securityManager) {
	AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
	aasa.setSecurityManager(securityManager);
	return new AuthorizationAttributeSourceAdvisor();
}
 
Example #22
Source File: ShiroConfiguration.java    From utils with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultSecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
    aasa.setSecurityManager(securityManager);

    return aasa;
}
 
Example #23
Source File: ShiroConfiguration.java    From utils with Apache License 2.0 5 votes vote down vote up
@Bean(name = "securityManager")
@DependsOn(value = {"cacheManager", "rememberMeManager", "mainRealm"})
public DefaultSecurityManager securityManager(Realm realm, RememberMeManager rememberMeManager, CacheManager cacheManager, SessionManager sessionManager) {
    DefaultSecurityManager sm = new DefaultWebSecurityManager();
    sm.setRealm(realm);
    sm.setCacheManager(cacheManager);
    sm.setSessionManager(sessionManager);
    sm.setRememberMeManager(rememberMeManager);

    return sm;
}
 
Example #24
Source File: ShiroManager.java    From shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultSecurityManager securityManager) {
	AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
	aasa.setSecurityManager(securityManager);
	return new AuthorizationAttributeSourceAdvisor();
}
 
Example #25
Source File: ShiroFilterConfiguration.java    From wolf with MIT License 5 votes vote down vote up
/**
 * 对过滤器进行调整
 *
 * @param securityManager
 * @return
 */
@Bean
protected ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager, SubjectFactory subjectFactory,@Qualifier("filters") Map<String, Filter> filters) {
    //把subject对象设为subjectFactory
    ((DefaultSecurityManager) securityManager).setSubjectFactory(subjectFactory);
    ShiroFilterFactoryBean filterFactoryBean = super.shiroFilterFactoryBean();
    filterFactoryBean.setSecurityManager(securityManager);

    filterFactoryBean.setFilters(filters);
    return filterFactoryBean;
}
 
Example #26
Source File: ShiroConfiguration.java    From spring-boot-shiro with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultSecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
    aasa.setSecurityManager(securityManager);
    return aasa;
}
 
Example #27
Source File: ShiroConfiguration.java    From spring-boot-shiro with Apache License 2.0 5 votes vote down vote up
@Bean(name = "securityManager")
@DependsOn(value = {"cacheManager", "rememberMeManager", "mainRealm"})
public DefaultSecurityManager securityManager(Realm realm, RememberMeManager rememberMeManager,
                                              CacheManager cacheManager, SessionManager sessionManager) {
    DefaultSecurityManager sm = new DefaultWebSecurityManager();
    sm.setRealm(realm);
    sm.setCacheManager(cacheManager);
    sm.setSessionManager(sessionManager);
    sm.setRememberMeManager(rememberMeManager);
    return sm;
}
 
Example #28
Source File: ShiroConfig.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * shiro拦截器
 * 
 * @time 2018年4月10日 下午5:10:12.
 * 
 * @version V1.0
 * @param securityManager
 * @param realm
 * @return ShiroFilterFactoryBean
 */
@Bean(name = "shiroFilter")
@DependsOn("securityManager")
@ConditionalOnMissingBean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultSecurityManager securityManager, Realm realm) {
	securityManager.setRealm(realm);

	ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
	shiroFilter.setSecurityManager(securityManager);
	shiroFilter.setLoginUrl("/admin/login");
	shiroFilter.setSuccessUrl("/admin/index");
	shiroFilter.setUnauthorizedUrl("/assets/401.html");
	Map<String, String> filterChainDefinitionMap = new HashMap<String, String>();
	filterChainDefinitionMap.put("/assets/**", "anon");
	filterChainDefinitionMap.put("/admin/regist", "anon");// 添加
	filterChainDefinitionMap.put("/admin/login", "anon");

	filterChainDefinitionMap.put("/isTrue", "anon"); // 验证码异步验证

	// 个人信息
	filterChainDefinitionMap.put("/admin/info/**", "anon");
	// 自主还书
	filterChainDefinitionMap.put("/admin/borrow/**", "anon");
	filterChainDefinitionMap.put("/admin/user/index", "perms[system:user:index]");
	filterChainDefinitionMap.put("/admin/user/add", "perms[system:user:add]");
	filterChainDefinitionMap.put("/admin/user/edit*", "perms[system:user:edit]");
	filterChainDefinitionMap.put("/admin/user/deleteBatch", "perms[system:user:deleteBatch]");
	filterChainDefinitionMap.put("/admin/user/grant/**", "perms[system:user:grant]");
	filterChainDefinitionMap.put("/admin/user/resume/**", "perms[system:user:resume]");
	// 注册账号验证和添加账号验证
	filterChainDefinitionMap.put("/admin/user/isExist/**", "anon");
	filterChainDefinitionMap.put("/admin/user/isAvailable/**", "anon");
	filterChainDefinitionMap.put("/admin/user/isAllTrue/**", "anon");

	filterChainDefinitionMap.put("/admin/role/index", "perms[system:role:index]");
	filterChainDefinitionMap.put("/admin/role/add", "perms[system:role:add]");
	filterChainDefinitionMap.put("/admin/role/edit*", "perms[system:role:edit]");
	filterChainDefinitionMap.put("/admin/role/deleteBatch", "perms[system:role:deleteBatch]");
	filterChainDefinitionMap.put("/admin/role/grant/**", "perms[system:role:grant]");

	filterChainDefinitionMap.put("/admin/resource/index", "perms[system:resource:index]");
	filterChainDefinitionMap.put("/admin/resource/add", "perms[system:resource:add]");
	filterChainDefinitionMap.put("/admin/resource/edit*", "perms[system:resource:edit]");
	filterChainDefinitionMap.put("/admin/resource/deleteBatch", "perms[system:resource:deleteBatch]");

	filterChainDefinitionMap.put("/druid/", "perms[system:resource:druid]");// druid
	filterChainDefinitionMap.put("/admin/memorandum/*", "perms[system:memorandum:memorandum]");// 系统记录,只使用一个拦截url
	// 添加过滤条件
	filterChainDefinitionMap.put("/admin/books/book_management", "perms[system:books:book_management]");

	filterChainDefinitionMap.put("/admin/**", "user"); // 默认所有均可依靠cookie,本项目隐藏bug,cookie太大,无法保存在浏览器本地
	shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
	return shiroFilter;
}
 
Example #29
Source File: ShiroAuthenticationFeature.java    From aries-jax-rs-whiteboard with Apache License 2.0 4 votes vote down vote up
public ShiroAuthenticationFeature(List<Realm> realms) {
    this.realms = realms;
    this.manager = realms.isEmpty() ? new DefaultSecurityManager() : new DefaultSecurityManager(realms);
}
 
Example #30
Source File: UserLoginInterceptor.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext actionContext=actionInvocation.getInvocationContext();  
	Map<String, Object> session=actionContext.getSession();  
	this.accountObj = (AccountObj)session.get(Constants.SESS_ACCOUNT);
	boolean getUserCurrentCookieFail = false; // 有 sysCurrentId 的 cookie, 但用這個cookie資料count tb_sys_usess 又與 core-web 的資料不符
	/*
	 * String contextPath = ServletActionContext.getServletContext().getContextPath();
	 * if (!contextPath.endsWith( ApplicationSiteUtils.getContextPathFromMap(Constants.getMainSystem()) ) ) {
	 */
	if ( !Constants.getSystem().equals(Constants.getMainSystem()) ) {
		/**
		 * 1. 先用admin登入
		 * 2. 登出admin 改用 tester登入
		 * 這樣的話 gsbsc-web 的 http-session 還是admin , 所以非core-web 要檢查當前CURRENT cookie 中的帳戶是否與 gsbsc-web 一樣
		 * 要是不同的話就讓這個 http-session 失效掉
		 */
		this.invalidCurrentSessionForDifferentAccount(actionContext);								
		if (accountObj==null) {
			getUserCurrentCookie(actionContext);
			if (accountObj==null && UserCurrentCookie.foundCurrent( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) ) ) {
				 // 有 sysCurrentId 的 cookie, 但用這個cookie資料count tb_sys_usess 又與 core-web 的資料不符
				getUserCurrentCookieFail = true;
			}				
		}			
	}
	if (accountObj!=null && !StringUtils.isBlank(accountObj.getAccount()) ) {
		Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
		String currentId = StringUtils.defaultString( dataMap.get("currentId") );
		if ( StringUtils.isBlank(currentId) ) {
			currentId = "NULL";
		}
		if (uSessLogHelper.countByCurrent(accountObj.getAccount(), currentId)<1) {
			return this.redirectLogin(session, getUserCurrentCookieFail);
		}						
		boolean isUnknownSession = false;
		SecurityUtils.setSecurityManager( (DefaultSecurityManager)AppContext.getBean("securityManager") );
		Subject subject = SecurityUtils.getSubject();
		try {
			if (subject.isAuthenticated() && !accountObj.getAccount().equals(subject.getPrincipal()) ) {
				subject.logout();
			}				
		} catch (ExpiredSessionException ese) {
			logger.warn( ese.getMessage().toString() );
			return this.redirectLogin(session, getUserCurrentCookieFail);
		} catch (UnknownSessionException ue) {
			logger.warn( ue.getMessage().toString() );
			isUnknownSession = true;
		}
		
		/**
		 * core-web 有 session了, 但gsbsc-web 沒有session, 所以產生gsbsc-web 的 http session
		 * 或是 apache shiro session 失效 expires
		 */			
		if ( !subject.isAuthenticated() || isUnknownSession ) {
			GreenStepBaseUsernamePasswordToken token = new GreenStepBaseUsernamePasswordToken();
			//token.setRememberMe(true);
			token.setRememberMe(false);
			token.setCaptcha("");
			token.setUsername(accountObj.getAccount());		
			token.setPassword( ((AccountVO)accountObj).getPassword().toCharArray() );
			try {					
				subject.login(token);
			} catch (UnknownAccountException uae) {
				logger.warn( uae.getMessage().toString() );
			    subject = new Subject.Builder().buildSubject();	
			    subject.login(token);
			} catch (UnknownSessionException use) {
				logger.warn( use.getMessage().toString() );
			    subject = new Subject.Builder().buildSubject();					
				/*
				Serializable sessionId = subject.getSession().getId();
				System.out.println("SESSION_ID=" + sessionId);
				subject = new Subject.Builder( (DefaultSecurityManager)AppContext.getBean("securityManager") )
					.sessionId(sessionId)
					.buildSubject();
				*/
			    subject.login(token);		
			} 
			UserAccountHttpSessionSupport.create(actionContext, accountObj);
		}
		return actionInvocation.invoke();
	}	
	return this.redirectLogin(session, getUserCurrentCookieFail);
}