shiro 使用

在使用Shiro標籤庫前,首先須要在JSP引入shiro標籤:
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>java

一、介紹Shiro的標籤guest標籤 :驗證當前用戶是否爲「訪客」,即未認證(包含未記住)的用戶。
<shiro:guest>
Hi there!  Please <a href="login.jsp">Login</a> or <a href="signup.jsp">Signup</a> today!
</shiro:guest>web

二、user標籤 :認證經過或已記住的用戶。
<shiro:user>
 Welcome back John!  Not John? Click <a href="login.jsp">here<a> to login.
</shiro:user>apache

三、authenticated標籤 :已認證經過的用戶。不包含已記住的用戶,這是與user標籤的區別所在。
<shiro:authenticated>
    <a href="updateAccount.jsp">Update your contact information</a>.
</shiro:authenticated>app

四、notAuthenticated標籤 :未認證經過用戶,與authenticated標籤相對應。與guest標籤的區別是,該標籤包含已記住用戶。
<shiro:notAuthenticated>
    Please <a href="login.jsp">login</a> in order to update your credit card information.
</shiro:notAuthenticated>jsp

 

五、principal 標籤 :輸出當前用戶信息,一般爲登陸賬號信息。
Hello, <shiro:principal/>, how are you today?ide

 

六、hasRole標籤 :驗證當前用戶是否屬於該角色。
<shiro:hasRole name="administrator">
    <a href="admin.jsp">Administer the system</a>
</shiro:hasRole>this

 

七、lacksRole標籤 :與hasRole標籤邏輯相反,當用戶不屬於該角色時驗證經過。
<shiro:lacksRole name="administrator">
    Sorry, you are not allowed to administer the system.
</shiro:lacksRole>url

 

八、hasAnyRole標籤 :驗證當前用戶是否屬於如下任意一個角色。
<shiro:hasAnyRoles name="developer, project manager, administrator">
    You are either a developer, project manager, or administrator.
</shiro:lacksRole>spa

 

九、hasPermission標籤 :驗證當前用戶是否擁有指定權限。
<shiro:hasPermission name="user:create">
    <a href="createUser.jsp">Create a new User</a>
</shiro:hasPermission>.net

十、lacksPermission標籤 :與hasPermission標籤邏輯相反,當前用戶沒有制定權限時,驗證經過。    
<shiro:hasPermission name="user:create">
    <a href="createUser.jsp">Create a new User</a>
</shiro:hasPermission>

 


=======================================================================================================
1.web.xml 添加shiro入口
 <!--- shiro 1.2 -->
    <listener>
        <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>shiroEnvironmentClass</param-name>
        <param-value>org.apache.shiro.web.env.IniWebEnvironment</param-value><!-- 默認先從/WEB-INF/shiro.ini,若是沒有找classpath:shiro.ini -->
    </context-param>
    <context-param>
        <param-name>shiroConfigLocations</param-name>
        <param-value>classpath:shiro.ini</param-value>
    </context-param>
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

2.shiro.ini   在src下面添加shiro配置文件
[main]
myRealm=com.aih.plugin.shiro.MyAuthorizingRealm
securityManager.realms=$myRealm
#默認是/login.jsp
authc.loginUrl=/login
roles.unauthorizedUrl=/unauthorized
perms.unauthorizedUrl=/unauthorized
logout.redirectUrl=/login

[urls]
/logout2=logout
/login=anon
/logout=anon
/unauthorized=anon
/static/**=anon
/authenticated=authc

 

3.自定義角色和用戶菜單權限,須要重寫realms
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
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.dodo.framework.helper.BeanHelper;

import com.aih.admin.model.system.Menu;
import com.aih.admin.model.system.Role;
import com.aih.admin.model.system.User;
import com.aih.admin.service.system.MenuService;
import com.aih.admin.service.system.RoleService;
import com.aih.admin.service.system.UserService;

public class MyAuthorizingRealm extends AuthorizingRealm{
    UserService userService=BeanHelper.getBean(UserService.class);
    MenuService menuService =BeanHelper.getBean(MenuService.class);
    RoleService roleService=BeanHelper.getBean(RoleService.class);
    /*
     * 檢查用戶是否擁有對應菜單的權限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        String username = (String) getAvailablePrincipal(principals);
        User user = userService.getUserByLoginName(username);
        if(user!=null){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Map<String,String> p=new HashMap<String,String>();
            List<Menu> list =menuService.getList(p);
            for (Menu menu : list){
                if (StringUtils.isNotBlank(menu.getPermission())){
                    // 添加基於Permission的權限信息
                    for (String permission : StringUtils.split(menu.getPermission(),",")){
                        info.addStringPermission(permission);
                    }
                }
            }
            // 添加用戶權限
            info.addStringPermission("user");
            // 添加用戶角色信息
            List<Role> roles=roleService.getRolesByLoginName(username);
            for (Role role : roles){
                info.addRole(role.getEnname());
            }
            return info;
        }else{
            return null;
        }
        
    }

    /*
     * 檢查用戶是否登陸權限
     */
    @SuppressWarnings("unused")
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token){
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }
        String password="123";
        if(password==null){
            throw new AccountException("account error...");
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
        return info;
    }


}

4.對應的加上權限代碼 Subject subject = SecurityUtils.getSubject(); subject.checkRole("admin"); subject.checkPermission("sys:dict:view");

相關文章
相關標籤/搜索