本文主要讲解的知识点有如下:html
上一篇咱们已经讲解了Shiro的认证相关的知识了,如今咱们来弄Shiro的受权java
Shiro受权的流程和认证的流程实际上是差很少的:程序员
Shiro支持的受权方式有三种:web
Shiro 支持三种方式的受权:
编程式:经过写if/else 受权代码块完成:
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole(“admin”)) {
//有权限
} else {
//无权限
}
注解式:经过在执行的Java方法上放置相应的注解完成:
@RequiresRoles("admin")
public void hello() {
//有权限
}
JSP/GSP 标签:在JSP/GSP 页面经过相应的标签完成:
<shiro:hasRole name="admin">
<!— 有权限—>
</shiro:hasRole>
复制代码
一样的,咱们是经过安全管理器来去受权的,所以咱们仍是须要配置对应的配置文件的:spring
shiro-permission.ini配置文件:数据库
#用户
[users]
#用户zhang的密码是123,此用户具备role1和role2两个角色
zhang=123,role1,role2
wang=123,role2
#权限
[roles]
#角色role1对资源user拥有create、update权限
role1=user:create,user:update
#角色role2对资源user拥有create、delete权限
role2=user:create,user:delete
#角色role3对资源user拥有create权限
role3=user:create
#权限标识符号规则:资源:操做:实例(中间使用半角:分隔)
user:create:01 表示对用户资源的01实例进行create操做。
user:create:表示对用户资源进行create操做,至关于user:create:*,对全部用户资源实例进行create操做。
user:*:01 表示对用户资源实例01进行全部操做。
复制代码
代码测试:apache
// 角色受权、资源受权测试
@Test
public void testAuthorization() {
// 建立SecurityManager工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory(
"classpath:shiro-permission.ini");
// 建立SecurityManager
SecurityManager securityManager = factory.getInstance();
// 将SecurityManager设置到系统运行环境,和spring后将SecurityManager配置spring容器中,通常单例管理
SecurityUtils.setSecurityManager(securityManager);
// 建立subject
Subject subject = SecurityUtils.getSubject();
// 建立token令牌
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan",
"123");
// 执行认证
try {
subject.login(token);
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("认证状态:" + subject.isAuthenticated());
// 认证经过后执行受权
// 基于角色的受权
// hasRole传入角色标识
boolean ishasRole = subject.hasRole("role1");
System.out.println("单个角色判断" + ishasRole);
// hasAllRoles是否拥有多个角色
boolean hasAllRoles = subject.hasAllRoles(Arrays.asList("role1",
"role2", "role3"));
System.out.println("多个角色判断" + hasAllRoles);
// 使用check方法进行受权,若是受权不经过会抛出异常
// subject.checkRole("role13");
// 基于资源的受权
// isPermitted传入权限标识符
boolean isPermitted = subject.isPermitted("user:create:1");
System.out.println("单个权限判断" + isPermitted);
boolean isPermittedAll = subject.isPermittedAll("user:create:1",
"user:delete");
System.out.println("多个权限判断" + isPermittedAll);
// 使用check方法进行受权,若是受权不经过会抛出异常
subject.checkPermission("items:create:1");
}
复制代码
通常地,咱们的权限都是从数据库中查询的,并非根据咱们的配置文件来进行配对的。所以咱们须要自定义reaml,让reaml去对比的是数据库查询出来的权限编程
shiro-realm.ini配置文件:将自定义的reaml信息注入到安全管理器中安全
[main]
#自定义 realm
customRealm=cn.itcast.shiro.realm.CustomRealm
#将realm设置到securityManager,至关 于spring中注入
securityManager.realms=$customRealm
复制代码
咱们上次已经使用过了一个自定义reaml,当时候仅仅重写了doGetAuthenticationInfo()方法,此次咱们重写doGetAuthorizationInfo()方法微信
// 用于受权
@Override
protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) {
//从 principals获取主身份信息
//将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证经过填充到SimpleAuthenticationInfo中身份类型),
String userCode = (String) principals.getPrimaryPrincipal();
//根据身份信息获取权限信息
//链接数据库...
//模拟从数据库获取到数据
List<String> permissions = new ArrayList<String>();
permissions.add("user:create");//用户的建立
permissions.add("items:add");//商品添加权限
//....
//查到权限数据,返回受权信息(要包括 上边的permissions)
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//将上边查询到受权信息填充到simpleAuthorizationInfo对象中
simpleAuthorizationInfo.addStringPermissions(permissions);
return simpleAuthorizationInfo;
}
复制代码
测试程序:
// 自定义realm进行资源受权测试
@Test
public void testAuthorizationCustomRealm() {
// 建立SecurityManager工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory(
"classpath:shiro-realm.ini");
// 建立SecurityManager
SecurityManager securityManager = factory.getInstance();
// 将SecurityManager设置到系统运行环境,和spring后将SecurityManager配置spring容器中,通常单例管理
SecurityUtils.setSecurityManager(securityManager);
// 建立subject
Subject subject = SecurityUtils.getSubject();
// 建立token令牌
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan",
"111111");
// 执行认证
try {
subject.login(token);
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("认证状态:" + subject.isAuthenticated());
// 认证经过后执行受权
// 基于资源的受权,调用isPermitted方法会调用CustomRealm从数据库查询正确权限数据
// isPermitted传入权限标识符,判断user:create:1是否在CustomRealm查询到权限数据以内
boolean isPermitted = subject.isPermitted("user:create:1");
System.out.println("单个权限判断" + isPermitted);
boolean isPermittedAll = subject.isPermittedAll("user:create:1",
"user:create");
System.out.println("多个权限判断" + isPermittedAll);
// 使用check方法进行受权,若是受权不经过会抛出异常
subject.checkPermission("items:add:1");
}
复制代码
shiro也经过filter进行拦截。filter拦截后将操做权交给spring中配置的filterChain(过虑链儿)
在web.xml中配置filter
<!-- shiro的filter -->
<!-- shiro过虑器,DelegatingFilterProxy经过代理模式将spring容器中的bean和filter关联起来 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!-- 设置true由servlet容器控制filter的生命周期 -->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<!-- 设置spring容器filter的bean id,若是不设置则找与filter-name一致的bean-->
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
复制代码
在applicationContext-shiro.xml 中配置web.xml中fitler对应spring容器中的bean。
<!-- web.xml中shiro的filter对应的bean -->
<!-- Shiro 的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<!-- loginUrl认证提交地址,若是没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证 -->
<property name="loginUrl" value="/login.action" />
<!-- 认证成功统一跳转到first.action,建议不配置,shiro认证成功自动到上一个请求路径 -->
<!-- <property name="successUrl" value="/first.action"/> -->
<!-- 经过unauthorizedUrl指定没有权限操做时跳转页面-->
<property name="unauthorizedUrl" value="/refuse.jsp" />
<!-- 自定义filter配置 -->
<property name="filters">
<map>
<!-- 将自定义 的FormAuthenticationFilter注入shiroFilter中-->
<entry key="authc" value-ref="formAuthenticationFilter" />
</map>
</property>
<!-- 过虑器链定义,从上向下顺序执行,通常将/**放在最下边 -->
<property name="filterChainDefinitions">
<value>
<!--全部url均可以匿名访问-->
/** = anon
</value>
</property>
</bean>
复制代码
配置安全管理器
<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm" />
</bean>
复制代码
配置reaml
<!-- realm -->
<bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
</bean>
复制代码
步骤:
咱们在spring配置过滤器链的时候,咱们发现这么一行代码:
<!--全部url均可以匿名访问 -->
/** = anon
复制代码
anon其实就是shiro内置的一个过滤器,上边的代码就表明着全部的匿名用户均可以访问
固然了,后边咱们还须要配置其余的信息,为了让页面可以正常显示,咱们的静态资源通常是不须要被拦截的。
因而咱们能够这样配置:
<!-- 对静态资源设置匿名访问 -->
/images/** = anon
/js/** = anon
/styles/** = anon
复制代码
上面咱们了解到了anno过滤器的,shiro还有其余的过滤器的..咱们来看看
经常使用的过滤器有下面几种:
anon:例子/admins/**=anon
没有参数,表示能够匿名使用。 authc:例如/admins/user/**
=authc表示须要认证(登陆)才能使用,FormAuthenticationFilter是表单认证,没有参数 perms:例子/admins/user/**=perms[user:add:*]
,参数能够写多个,多个时必须加上引号,而且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"]
,当有多个参数时必须每一个参数都经过才经过,想当于isPermitedAll()方法。 user:例如/admins/user/**
=user没有参数,表示必须存在用户, 身份认证经过或经过记住我认证经过的能够访问,当登入操做时不作检查
使用FormAuthenticationFilter过虑器实现 ,原理以下:
因为FormAuthenticationFilter的用户身份和密码的input的默认值(username和password),修改页面的帐号和密码的input的名称为username和password
<TR>
<TD>用户名:</TD>
<TD colSpan="2"><input type="text" id="usercode" name="username" style="WIDTH: 130px" /></TD>
</TR>
<TR>
<TD>密 码:</TD>
<TD><input type="password" id="pwd" name="password" style="WIDTH: 130px" />
</TD>
</TR>
复制代码
上面咱们已经说了,当用户没有认证的时候,请求的loginurl进行认证,用户身份的用户密码提交数据到loginrul中。
当咱们提交到loginurl的时候,表单过滤器会自动解析username和password去调用realm来进行认证。最终在request域对象中存储shiroLoginFailure认证信息,若是返回的是异常的信息,那么咱们在login中抛出异常便可
//登录提交地址,和applicationContext-shiro.xml中配置的loginurl一致
@RequestMapping("login")
public String login(HttpServletRequest request)throws Exception{
//若是登录失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
//根据shiro返回的异常类路径判断,抛出指定异常信息
if(exceptionClassName!=null){
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
//最终会抛给异常处理器
throw new CustomException("帐号不存在");
} else if (IncorrectCredentialsException.class.getName().equals(
exceptionClassName)) {
throw new CustomException("用户名/密码错误");
} else if("randomCodeError".equals(exceptionClassName)){
throw new CustomException("验证码错误 ");
}else {
throw new Exception();//最终在异常处理器生成未知错误
}
}
//此方法不处理登录成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
//登录失败还到login页面
return "login";
}
复制代码
配置认证过滤器
<value>
<!-- 对静态资源设置匿名访问 -->
/images/** = anon
/js/** = anon
/styles/** = anon
<!-- /** = authc 全部url都必须认证经过才能够访问-->
/** = authc
</value>
复制代码
不用咱们去实现退出,只要去访问一个退出的url(该 url是能够不存在),由LogoutFilter拦截住,清除session。
在applicationContext-shiro.xml配置LogoutFilter:
<!-- 请求 logout.action地址,shiro去清除session-->
/logout.action = logout
复制代码
一、认证后用户菜单在首页显示 二、认证后用户的信息在页头显示
realm从数据库查询用户信息,将用户菜单、usercode、username等设置在SimpleAuthenticationInfo中。
//realm的认证方法,从数据库查询用户信息
@Override
protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException {
// token是用户输入的用户名和密码
// 第一步从token中取出用户名
String userCode = (String) token.getPrincipal();
// 第二步:根据用户输入的userCode从数据库查询
SysUser sysUser = null;
try {
sysUser = sysService.findSysUserByUserCode(userCode);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 若是查询不到返回null
if(sysUser==null){//
return null;
}
// 从数据库查询到密码
String password = sysUser.getPassword();
//盐
String salt = sysUser.getSalt();
// 若是查询到返回认证信息AuthenticationInfo
//activeUser就是用户身份信息
ActiveUser activeUser = new ActiveUser();
activeUser.setUserid(sysUser.getId());
activeUser.setUsercode(sysUser.getUsercode());
activeUser.setUsername(sysUser.getUsername());
//..
//根据用户id取出菜单
List<SysPermission> menus = null;
try {
//经过service取出菜单
menus = sysService.findMenuListByUserId(sysUser.getId());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//将用户菜单 设置到activeUser
activeUser.setMenus(menus);
//将activeUser设置simpleAuthenticationInfo
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
activeUser, password,ByteSource.Util.bytes(salt), this.getName());
return simpleAuthenticationInfo;
}
复制代码
配置凭配器,由于咱们用到了md5和散列
<!-- 凭证匹配器 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5" />
<property name="hashIterations" value="1" />
</bean>
复制代码
<!-- realm -->
<bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
<!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 -->
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
复制代码
在跳转到首页的时候,取出用户的认证信息,转发到JSP便可
//系统首页
@RequestMapping("/first")
public String first(Model model)throws Exception{
//从shiro的session中取activeUser
Subject subject = SecurityUtils.getSubject();
//取身份信息
ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
//经过model传到页面
model.addAttribute("activeUser", activeUser);
return "/first";
}
复制代码
若是文章有错的地方欢迎指正,你们互相交流。习惯在微信看技术文章,想要获取更多的Java资源的同窗,能够关注微信公众号:Java3y