Shiro授权
1,shiro授权角色、权限
1.1 在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>
1.2 在ShiroUserMapper.java中用set集合进行接收xml中传过来的方法
/**
* 查询用户对应的角色id集合
* @param userid
* @return
*/
Set<String> getRolesByUserId(@Param("userid") Integer userid);
/**
* 查询用户对应的权限名称集合
* @param userid
* @return
*/
Set<String> getPersByUserId(@Param("userid") Integer userid);
1.3 在ShiroUserService.java中添加内容,并实现对应接口中的内容
package com.su.ssm.service;
import com.su.ssm.model.ShiroUser;
import java.util.Set;
public interface ShiroUserService {
//shiro授权
public Set<String> getRolesByUserId(Integer userId);
public Set<String> getPersByUserId(Integer userId);
//shiro认证盐加密
ShiroUser queryByName(String uname);
int insert(ShiroUser record);
}
ShiroUserServiceImpl:
package com.su.ssm.service.impl;
import com.su.ssm.mapper.ShiroUserMapper;
import com.su.ssm.model.ShiroUser;
import com.su.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper;
//shiro授权
@Override
public Set<String> getRolesByUserId(Integer userId) {
return shiroUserMapper.getRolesByUserId(userId);
}
@Override
public Set<String> getPersByUserId(Integer userId) {
return shiroUserMapper.getPersByUserId(userId);
}
//shiro认证盐加密
@Override
public ShiroUser queryByName(String uname) {
return shiroUserMapper.queryByName(uname);
}
@Override
public int insert(ShiroUser record) {
return shiroUserMapper.insert(record);
}
}
1.4 重写MyRealm.java中的授权方法
package com.su.ssm.shiro;
import com.su.ssm.model.ShiroUser;
import com.su.ssm.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 org.springframework.stereotype.Component;
import java.util.Set;
/**
* 替换了上堂课的ini文件,所有用户的身份都从这里来
*/
@Component
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) {
System.out.println("进行授权。。。");
ShiroUser shiroUser = this.shiroUserService.queryByName(principals.getPrimaryPrincipal().toString());
//当前认证过的用户对应的角色id集合
Set<String> rolesByUserId = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
//当前认证过的用户对应的权限id集合
Set<String> persByUserId = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
AuthorizationInfo info=new SimpleAuthorizationInfo();
((SimpleAuthorizationInfo) info).setRoles(rolesByUserId);
((SimpleAuthorizationInfo) info).setStringPermissions(persByUserId);
return info;
}
/**
* 身份认证的方法
* @param authenticationToken
* @return
* @throws AuthenticationException
* token是controller层传递过来的,也就是说一做登录操作,就会访问这个方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String uname= (String) authenticationToken.getPrincipal().toString();
String pwd= (String) authenticationToken.getCredentials().toString();
ShiroUser shiroUser = shiroUserService.queryByName(uname);
AuthenticationInfo info=new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
this.getName()
);
return info;
}
}
用zmd登录点击用户新增未授权会显示如下图:
授权显示如下:
shiro是优缺点并存的,优点就是安全性能高,缺点就是性能低,因为每发一次请求就要做一次权限认证
2, 注解式开发
常用注解介绍
@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.su.ssm.controller;
import com.su.ssm.model.Book;
import com.su.ssm.service.BookService;
import com.su.ssm.util.PageBean;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* springmvc 中五种返回值处理情况
* 转发3种
* 转发到安全目录web-inf下
* 转发到根目录下
* 转发到requestMapping
*
*重定向2种
* 根目录
* requestMapping
*/
@Controller
public class HelloController {
@Autowired
private BookService bookService;
@RequestMapping("/say1")
public String say1() {
return "hello";
}
public ModelAndView say2() {
ModelAndView mv = new ModelAndView();
mv.setViewName("/hello2");
mv.addObject("msg", "略略略");
return mv;
}
// 转发到安全目录web-inf下
@RequestMapping("/req1")
public String req1() {
System.out.println("转发到安全目录web-inf下...");
return "abc";
}
// 转发到根目录下
@RequestMapping("/req2")
public String req2() {
System.out.println("转发到根目录下...");
return "forward:/cba.jsp";
}
// 转发到requestMapping
@RequestMapping("/req3")
public String req3() {
System.out.println("转发到requestMapping...");
return "forward:/req2";
}
// 根目录
@RequestMapping("/red1")
public String red1() {
System.out.println("red1根目录...");
return "redirect:/bca.jsp";
}
// requestMapping
@RequestMapping("/red2")
public String red2() {
System.out.println("red1根目录...");
return "redirect:/req2";
}
//map集合里面套了list
@ResponseBody
@RequestMapping("/json1")
public Map json1(HttpServletRequest req) {
//之前的用法
// ObjectMapper om=new ObjectMapper();
// String s = om.writeValueAsString("这里既可以放map,也可以放list,也可以放字符串");
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map> list = bookService.listPager(new Book(), pageBean);
Map map = new HashMap();
map.put("total", 101);
map.put("data", list);
return map;
}
//直接是list
@ResponseBody
@RequestMapping("/json2")
public List<Map> json2(HttpServletRequest req) {
//之前的用法
// ObjectMapper om=new ObjectMapper();
// String s = om.writeValueAsString("这里既可以放map,也可以放list,也可以放字符串");
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map> list = bookService.listPager(new Book(), pageBean);
return list;
}
//字符串
@ResponseBody
@RequestMapping("/json3")
public String json3(HttpServletRequest req) {
return "springmvc string to json";
}
//注解式开发
@RequiresUser
@ResponseBody
@RequestMapping("/passUser")
public String passUser(HttpServletRequest req) {
return "pass user";
}
@RequiresRoles(value = {"2","4"},logical = Logical.OR)
@ResponseBody
@RequestMapping("/passRole")
public String passRole(HttpServletRequest req) {
return "pass role";
}
@RequiresPermissions(value = {"user:load","user:export"},logical = Logical.AND)
@ResponseBody
@RequestMapping("/passAuth")
public String passAuth(HttpServletRequest req) {
return "pass auth";
}
}
在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>
@RequiresUser
只要是用户都可以访问
@RequiresRoles(value = {“2”,“4”},logical = Logical.OR)
在满足注解里的要求的角色才可以访问
同样也是在满足注解里的要求的权限才可以访问
zdm登录访问。如果想让另外一个也访问到那就将AND改成OR
上一篇: 创建Oracle监听白名单
下一篇: 完成登陆接口
推荐阅读
-
AutoCAD2006序列号 | 授权号
-
手机App无授权就能监听电话 成功率高达90%:罪魁祸首你想象不到
-
详解.Net Core 权限验证与授权(AuthorizeFilter、ActionFilterAttribute)
-
华为DFH授权配件计划开始实施:摩米士首批获认证
-
微信授权就是这个原理,Spring Cloud OAuth2 授权码模式
-
centos 7中添加一个新用户并授权的步骤详解
-
使用weixin-java-tools完成微信授权登录、微信支付的示例
-
千牛子账号怎么授权?千牛子账号权限设置教程
-
apowersoft video converter studio如何激活?视频转换王获取终生商业授权的方法
-
Ashampoo Burning Studio 20.0如何安装?Ashampoo Burning Studio授权激活教程