关闭

使用shrio保护spring 应用

505人阅读 评论(0) 收藏 举报
分类:
第一步:引入Shiro的依赖
 
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.2.3</version>
</dependency>
第二步:使用AutoConfiguration方式注入
 
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter() {
    ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
    shiroFilter.setLoginUrl("/login");
    shiroFilter.setSuccessUrl("/index");
    shiroFilter.setUnauthorizedUrl("/forbidden");
    Map<String, String> filterChainDefinitionMapping = new HashMap<String, String>();
    filterChainDefinitionMapping.put("/", "anon");
    filterChainDefinitionMapping.put("/home", "authc,roles[guest]");
    filterChainDefinitionMapping.put("/admin", "authc,roles[admin]");
    shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMapping);
    shiroFilter.setSecurityManager(securityManager());
    Map<String, Filter> filters = new HashMap<String, Filter>();
    filters.put("anon", new AnonymousFilter());
    filters.put("authc", new FormAuthenticationFilter());
    filters.put("logout", new LogoutFilter());
    filters.put("roles", new RolesAuthorizationFilter());
    filters.put("user", new UserFilter());
    shiroFilter.setFilters(filters);
    System.out.println(shiroFilter.getFilters().size());
    return shiroFilter;
}

@Bean(name = "securityManager")
public SecurityManager securityManager() {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(realm());
    return securityManager;
}

@Bean(name = "realm")
@DependsOn("lifecycleBeanPostProcessor")
public PropertiesRealm realm() {
    PropertiesRealm propertiesRealm = new PropertiesRealm();
    propertiesRealm.init();
    return propertiesRealm;
}

@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
    return new LifecycleBeanPostProcessor();
}
第三步:使用Shiro的PropertiesRealm作为认证和授权管理器,所以添加classpath:/shiro-users.properties,格式为user.username = password,role1,role1,... 
user.admin = 567890,admin,guest
user.lenic = 123456,guest
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:94006次
    • 积分:2002
    • 等级:
    • 排名:第19978名
    • 原创:128篇
    • 转载:17篇
    • 译文:8篇
    • 评论:12条
    最新评论