1、shiro授权角色、权限
①权限图解
②授权
ShiroUserMapper
Set<String> getRolesByUserId(Integer uid);
Set<String> getPersByUserId(Integer uid);
在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>
③Service层
ShiroUserService
package com.wyy.service;
import com.wyy.model.ShiroUser;
import java.util.Set;
/**
* @author 秃头集团王某
* @company 秃头公司
* @create 2019-10-13 18:09
*/
public interface ShiroUserService {
/**
* 用来shiro认证的
* @param uname
* @return
*/
ShiroUser queryByName(String uname);
int insert(ShiroUser shiroUser);
Set<String> getRolesByUserId(Integer uid);
Set<String> getPersByUserId(Integer uid);
}
④重写自定义realm中的授权方法
MyRealm
package com.wyy.shiro;
import com.wyy.model.ShiroUser;
import com.wyy.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 秃头集团王某
* @company 秃头公司
* @create 2019-10-13 17:07
*
* 认证的过程
* 1、数据源(ini->数据源)
* 2、doGetAuthorizationInfo将数据库的用户信息给subject主题做shiro认证的
* 2.1、需要在当前realm中调用service来验证,当前用户是否在数据库中存在的
*/
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> 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 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);
System.out.println("输出用户信息:");
System.out.println(shiroUser);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
this.getName()
);
return info;
}
}
2、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
②注解的使用
Controller层
package com.wyy.controller;
import com.wyy.model.ShiroUser;
import com.wyy.service.ShiroUserService;
import com.wyy.util.PasswordHelper;
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.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 秃头集团王某
* @company 秃头公司
* @create 2019-10-13 19:20
*/
@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
*/
@RequestMapping("/register")
public String register(HttpServletRequest req, HttpServletResponse resp) {
String uname = req.getParameter("username");
String pwd = req.getParameter("password");
String salt = PasswordHelper.createSalt();
String credentials = PasswordHelper.createCredentials(pwd, salt);
ShiroUser shiroUser = new ShiroUser();
shiroUser.setUsername(uname);
shiroUser.setPassword(credentials);
shiroUser.setSalt(salt);
int insert = shiroUserService.insert(shiroUser);
if (insert > 0) {
req.setAttribute("message", "注册成功");
return "login";
} else {
req.setAttribute("message", "注册失败");
return "login";
}
}
/**
* 讲解身份认证的注解
* @param req
* @param resp
* @return
*/
@RequestMapping("/passUser")
public String passUser ( HttpServletRequest req, HttpServletResponse resp){
return "admin/addUser";
}
/**
* 角色认证的注解
* @param req
* @param resp
*
* 当前方法必须同时具备1、4的角色id,才能被访问
* @return
*/
@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";
}
}
Springmvc.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>
③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>