shiro授权角色、权限
ShiroUserMapper
进行权限认证,首先我们需要根据用户id获取他的角色(role)和权限(pers),写两个查询的方法
Set<String> getRolesByUserId(Integer userId);
Set<String> getPersByUserId(Integer userName);
在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>
ShiroUserServiceImpl 实现类
package com.xhh.service.Impl;
import com.xhh.mapper.ShiroUserMapper;
import com.xhh.model.ShiroUser;
import com.xhh.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* @author 林耀东
* @site www.baidu.com
* @company
* @create 2019-12-4 8:40
*/
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper;
@Override
public ShiroUser queryByName(String uname) {
return shiroUserMapper.queryByName(uname);
}
@Override
public Set<String> getRolesByUserId(Integer uid) {
return shiroUserMapper.getRolesByUserId(uid);
}
@Override
public Set<String> getPersByUserId(Integer uid) {
return shiroUserMapper.getPersByUserId(uid);
}
}
然后在我们自己写的realm中调用方法验证
package com.xhh.shiro;
import com.xhh.model.ShiroUser;
import com.xhh.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 林耀东
* @site www.baidu.com
* @company
* @create 2019-12-4 8:55
*
* 认证的过程
* 1.数据源(ini->数据源
* 2.doGetAuthenticationInfo将数据库的用户信息给subject主体做shiro认证的
* 2.1、需要在当前reaim中调用service,来验 证当前用户是否存在数据库中
* 2.2盐加密
*/
public class MyReaIm 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> roleids = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
Set<String> perIds = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(roleids);
info.setStringPermissions(perIds);
return null;
}
/**
* 认证
* 获取数据源
* @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);
AuthenticationInfo info = new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
this.getName()
);
return info;
}
}
Shiro的注解式开发
ShiroUserController
package com.xhh.controller;
import com.xhh.service.ShiroUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 林耀东
* @site www.baidu.com
* @company
* @create 2019-12-4 9:05
*/
@Controller
public class ShiroUserController {
@Autowired
private ShiroUserService shiroUserService;
@RequestMapping("/login")
public String login(HttpServletRequest req, HttpServletResponse resp) {
Subject subject = SecurityUtils.getSubject();
String uname = req.getParameter("username");
String pwd = req.getParameter("password");
UsernamePasswordToken token = new UsernamePasswordToken(uname, pwd);
try {
subject.login(token);
req.setAttribute("uname", uname);
return "main";
} catch (Exception e) {
req.setAttribute("message", "用户名或密码错误");
return "login";
}
}
@RequestMapping("/logout")
public String logout(HttpServletRequest req, HttpServletResponse resp) {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "login";
}
/**
* 讲解身份认证的注解
* @param req
* @param resp
* @return
*/
@RequiresUser
@RequestMapping("/passUser")
public String passUser(HttpServletRequest req, HttpServletResponse resp) {
return "admin/addUser";
}
/**
* 角色认证的注解
* @param req
* @param resp
*
* 当前方法必须同时具备1,4的角色id才能被访问
* @return
*/
@RequiresRoles(value = {"2","4"},logical = Logical.OR)
@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 "login";
}
}
配合拦截器
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>