Shiro的简单入门

1、什么是Shiro

shiro (java安全框架)
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

2、快速入门

1、在Github上下载一个简单的Shiro入门案例
https://github.com/apache/shiro
2、下载完之后是一个名为shiro-master.zip的压缩包,解压它
3、解压后在shiro-master\shiro-master\samples目录下找到quickstart,将它导入IDEA
4、简单分析一下Quickstart这个类
(1)

//读取类路径下的shiro.ini文件,创建工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//通过工厂获取安全管理器
SecurityManager securityManager = factory.getInstance();

(2)

//通过当前用户拿到对象  Subject
Subject currentUser = SecurityUtils.getSubject();
//通过当前用户拿到  Session
Session session = currentUser.getSession();

(3)

//可以往session里面存值取值
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
   log.info("Retrieved the correct value! [" + value + "]");
}

(4)

if (!currentUser.isAuthenticated()) {//没有被认证

    //设置令牌  token
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");

    //记住我
    token.setRememberMe(true);
    try {
        currentUser.login(token);//执行了登录操作,需要传入一个令牌token
    } catch (UnknownAccountException uae) {//未知的用户,username = lonestarr, 在ini文件里可以找到这个名字
        log.info("There is no user with username of " + token.getPrincipal());
    } catch (IncorrectCredentialsException ice) {//密码错误
        log.info("Password for account " + token.getPrincipal() + " was incorrect!");
    } catch (LockedAccountException lae) {//多次密码不对,用户就会被锁定
        log.info("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?
    }
}

(5)以下图片是shiro.ini中角色部分内容
admin:有所有的权限
schwartz:拥有 lightsaber : * 的权限,这里*是通配符,schwartz有以lightsaber :开头的所有权限
goodguy:只有 winnebago:drive:eagle5这个具体的权限shiro.ini中的部分内容

//粗粒度的,非实例级别的权限测试,对某一类权限的判断
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
    log.info("You may use a lightsaber ring.  Use it wisely.");
} else {
    log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//细粒度,对某一个具体权限的判断
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
    log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
            "Here are the keys - have fun!");
} else {
    log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

3、在SpringBoot整合Shiro

1、在IDEA创建一个SpringBoot工程

创建SpringBoot项目
勾选上Spring Web以及Thymeleaf(之后会和Thymeleaf整合)

2、导入Shiro的依赖

<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-spring</artifactId>
	<version>1.5.3</version>
</dependency>

3、编写简单的页面和Controller

@Controller
public class ShiroController {

    @RequestMapping({"/", "/index"})
    public String index(Model model){
        model.addAttribute("msg", "Hello Shiro~");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        return "index";
    }

    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unauthorized(){
        return "您没有权限!";
    }
}

页面目录
在这里插入图片描述

4、编写ShiroConfig和UserRealm

在这里插入图片描述

@Configuration
public class ShiroConfig {

	//本质是一个过滤器
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        //暂时没有过滤任何请求
        return bean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象  :用户认证的东西放在UserRealm里
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
}
public class UserRealm extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=====授权方法");
        return null;//返回null表示不进行授权
    }

    //认证:登录的时候认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=====认证方法");
        return null;//返回空表示不进行认证
    }
}

5、实现登录拦截

在ShiroConfig中的getShiroFilterFactoryBean中加入过滤

@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(
				@Autowired DefaultWebSecurityManager securityManager){
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    bean.setSecurityManager(securityManager);

    //添加 shiro的内置过滤器
    /*
        anon:  无需认证就可以访问
        authc: 必须认证了才能访问
        user:  必须 记住我才能访问
        perms: 有用对某个资源的权限才能访问
        role:  拥有对某个角色权限才能访问
    */
    Map<String, String> filterMap = new LinkedHashMap<>();
    
    //无需认证就可以访问/user/add
    filterMap.put("/user/add", "anon");
    //必须认证了才能访问user/update
    filterMap.put("/user/update", "authc");
    //filterMap.put("/user/*", "authc");支持通配符
    
    bean.setFilterChainDefinitionMap(filterMap);

    //和SpringSecurity的setLoginUrl一样
    //当需要验证信息(但是你没有认证)的时候,跳转到登录界面
    bean.setLoginUrl("/toLogin");
   
    return bean;
}

现在可以访问/user/add并跳转到add.html,但是访问/user/update时,会跳到登录界面,需要登录认证后才能访问

6、实现用户认证

在登录时将用户名和密码交给令牌token,并进行认证

@RequestMapping("/login")
public String login(String username, String password, Model model){
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    try{
        subject.login(token);//进行认证
        return "index";
    } catch (UnknownAccountException e){
        model.addAttribute("msg", "用户名或密码错误");
        return "login";
    } catch (IncorrectCredentialsException e){
        model.addAttribute("msg", "用户名或密码错误");
        return "login";
    }
}

