shiro受權、註解式開發

Shiro受權

流程:根據前臺傳遞管理的帳號和密碼進行認真,在跳頁面前進行受權驗證,看這個用戶是否有這個權限。java

今天的權限是由5張表構成的:web

寫兩個查詢方法:spring

<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 = #{uid} </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 = #{uid} </select>

ShourUserMapper數據庫

Set<String> getRolesByUserId(Integer uid); Set<String> getPersByUserId(Integer uid);

ShourUserServiceapache

package com.cjh.service; import com.cjh.model.ShiroUser; import java.util.Set; /** * @author * @site * @company * @create 2019-10-13 16:29 */
public interface ShiroUserService { /** * 用於shiro認證 * @param uname * @return */
    public ShiroUser queryByName(String uname); int insert(ShiroUser record); Set<String> getRolesByUserId(Integer uid); Set<String> getPersByUserId(Integer uid); }

ShourUserServiceimplmvc

package com.cjh.service.Impl; import com.cjh.mapper.ShiroUserMapper; import com.cjh.model.ShiroUser; import com.cjh.service.ShiroUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Set; /** * @author * @site * @company * @create 2019-10-13 16:31 */ @Service("shiroUserService") public class ShiroUserServiceImpl implements ShiroUserService { @Autowired private ShiroUserMapper shiroUserMapper; @Override public ShiroUser queryByName(String uname) { return shiroUserMapper.queryByName(uname); } @Override public int insert(ShiroUser record) { return shiroUserMapper.insert(record); }  @Override public Set<String> getRolesByUserId(Integer uid) { return shiroUserMapper.getRolesByUserId(uid); } @Override public Set<String> getPersByUserId(Integer uid) { return shiroUserMapper.getPersByUserId(uid); } }

 

 

MyRealmapp

package com.cjh.shiro; import com.cjh.model.ShiroUser; import com.cjh.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 * @company * @create 2019-10-13 16:19 * 認證過程 * 1.數據原(ini-》數據庫) * 2.doGetAuthenticationInfo將數據庫的用戶信息個shbjet主體認證 * 2.1 須要在當前realm中調用service來驗證,當前用戶是否在數據庫中存在 * 2.2 鹽加密 */
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; } /** * 認證 * @param token 從jsp頁面傳遞過來的用戶名和密碼組成成的一個token對象 * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String userName = token.getPrincipal().toString(); String pwd = token.getPrincipal().toString(); ShiroUser shiroUser = this.shiroUserService.queryByName(userName); AuthenticationInfo info = new SimpleAuthenticationInfo( shiroUser.getUsername(), shiroUser.getPassword(), ByteSource.Util.bytes(shiroUser.getSalt()), this.getName() ); return info; } }

註解式開發

@RequiresAuthenthentication:表示當前Subject已經經過login進行身份驗證;即 Subject.isAuthenticated()返回 truejsp

  @RequiresUser:表示當前Subject已經身份驗證或者經過記住我登陸的ide

  @RequiresGuest:表示當前Subject沒有身份驗證或者經過記住我登陸過,便是遊客身份ui

  @RequiresRoles(value = {"admin","user"},logical = Logical.AND):表示當前Subject須要角色admin和user

  @RequiresPermissions(value = {"user:delete","user:b"},logical = Logical.OR):表示當前Subject須要權限user:delete或者user:b

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>

Controller層

/** * 身份認證的註解 * @param request * @param response * @return */ @RequiresUser @RequestMapping("/passUser") public String passUser(HttpServletRequest request, HttpServletResponse response) { return "admin/addUser"; } /** * 角色認證的註解 * @param request * @param response * @return * * 當方法必須同時具有一、4的角色id,才能被訪問 */ @RequiresRoles(value = {"1","4"},logical = Logical.OR) @RequestMapping("/passRole") public String passRole(HttpServletRequest request, HttpServletResponse response) { return "admin/listUser"; } /** * 權限認證的註解 * @param request * @param response * @return */ @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR) @RequestMapping("/passPer") public String passPer(HttpServletRequest request, HttpServletResponse response) { return "admin/resetPwd"; } /** * 身份、角色、權限認證失敗後的處理方式 * @param request * @param response * @return */ @RequestMapping("/unauthorized") public String xxx(HttpServletRequest request, HttpServletResponse response) { System.out.println("錯誤!!"); return  "unauthorized"; }

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

結果:直接進入會跳到錯誤處理頁面,只有相關權限的才能進入

相關文章
相關標籤/搜索