shiro 授权和注解开发
shiro授权角色、权限
通过用户登录可以联表查询到其所对应的角色和权限
图解:
在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 = #{uid}
</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 = #{uid}
</select>
ShiroUserMapper
Set<String> getRolesByUserId(Integer uid);
Set<String> getPersByUserId(Integer uid);
MyRealm
package com.li.shio;
import com.li.model.ShiroUser;
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;
/**
* 认证过程
* 1.数据源(ini-》数据库)
* 2.doGetAuthenticationInfo将数据库用户信息给subject主题做shiro认证
* 2.1、需要再当前realm中调用service来验证,当前用户是否再数据库中存在(shiro会优先于spring加载)
* 2.2 盐加密
*/
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) {
ShiroUser shiroUser = this.shiroUserService.queryByName(principals.getPrimaryPrincipal().toString());//当前登陆的用户
Set<String> rolesByUserId = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());//获取用户角色
Set<String> persByUserId = this.shiroUserService.getPersByUserId(shiroUser.getUserid());//权限
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(rolesByUserId);
info.setStringPermissions(persByUserId);
return info;
}
/**
* 认证
* @param token 从jsp传递过来的用户名密码组成的的一个token对象
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = token.getPrincipal().toString();
String password = token.getCredentials().toString();
ShiroUser user = shiroUserService.queryByName(username);
// 拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
AuthenticationInfo info = new SimpleAuthenticationInfo(
user.getUsername(),
user.getPassword(),
ByteSource.Util.bytes(user.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-servlet.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>
ShiroUserController
/**
* 身份认证注解
* @param req
* @param resp
* @return
*/
@RequiresUser
@RequestMapping("/passUser")
public String passUser(HttpServletRequest req, HttpServletResponse resp) {
return "admin/addUser";
}
/**
* 角色认证注解
* @param req
* @param resp
* @return
*
* and :当前方法必须同时具备1,4角色id,才能被访问
*/
@RequiresRoles(value = {"1","4"},logical = Logical.AND)
@RequestMapping("/passRole")
public String passRole(HttpServletRequest req, HttpServletResponse resp) {
return "admin/listUser";
}
/**
* 权限认证注解
* @param req
* @param resp
* @return
*/
@RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
@RequestMapping("/passPer")
public String passPer(HttpServletRequest req, HttpServletResponse resp) {
return "admin/resetPwd";
}
/**
* 认证失败后的处理方式
* @param req
* @param resp
* @return
*/
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest req, HttpServletResponse resp) {
System.out.println();
return "unauthorized";
}
main.jsp
<ul>
shiro注解
<li>
<a href="${pageContext.request.contextPath}/passUser">用户认证</a>
</li>
<li>
<a href="${pageContext.request.contextPath}/passRole">角色</a>
</li>
<li>
<a href="${pageContext.request.contextPath}/passPer">权限认证</a>
</li>
</ul>
预测结果
zs只能查看身份认证的按钮内容
ls、ww可以看权限认证按钮内容
zdm可以看所有按钮的内容