具体认证的代码,在UserRealm类的doGetAuthenticationInfo编写

//认证:登录的时候认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    System.out.println("执行了=====认证方法");

    //登录时传进来token中的username和password都可以在token中获取
    UsernamePasswordToken userToken =
            (UsernamePasswordToken) token;
    //在真实开发中用户名和密码应该利用从token中获取的用户名和密码在在数据库中用户
	String name = "Rengar";
	String pwd = "123";

    if(!userToken.getUsername().equals(name)){
        return null; //return null;的意思是认证失败
    }

    //密码认证
    return new SimpleAuthenticationInfo("", pwd , "");
}

现在登录是输入正确的他还没和密码就可以在完成认证,并且访问/user/update了

7、实现请求授权

1、权限过滤

在ShiroConfig中的getShiroFilterFactoryBean中加入权限过滤

@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    bean.setSecurityManager(securityManager);

    //添加 shiro的内置过滤器
    /*
        anon:  无序认证就可以访问
        authc: 必须认证了才能访问
        user:  必须 记住我才能访问
        perms: 有用对某个资源的权限才能访问
        role:  拥有对某个角色权限才能访问
    */

    Map<String, String> filterMap = new LinkedHashMap<>();
    
    filterMap.put("/user/add", "authc");
    filterMap.put("/user/update", "authc");
    //filterMap.put("/user/*", "authc");支持通配符

    //检查权限, 拥有user:add权限才可以访问/user/add
    filterMap.put("/user/add", "perms[user:add]");

    bean.setFilterChainDefinitionMap(filterMap);

    //和SpringSecurity的setLoginUrl一样
    //当需要验证信息(但是你没有认证)的时候,跳转到登录界面
    bean.setLoginUrl("/toLogin");
    //权限不够时会跳转到的页面
    bean.setUnauthorizedUrl("/unauthorized");
    return bean;
}

登录认证后仍然无法访问/user/add,因为授权的代码还没有实现
此时当用户访问/user/add,会重定向到/unauthorized

2、授权

具体授权的代码,在UserRealm类的doGetAuthorizationInfo编写

//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("执行了=====授权方法");

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    //获取subject
    Subject subject = SecurityUtils.getSubject();
    
    //给所有的用户添加user:add的权限
    //真实开发中应该从数据库获取信息,判断给谁添加权限
    info.addStringPermission("user:add");
    
    return info;
}

此时用户可以访问/user/add

8、整合Thymeleaf

导入Thymeleaf整合Shiro的依赖

<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
	<groupId>com.github.theborakompanioni</groupId>
	<artifactId>thymeleaf-extras-shiro</artifactId>
	<version>2.0.0</version>
</dependency>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>

<!--有user:add权限的用户能看到这个新增的a标签-->
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">新增</a>
</div>  <a th:href="@{/user/update}">更新</a>
</body>
</html>

以上只是Shiro的简单入门,如果想要深入了解Shiro可以去Shiro官网看官方文档
http://shiro.apache.org/
本人新手,如有错误,还请指出

