shiro authorized to comment and Development

shiro_03_ it authorized to comment and Development

shiro 授权

What's new in the UserMapper.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 Layer

 /**
     * 查询用户对应的角色id集合
     * @param userId
     * @return
     */
    Set<String> getRolesByUserId(@Param("userid") Integer userId);

    /**
     * 查询用户对应的权限名称集合
     * @param userId
     * @return
     */
    Set<String> getPersByUserId(@Param("userid") Integer userId);

UserService.java

package com.javachz.ssm.service;


import com.javachz.ssm.model.User;

import java.util.Set;

/**
 * @author 52hz
 * @site www.javachz.com
 * @company xxx公司
 * @create  2019-11-30 21:21
 */
public interface UserService {
    User queryByName(String userName);

    Set<String> getRolesByUserId(Integer userId);

    Set<String> getPersByUserId(Integer userId);
}

UserServletImpl .java

package com.javachz.ssm.service.Impl;

import com.javachz.ssm.mapper.UserMapper;
import com.javachz.ssm.model.User;
import com.javachz.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author 52hz
 * @site www.javachz.com
 * @company xxx公司
 * @create  2019-11-30 21:22
 */
@Service("userService")
public class UserServletImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public User queryByName(String userName) {
        return userMapper.queryByName(userName);
    }

    @Override
    public Set<String> getRolesByUserId(Integer userId) {
        return userMapper.getRolesByUserId(userId
        );
    }

    @Override
    public Set<String> getPersByUserId(Integer userId) {
        return userMapper.getPersByUserId(userId);
    }
}

MyRealm.java

package com.javachz.ssm.shiro;

import com.javachz.ssm.model.User;
import com.javachz.ssm.service.Impl.UserServletImpl;
import com.javachz.ssm.service.UserService;
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.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 52hz
 * @site www.javachz.com
 * @company xxx公司
 * @create  2019-11-30 20:44
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进行授权.....");
        User user = this.userService.queryByName(principalCollection.getPrimaryPrincipal().toString());
        //当前认证过的用户对应的角色id集合
        Set<String> rolesByUserId = this.userService.getRolesByUserId(user.getUserid());
        Set<String> persByUserId = this.userService.getPersByUserId(user.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 userName=authenticationToken.getPrincipal().toString();
        User user = this.userService.queryByName(userName);
        AuthenticationInfo info=new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName());
        return info;
    }
}

UserController.java

package com.javachz.ssm.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 52hz
 * @site www.javachz.com
 * @company xxx公司
 * @create  2019-11-30 21:58
 */
@Controller
public class UserController {

    @RequestMapping("/login")
    public String login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password= request.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            request.getSession().setAttribute("username", username);
            return "main";
        } catch (Exception e) {
            request.setAttribute("message","用户或者密码错误!!!");
            return "login";
        }


    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }
}

Ready appropriate jsp page after logging operations renderings
login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>用户登陆</h1>
    <div style="color: red">${message}</div>
    <form action="${pageContext.request.contextPath}/login " method="post">
        帐号:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="确定">
        <input type="reset" value="重置">
    </form>
</body>
</html>

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="r" uri="http://shiro.apache.org/tags" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>主界面<%=System.currentTimeMillis()%>,欢迎您:[${sessionScope.username}]</h1>
<ul>
    系统功能列表
    <li>
        <a href="admin/addUser.jsp">用户新增</a>
    </li>
    <li>
        <a href="admin/listUser.jsp">用户查询</a>
    </li>
    <li>
        <a href="admin/resetPwd.jsp">重置用户密码</a>
    </li>
    <li>
        <a href="admin/updateUser.jsp">用户修改</a>
    </li>
    <li>
        <a href="user/updatePwd.jsp">个人密码修改</a>
    </li>
    <li>
        <a href="user/teacher.jsp">老师简介</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/logout">退出系统</a>
    </li>
</ul>
<ul>
    shiro标签
    <li>
        <r:hasPermission name="user:create">
            <a href="admin/addUser.jsp">用户新增</a>
        </r:hasPermission>
    </li>
    <li>
        <a href="admin/listUser.jsp">用户查询</a>
    </li>
    <li>
        <a href="admin/resetPwd.jsp">重置用户密码</a>
    </li>
    <li>
        <r:hasPermission name="user:update">
            <a href="admin/updateUser.jsp">用户修改</a>
        </r:hasPermission>
    </li>
    <li>
        <a href="user/updatePwd.jsp">个人密码修改</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/logout">退出系统</a>
    </li>
</ul>
</body>
</html>

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

shiro annotation style development

Common notes Introduction

@RequiresAuthenthentication: Indicates the current Subject has been authenticated by login; namely Subject.isAuthenticated () to return to true
@RequiresUser: Indicates the current Subject has been authenticated, or by remembering my login
@RequiresGuest: indicates the current Subject no authentication or by remembering I logged on, that is, a visitor
@RequiresRoles (value = { "admin" , "user"}, logical = Logical.AND): Indicates the current Subject require admin role and the User
@RequiresPermissions (value = { "the User: the Delete", "user: b"}, logical = Logical.OR): Indicates the current Subject needs permission user: delete or user: b

Annotated using
Controller layer

 @RequiresUser
    @ResponseBody
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest request){
        return "shiro pass User";
    }

    @RequiresRoles(value = {"2","4"},logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest request){
        return "shiro pass Role";
    }

    @RequiresPermissions(value = {"user:load","user:export"},logical = Logical.AND)
    @ResponseBody
    @RequestMapping("/passAuth")
    public String passAuth(HttpServletRequest request){
        return "shiro pass Auth";
    }

springmvc-servlet.xml arranged interceptor

 <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>

Test results renderings
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
predictions
zs can only view the contents of the authentication button
ls, ww certification authority can see the button content
zdm can see the contents of all the buttons

Published 66 original articles · won praise 4 · Views 962

Guess you like

Origin blog.csdn.net/weixin_45346741/article/details/103376650