目录
一、shiro之授权角色、权限
分析如图:
步骤:
1,mapper层,service层
usermapper.xml
<select id="selectRoleIdByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
select roleid from t_shiro_user u,t_shiro_user_role ur
where u.userid=ur.userid and u.username = #{userName}
</select>
<!---->
<select id="selectPerIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
select rp.perid from t_shiro_user u,t_shiro_user_role ur ,t_shiro_role_permission rp
where u.userid= ur.userid and ur.roleid=rp.roleid and u.username = #{userName}
</select>
usermapper.java类
//角色编号查找
Set<String> selectRoleIdByUserName(@Param("userName") String username);
//查看权限
Set<String> selectPerIdsByUserName(@Param("userName") String username);
实现类
package com.zking.oa.biz;
import com.zking.oa.mapper.UserMapper;
import com.zking.oa.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* @author 锦鲤
* @site www.lucy.com
* @company xxx公司
* @create 2022-08-25 18:47
* //@ContextConfiguration(locations = "classpath:applicationContext-shiro.xml","classpath:UserMapper.xml")
*/
@Service("userbiz")
public class UserBizImpl implements UserBiz {
@Autowired
private UserMapper usermapper;
@Override
public int deleteByPrimaryKey(Integer userid) {
return usermapper.deleteByPrimaryKey(userid);
}
@Override
public int insert(User record) {
return usermapper.insert(record);
}
@Override
public int insertSelective(User record) {
return usermapper.insertSelective(record);
}
@Override
public User selectByPrimaryKey(Integer userid) {
return usermapper.selectByPrimaryKey(userid);
}
@Override
public int updateByPrimaryKeySelective(User record) {
return usermapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(User record) {
return usermapper.updateByPrimaryKey(record);
}
@Override
public User queryUserByUserName(String userName) {
return usermapper.queryUserByUserName(userName);
}
@Override
public Set<String> selectRoleIdByUserName(String username) {
return usermapper.selectRoleIdByUserName(username);
}
@Override
public Set<String> selectPerIdsByUserName(String username) {
return usermapper.selectPerIdsByUserName(username);
}
}
2,shiro的授权方法
package com.zking.oa.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @author 锦鲤
* @site www.lucy.com
* @company xxx公司
* @create 2022-08-19 21:46
*/
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(HttpServletRequest req){
try {
String username=req.getParameter("username");
String password=req.getParameter("password");
UsernamePasswordToken token=new UsernamePasswordToken(username,password);
Subject subject=SecurityUtils.getSubject();
subject.login(token);
return "main";
}catch (Exception e){
req.setAttribute("message","用户名或者密码有误!");
return "login";
}
}
// 退出登录
@RequestMapping("/logout")
public String logout(HttpServletRequest req){
Subject subject=SecurityUtils.getSubject();
subject.logout();
return "login";
}
}
package com.zking.oa.shiro;
import com.zking.oa.biz.UserBiz;
import com.zking.oa.model.User;
import jdk.nashorn.internal.parser.Token;
import org.apache.shiro.authc.*;
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.lucy.com
* @company xxx公司
* @create 2022-08-25 18:53
*/
public class MyRealm extends AuthorizingRealm {
private UserBiz userbiz;
public UserBiz getUserbiz() {
return userbiz;
}
public void setUserbiz(UserBiz userbiz) {
this.userbiz = userbiz;
}
/**
* 授权
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName= principals.getPrimaryPrincipal().toString();
System.out.println("名字"+userName);
Set<String> roleIds= userbiz.selectRoleIdByUserName(userName);
Set<String> perIds= userbiz.selectPerIdsByUserName(userName);
SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
//将当前登录的权限交给shiro授权器
info.setStringPermissions(perIds);
// 将当前登录的角色交给shrio的授权器
info.setRoles(roleIds);
return info;
}
/**
*
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("身份认证...");
String username = token.getPrincipal().toString();
String password = token.getCredentials().toString();
User user = userbiz.queryUserByUserName(username);
// 拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
user.getUsername(),
user.getPassword(),
ByteSource.Util.bytes(user.getSalt()),
this.getName()
);
return info;
}
}
3,测试
二、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
注解式开发:
1将对应的注解添加到指定的权限控制方法上
身份认证:@RequiresUser
角色认证:@RequiresRoles
权限认证 @RequiresPermissions
2.在springmvc.xml在添加拦截器相关配置
package com.zking.oa.shiro;
import com.zking.oa.biz.UserBiz;
import com.zking.oa.model.User;
import jdk.nashorn.internal.parser.Token;
import org.apache.shiro.authc.*;
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.lucy.com
* @company xxx公司
* @create 2022-08-25 18:53
*/
public class MyRealm extends AuthorizingRealm {
private UserBiz userbiz;
public UserBiz getUserbiz() {
return userbiz;
}
public void setUserbiz(UserBiz userbiz) {
this.userbiz = userbiz;
}
/**
* 授权
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName= principals.getPrimaryPrincipal().toString();
System.out.println("名字"+userName);
Set<String> roleIds= userbiz.selectRoleIdByUserName(userName);
Set<String> perIds= userbiz.selectPerIdsByUserName(userName);
SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
//将当前登录的权限交给shiro授权器
info.setStringPermissions(perIds);
// 将当前登录的角色交给shrio的授权器
info.setRoles(roleIds);
return info;
}
/**
*
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("身份认证...");
String username = token.getPrincipal().toString();
String password = token.getCredentials().toString();
User user = userbiz.queryUserByUserName(username);
// 拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
user.getUsername(),
user.getPassword(),
ByteSource.Util.bytes(user.getSalt()),
this.getName()
);
return info;
}
}
package com.zking.oa.controller;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author 锦鲤
* @site www.lucy.com
* @company xxx公司
* @create 2022-08-26 20:38
*/
@RequestMapping("/shiro")
@Controller
public class shiroController {
@RequiresUser
@RequestMapping("/passUser")
public String passUser(){
return "admin/addUser";
}
//RequiresRoles当前方法只有具备指定的的角色 才能访问
@RequiresRoles(value = {"1","4"},logical = Logical.AND)
@RequestMapping("/passRole")
public String passRole(){
System.out.println("角色认证通过、");
return "admin/addUser";
}
//RequiresRoles当前方法只有具备指定的的权限 才能访问
@RequiresRoles(value = {"2"},logical = Logical.AND)
@RequestMapping("/passPermission")
public String passPermission(){
System.out.println("权限认证通过、");
return "admin/addUser";
}
}
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>
controller层
package com.zking.oa.controller;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author 锦鲤
* @site www.lucy.com
* @company xxx公司
* @create 2022-08-26 20:38
*/
@RequestMapping("/shiro")
@Controller
public class shiroController {
@RequiresUser
@RequestMapping("/passUser")
public String passUser(){
return "admin/addUser";
}
//RequiresRoles当前方法只有具备指定的的角色 才能访问
@RequiresRoles(value = {"1","4"},logical = Logical.AND)
@RequestMapping("/passRole")
public String passRole(){
System.out.println("角色认证通过、");
return "admin/addUser";
}
//RequiresRoles当前方法只有具备指定的的权限 才能访问
@RequiresRoles(value = {"2"},logical = Logical.AND)
@RequestMapping("/passPermission")
public String passPermission(){
System.out.println("权限认证通过、");
return "admin/addUser";
}
}
本文含有隐藏内容,请 开通VIP 后查看