本项目详细介绍请看:http://www.sojson.com/shiro (强烈推荐) Demo已经部署到线上,地址是http://shiro.itboy.net, 管理员帐号:admin,密码:sojson.com 如果密码错误,请用sojson。 PS:你可以注册自己的帐号,然后用管理员赋权限给你自己的帐号,但是,每20分钟会把数据初始化一次。建议自己下载源码,让Demo跑起来,然后跑的更快,有问题加群解决。 声明: 本人提供这个Shiro + SpringMvc + Mybatis + Redis 的Demo 本着学习的态度,如果有欠缺和不足的地方,给予指正,并且多多包涵。 “去其糟粕取其精华”。如果觉得写的好的地方就给个赞,写的不好的地方,也请多多包涵。 使用过程: 1.创建数据库。 创建语句 :tables.sql 2.插入初始化数据 插入初始化数据:init.data.sql 3.运行。 管理员帐号:admin 密码:sojson ps:定时任务的sql会把密码改变为sojson.com 新版本说明:http://www.sojson.com/blog/164.html 和 http://www.sojson.com/blog/165.html 主要解决是之前说的问题:Shiro 教程,关于最近反应的相关异常问题,解决方法合集。 项目在本页面的附件中提取。 一、Cache配置修改。 配置文件(spring-cache.xml )中已经修改为如下配置: <!-- redis 配置,也可以把配置挪到properties配置文件中,再读取 --> <!-- 这种 arguments 构造的方式,之前配置有缺点。 这里之前的配置有问题,因为参数类型不一致,有时候jar和环境的问题,导致参数根据index对应,会处理问题, 理论上加另一个 name,就可以解决,现在把name 和type都加上,更保险。 --> 二、登录获取上一个URL地址报错。 当没有获取到退出前的request ,为null 的时候会报错。在(UserLoginController.java )135行处有所修改。 /** * shiro 获取登录之前的地址 * 之前0.1版本这个没判断空。 */ SavedRequest savedRequest = WebUtils.getSavedRequest(request); String url = null ; if(null != savedRequest){ url = savedRequest.getRequestUrl(); } /** * 我们平常用的获取上一个请求的方式,在Session不一致的情况下是获取不到的 * String url = (String) request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE); */ 三、删除了配置文件中的cookie写入域的问题。 在配置文件里(spring-shiro.xml )中的配置有所修改。 <!-- 会话Cookie模板 --> <!--cookie的name,我故意取名叫xxxxbaidu --> <!--cookie的有效时间 --> <!-- 配置存储Session Cookie的domain为 一级域名 --> 上面配置是去掉了 Session 的存储Key 的作用域,之前设置的.itboy.net ,是写到当前域名的 一级域名 下,这样就可以做到N 个 二级域名 下,三级、四级....下 Session 都是共享的。 <!-- 用户信息记住我功能的相关配置 --> <!-- 配置存储rememberMe Cookie的domain为 一级域名 --> <!-- 30天时间,记住我30天 --> 记住我登录的信息配置。和上面配置是一样的道理,可以在相同 一级域名 下的所有域名都可以获取到登录的信息。 四、简单实现了单个帐号只能在一处登录。 我们在其他的系统中可以看到,单个帐号只允许一人使用,在A处登录了,B处再登录,那A处就被踢出了。如下图所示。 但是此功能不是很完美,当A处被踢出后,再重新登录,这时候B处反应有点慢,具体我还没看,因为是之前加的功能,现在凌晨了,下次我有空再瞧瞧,同学你也可以看看,解决了和我说一声,我把功能修复。 五、修复功能(BUG) 1.修复权限添加功能BUG。 之前功能有问题,每当添加一个权限的时候,默认都给角色为“管理员”的角色默认添加当前新添加的权限。这样达到管理员的权限永远是最大的。由于代码有BUG ,导致所有权限删除了。现已修复。 2.修复项目只能部署到Root目录下的问题。 问题描述:之前项目只能部署到Root 下才能正常运行,目前已经修复,可以带项目路径进行访问了,之前只能这样访问,http://localhost:8080 而不能http://localhost:8080/shiro.demo/ 访问,目前是可以了。 解决方案:在 FreeMarkerViewExtend.java 33行处 增加了BasePath ,通过BasePath 来控制请求目录,在 Freemarker 中可以自由使用,而 JSP 中是直接在 JSP 中获取BasePath 使用。 解决后遗症:因为我们的权限是通过URL 来控制的,那么增加了项目的目录,导致权限不能正确的判断,再加上我们的项目名称(目录)可以自定义,导致更不好判断。 后遗症解决方案:PermissionFilter.java 50行处 解决了这个问题,详情请看代码和注释,其实就是replace 了一下。 HttpServletRequest httpRequest = ((HttpServletRequest)request); /** * 此处是改版后,为了兼容项目不需要部署到root下,也可以正常运行,但是权限没设置目前必须到root 的URI, * 原因:如果你把这个项目叫 ShiroDemo,那么路径就是 /ShiroDemo/xxxx.shtml ,那另外一个人使用,又叫Shiro_Demo,那么就要这么控制/Shiro_Demo/xxxx.shtml * 理解了吗? * 所以这里替换了一下,使用根目录开始的URI */ String uri = httpRequest.getRequestURI();//获取URI String basePath = httpRequest.getContextPath();//获取basePath if(null != uri && uri.startsWith(basePath)){ uri = uri.replace(basePath, ""); } 3.项目启动的时候报错,关于JNDI的错误提示。 其实也不是错,但是看着不舒服,所以还得解决这个问题。解决这个问题需要在web.xml 中的开始部位加入以下代码。 spring.profiles.active dev spring.profiles.default dev spring.liveBeansView.mbeanDomain dev 4.项目Maven打包问题。 打包的时候,不同版本的 Eclipse 还有IDEA 会有打包打不进去Mapper.xml 文件,这个时候要加如下代码(群里同学提供的)。 src/main/java **/*.properties **/*.xml false 在 标签内加入即可,如果还是不能解决,那么请你加群(改名后)说明你的问题,有人会回答你。 5.Tomcat7以上在访问JSP页面的时候,提示JSTL错误。 这个错误是因为Tomcat7 中没有 JSTL 的jar包,现在已经在项目pom.xml 中增加了如下 jar 的引入管理。 javax.servlet jstl 1.2 javax.servlet jsp-api 2.0 provided 如果还是不能解决问题,请在官方群(群号:259217951)内搜索“jstl” 如图下载依赖包。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值