shiro授权
shiro完成登录的流程:首先是我们前端输入用户名和密码,跳转到Controller然后生成token之后进行认证,我们根据用户名拿到这个用户的所有信息(主要是盐和MD5加密后的密码)然后判断通过,在跳转到前端之前又进行授权验证,看看这个用户是否拥有权限进入jsp,这就是我们今天要做的事情
一个完整的权限是五张表构成
既然我们需要进行权限认证,首先我们需要根据用户id获取他的角色(role)和权限(pers),所以需要写两个查询的方法
ShiroUserMapper.xml
<select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
where u.userid = ur.userid and ur.roleid = r.roleid
and u.userid = #{userid}
</select>
<select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
and u.userid = #{userid}
</select>
ShiroUserMapper
Set<String> getRolesByUserId(Integer userId);
Set<String> getPersByUserId(Integer userName);
然后分别在service层中实现就好,然后在我们自己写的realm中调用方法验证
MyRealm
package com.xy.shiro;
import com.xy.model.ShiroUser;
import com.xy.service.ShiroUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.Set;
/**
* @author 阳某
* @create 2019-10-13 16:13
*
*/
public class MyRealm extends AuthorizingRealm {
private ShiroUserService shiroUserService;
public ShiroUserService getShiroUserService() {
return shiroUserService;
}
public void setShiroUserService(ShiroUserService shiroUserService) {
this.shiroUserService = shiroUserService;
}
/**
* 授权
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = principals.getPrimaryPrincipal().toString();//获取用户名
ShiroUser shiroUser = shiroUserService.queryByName(username);//根据用户名获取用户信息
Set<String> pers = shiroUserService.getPersByUserId(shiroUser.getUserid());//根据uid获取权限
Set<String> roles = shiroUserService.getRolesByUserId(shiroUser.getUserid());//根据uid获取角色
// SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addRoles(roles);
// info.addStringPermissions(pers);
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
info.setRoles(roles);
info.setStringPermissions(pers);
return info;
}
/**
* 认证
*
* 认证的过程
* 1、数据源(ini)现在数据库
* 2、doGetAuthenticationInfo将数据库的用户信息给subject主体做shiro认证
* 2.1、需要在当前realm中调用service来验证,当前用户是要有在数据库中存在
* 2.2、盐加密
*
* @param token 从jsp传递过来的用户名密码组成的一个token对象
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = token.getPrincipal().toString();
String pwd = token.getCredentials().toString();
ShiroUser shiroUser = this.shiroUserService.queryByName(userName);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
this.getName()
);
return info;
}
}
shiro注解式开发
常用注解介绍
@RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true
@RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
@RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
@RequiresRoles(value = {“admin”,“user”},logical = Logical.AND):表示当前Subject需要角色admin和user
@RequiresPermissions(value = {“user:delete”,“user:b”},logical = Logical.OR):表示当前Subject需要权限user:delete或者user:b
我们需要在springMVC中使用shiro注解,所以需要把我们的securityManager安全管理器和我们的错误信息处理交给springMVC来管,所以就需要把它们配置进入spring-MVC.xml中
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.apache.shiro.authz.UnauthorizedException">
unauthorized
</prop>
</props>
</property>
<property name="defaultErrorView" value="unauthorized"/>
</bean>
然后再Controller中运用注解
/**
* 用户认证注解
* @param req
* @param resp
* @return
*/
@RequiresUser
@RequestMapping("/passUser")
public String passUser(HttpServletRequest req,HttpServletResponse resp){
return "admin/addUser";
}
/**
* 角色认证注解
* @param req
* @return
*/
@RequiresRoles(value = {"1","4"},logical = Logical.OR)
@RequestMapping("/passRole")
public String passRole(HttpServletRequest req,HttpServletResponse resp){
return "admin/listUser";
}
/**
* 权限认证注解
* @param req
* @return
*/
@RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
@RequestMapping("/passPer")
public String passPer(HttpServletRequest req,HttpServletResponse resp){
return "admin/resetPwd";
}
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest req,HttpServletResponse resp){
return "unauthorized";
}
然后前端main页面改了跳转方法,来分别测试
shiro注解标签
<li>
<r:hasPermission name="user:create">
<a href="${pageContext.request.contextPath}/passUser">用户认证</a>
</r:hasPermission>
</li>
<li>
<a href="${pageContext.request.contextPath}/passRole">角色认证</a>
</li>
<li>
<a href="${pageContext.request.contextPath}/passPer">权限认证</a>
</li>
最终效果是:如果直接进入页面会进入错误处理页面,只有登录了相关权限的用户才能点击进入
end…