06-SSM integrated Shiro integrated menu example

* SSM integrated Shiro integrated menu example

 

*SSM integrated Shiro for authentication

 

* copy RoleUsers,RolePermissions

* add passwordSalt to the User class (and survive the set/get method)

           

* add roles, permissions, user roles in database hx01

 

*Modify user table

*Add dependency

<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>

* MyBatisRealm

/**
 * @author xiaozhao
 */
public class MyBatisRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper mUserMapper;
    private boolean permissionsLookupEnabled;
    public boolean isPermissionsLookupEnabled() {
        return permissionsLookupEnabled;
    }

    public void setPermissionsLookupEnabled(boolean permissionsLookupEnabled) {
        this.permissionsLookupEnabled = permissionsLookupEnabled;
    }
    private boolean havingSalt;

    public boolean isHavingSalt() {
        return havingSalt;
    }

    public void setHavingSalt(boolean havingSalt) {
        this.havingSalt = havingSalt;
    }

    // Authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken mtoken= (UsernamePasswordToken) token;
        String username = mtoken.getUsername();
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }
        List<User> users = mUserMapper.queryUsersByUsername(username);
        if(users==null || users.size()<=0){
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }
        String passord=users.get(0).getPsw();
        if(passord==null){
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(username,passord.toCharArray(),getName());
        if (havingSalt){
            info.setCredentialsSalt(ByteSource.Util.bytes(users.get(0).getPasswordSalt()));
        }
        return info;
    }

    // To grant authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //null usernames are invalid
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        String username= (String) getAvailablePrincipal(principals);
        Set<UserRoles> userRoles = mUserMapper.queryUserRolesByUsername(username);
        Set<String> roleNames=new LinkedHashSet<String>();
        Set<String> permissions=new LinkedHashSet<String>();
        for(UserRoles role:userRoles){
            roleNames.add(role.getRoleName());
            if(permissionsLookupEnabled) {
                Set<RolePermissions> rolePermissions = mUserMapper.queryRolePermissionsByRoleName(role.getRoleName());
                for (RolePermissions permission : rolePermissions) {
                    permissions.add(permission.getPermission());
                }
            }
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roleNames);
        info.setStringPermissions(permissions);
        return info;
    }


}

* modify UserMapper, UserMapper.xml (same as the example of MyBatis inheriting Shiro)

* add in LoginController

@RequestMapping("/mainui")
    public String toMain(HttpSession session){
        return "main";
    }

* comment the code of the spring MVC interceptor before

 

*web.xml configuration file

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>SSM</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <filter>
        <filter-name>CharacterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>DelegatingFilterProxy</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>shiroFilter</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>DelegatingFilterProxy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/jsps/404.jsp</location>
    </error-page>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.gif</url-pattern>

    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.bmp</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.png</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.otf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.svg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.ttf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.woff</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.woff2</url-pattern>
    </servlet-mapping>
</web-app>

The * spring-shiro.xml file (shiro.ini)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <property name="loginUrl" value="/login"></property>
        <property name="successUrl" value="/mainui"></property>
        <property name="filterChainDefinitions">
            <value>
                /images/** = anon
                /js/** = anon
                /bootstrap/** = anon
                /bootstraptabs/** = anon
                /css/** = anon
                /hightchart/** = anon
                /bootstraptabs/** = anon
                /images/** = anon
                /jquery/** = anon
                /ztree/** = anon
                /index.jsp = anon
                /mainui =anon
                /** = authc
            </value>
        </property>
    </bean>
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="mRealm"></property>
    </bean>
    <bean id="mRealm" class="com.hx.ssm.realm.MyBatisRealm">
        <property name="havingSalt" value="true"></property>
        <property name="permissionsLookupEnabled" value="true"/>
        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
    </bean>

    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="md5"/>
        <property name="hashIterations" value="1"/>
        <property name="storedCredentialsHexEncoded" value="true"/>
    </bean>


</beans>

* import shiro file in spring.xml

<import resource="classpath:spring-shiro.xml"></import>

*Modify login page

* authentication passed, but did not jump to successUrl

Solution (refer to FormAuthenticationFilter)

Rewrite FormAuthenticationFilter

public class MFormAuthenticationFilter extends FormAuthenticationFilter {


    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        String successUrl = getSuccessUrl();
        if(successUrl==null || successUrl.trim().length()==0){
            throw new IllegalStateException("Success URL not available via saved request or via the " +
                    "successUrlFallback method parameter. One of these must be non-null for " +
                    "issueSuccessRedirect() to work.");
        }
        HttpServletResponse res= (HttpServletResponse) response;
        res.sendRedirect(request.getServletContext().getContextPath()+successUrl);
        return false;
    }
    
}

 

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <property name="loginUrl" value="/login"></property>
        <property name="successUrl" value="/mainui"></property>
        <property name="filters">
            <map>
                <entry key="mauthc1" value-ref="mauthc"/>
            </map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                /images/** = anon
                /js/** = anon
                /bootstrap/** = anon
                /bootstraptabs/** = anon
                /css/** = anon
                /hightchart/** = anon
                /bootstraptabs/** = anon
                /images/** = anon
                /jquery/** = anon
                /ztree/** = anon
                /index.jsp = anon
                /mainui =anon
                /** = mauthc1
            </value>
        </property>
    </bean>
    <bean id="mauthc" class="com.hx.ssm.filter.MFormAuthenticationFilter"/>
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="mRealm"></property>
    </bean>
    <bean id="mRealm" class="com.hx.ssm.realm.MyBatisRealm">
        <property name="havingSalt" value="true"></property>
        <property name="permissionsLookupEnabled" value="true"/>
        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
    </bean>

    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="md5"/>
        <property name="hashIterations" value="1"/>
        <property name="storedCredentialsHexEncoded" value="true"/>
    </bean>


</beans>

* implementation of rememberMe function

Add name as rememberMe field

 

<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="sessionIdUrlRewritingEnabled" value="false"></property>
        <property name="sessionIdCookie" ref="cookie"></property>
    </bean>
    <bean class="org.apache.shiro.web.servlet.SimpleCookie" id="cookie">
        <constructor-arg name="name" value="lg_session_id"></constructor-arg>
        <property name="maxAge" value="-1"></property>
        <property name="path" value="/ssm"></property>
        <property name="domain" value="localhost"></property>
    </bean>

*Override in MFormAuthenticationFilter

 @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        return (subject.isAuthenticated() || subject.isRemembered());
    }

* different roles see different menus

* copy include.jsp file

<%@ page import="org.apache.shiro.SecurityUtils" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

* in main.jsp

<%@ include file="include.jsp"%>

* different user login displays different user information

<div  style="height: 45px;width: 100%;background-color: #e7e7e7">
    <div>
        <span>management system</span>
    </div>
    <div>
        <form class="form-inline" role="form" action="${pageContext.request.contextPath}/logout" method="post">
            <div class="form-group">
                <span><shiro:hasRole name="admin">Current user: system administrator</shiro:hasRole>
                      <shiro:hasRole name="user">Current user:<shiro:principal></shiro:principal></shiro:hasRole>
                </span>
            </div>
            <button type="submit" class="btn btn-link">Sign out</button>
        </form>
    </div>
</div>

 

*Add exit function

*Add roles menu

CREATE TABLE roles_menu(
  id BIGINT AUTO_INCREMENT,
  role_name VARCHAR(100),
  menu INT,
  CONSTRAINT pk_roles_menu PRIMARY KEY(id)
) CHARSET=utf8 ENGINE=INNODB;

CREATE UNIQUE INDEX idx_roles_menu ON roles_permissions(role_name, menu);

 

/**
 * @author xiaozhao
 */
public interface ZNodeMapper {
    /**
     * Query all nodes
     * @return
     */
    List<ZNode> queryAllZNodes();

    /**
     * Query the corresponding menu according to different users (corresponding to different roles)
     * @param username
     * @return
     */
    List<ZNode> queryZNodesByUserName(String username);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hx.ssm.dao.ZNodeMapper">
    <select id="queryAllZNodes"  resultType="ZNode">
        SELECT id,pid,NAME,OPEN,FILE FROM znode
    </select>

    <select id="queryZNodesByUserName" parameterType="string" resultType="ZNode">
        SELECT id,pid,NAME,OPEN,FILE FROM znode WHERE id IN(SELECT menu FROM roles_menu WHERE role_name IN(SELECT role_name FROM user_roles WHERE username=#{username}));
    </select>
</mapper>

 * service

/**
 * @author xiaozhao
 */
@Service("nodeService")
public class ZNodeServiceImpl implements ZNodeService {
    @Autowired
    private ZNodeMapper mZNodeMapper;
    @Override
    public BaseDataVo getAllZNodes() {
        ZnodeDataVo znodeDataVo=new ZnodeDataVo();
        List<ZNode> zNodes = mZNodeMapper.queryAllZNodes();
        znodeDataVo.setzNodes(zNodes);
        return znodeDataVo;
    }

    @Override
    public BaseDataVo getZNodesByUserName(String username) {
        ZnodeDataVo znodeDataVo=new ZnodeDataVo();
        List<ZNode> zNodes = mZNodeMapper.queryZNodesByUserName(username);
        znodeDataVo.setzNodes(zNodes);
        return znodeDataVo;
    }
}

 * controller

/**
 * @author xiaozhao
 */
@Controller
@RequestMapping("/znode")
public class ZNodeController {
    @Autowired
    private ZNodeService mZNodeService;
    @Autowired
    private SecurityManager mSecurityManager;
    @RequestMapping(value = "/allZnodes",method = RequestMethod.POST)
    @ResponseBody
    public BaseDataVo queryAllZNode() {
        return mZNodeService.getAllZNodes();
    }

    @RequestMapping(value = "/username/{username}")
    @ResponseBody
    public BaseDataVo queryZnodesByUserName(@PathVariable("username") String username, HttpSession session){
        ZnodeDataVo znodeDataVo= (ZnodeDataVo) mZNodeService.getZNodesByUserName(username);
        return znodeDataVo;
    }

    @RequestMapping("/ui")
    public String main(Model model){
        return "main";
    }
}

 * view

In main.jsp

 url: "${pageContext.request.contextPath}/znode/username/<shiro:principal/>",
                type: "POST"

 

 

Control of fine granularity permission

 

 * shiro1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<!DOCTYPE html>
<%@ include file="include.jsp" %>
<html>
<head>
    <meta charset="utf-8">
    <title>Welcome to login</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css">
    <script src="${pageContext.request.contextPath}/jquery/jquery-3.3.1.js"></script>
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<shiro:hasPermission name="shiro:create">
    <button type="button" class="btn btn-primary">Add to</button>
</shiro:hasPermission>
<shiro:hasPermission name="shiro:delete">
    <button type="button" class="btn btn-primary">delete</button>
</shiro:hasPermission>
<shiro:hasPermission name="shiro:update">
    <button type="button" class="btn btn-primary">To update</button>
</shiro:hasPermission>
<shiro:hasPermission name="shiro:query">
    <button type="button" class="btn btn-primary">query</button>
</shiro:hasPermission>

</body>
</html>

 * shiro2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<!DOCTYPE html>
<%@ include file="include.jsp" %>
<html>
<head>
    <meta charset="utf-8">
    <title>shiro Permissions test</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css">
    <script src="${pageContext.request.contextPath}/jquery/jquery-3.3.1.js"></script>
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        function checkPermisstion1() {
            $.ajax({
                url : "${pageContext.request.contextPath}/shiro/create",
                type:"GET",
                dataType: "json",
                success: function (data, status) {
                    var content = JSON.parse(JSON.stringify(data));
                    if(content.isPermitted){
                        alert("Add success");
                    }else {
                        alert("You do not have permission to add");
                    }
                }
            }
            )
        }
        function checkPermisstion2() {
            $.ajax({
                    url : "${pageContext.request.contextPath}/shiro/delete",
                    type:"GET",
                    dataType: "json",
                    success: function (data, status) {
                        var content = JSON.parse(JSON.stringify(data));
                        if(content.isPermitted){
                            alert("Delete successful");
                        }else {
                            alert("You do not have permission to delete");
                        }
                    }
                }
            )
        }

        function checkPermisstion3() {
            $.ajax({
                    url : "${pageContext.request.contextPath}/shiro/update",
                    type:"GET",
                    dataType: "json",
                    success: function (data, status) {
                        var content = JSON.parse(JSON.stringify(data));
                        if(content.isPermitted){
                            alert("Update success");
                        }else {
                            alert("You do not have permission to update");
                        }
                    }
                }
            )
        }
        function checkPermisstion4() {
            $.ajax({
                    url : "${pageContext.request.contextPath}/shiro/query",
                    type:"GET",
                    dataType: "json",
                    success: function (data, status) {
                        var content = JSON.parse(JSON.stringify(data));
                        if(content.isPermitted){
                            alert("query was successful");
                        }else {
                            alert("You do not have permission to query");
                        }
                    }
                }
            )
        }

    </script>
</head>
<body>

<button type="button" class="btn btn-primary" onclick="checkPermisstion1()">Add to</button>
<button type="button" class="btn btn-primary" onclick="checkPermisstion2()">delete</button>
<button type="button" class="btn btn-primary" onclick="checkPermisstion3()">To update</button>
<button type="button" class="btn btn-primary" onclick="checkPermisstion4()">query</button>

</body>
</html>

* entity

/**
 * @author xiaozhao
 */
public class ShiroOutDataVo extends BaseDataVo {
    private boolean isPermitted;

    public boolean isPermitted() {
        return isPermitted;
    }

    public void setPermitted(boolean permitted) {
        isPermitted = permitted;
    }

    @Override
    public String toString() {
        return "ShiroOutDataVo{" +
                "isPermitted=" + isPermitted +
                ", code=" + code +
                ", result='" + result + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ShiroOutDataVo that = (ShiroOutDataVo) o;
        return isPermitted == that.isPermitted;
    }

    @Override
    public int hashCode() {
        return Objects.hash(isPermitted);
    }
}

* ShiroController

/**
 * @author xiaozhao
 */
@Controller
@RequestMapping("/shiro")
public class ShiroController {
    @RequestMapping("/ui1")
    public String shiro1(){
        return "shiro1";
    }

    @RequestMapping("/ui2")
    public String shiro2(){
        return "shiro2";
    }

    @RequestMapping("/create")
    @ResponseBody
    public BaseDataVo create(){
        BaseDataVo baseDataVo=new ShiroOutDataVo();
        Subject subject = SecurityUtils.getSubject();
        ((ShiroOutDataVo) baseDataVo).setPermitted(subject.isPermitted("shiro:create"));
        return baseDataVo;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public BaseDataVo delete(){
        BaseDataVo baseDataVo=new ShiroOutDataVo();
        Subject subject = SecurityUtils.getSubject();
        ((ShiroOutDataVo) baseDataVo).setPermitted(subject.isPermitted("shiro:delete"));
        return baseDataVo;
    }

    @RequestMapping("/update")
    @ResponseBody
    public BaseDataVo update(){
        BaseDataVo baseDataVo=new ShiroOutDataVo();
        Subject subject = SecurityUtils.getSubject();
        ((ShiroOutDataVo) baseDataVo).setPermitted(subject.isPermitted("shiro:update"));
        return baseDataVo;
    }
    @RequestMapping("/query")
    @ResponseBody
    public BaseDataVo query(){
        BaseDataVo baseDataVo=new ShiroOutDataVo();
        Subject subject = SecurityUtils.getSubject();
        ((ShiroOutDataVo) baseDataVo).setPermitted(subject.isPermitted("shiro:query"));
        return baseDataVo;
    }
}

 

* Ehcache cache explanation

Reference the extended Ehcache explanation

Explanation of Ehcache cache

Ehcache combined with mybatis

shiro in combination with cache Ehcache

 

* close and open again or query the database

 

*Add Shiro cache

Add dependency

<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.4.0</version>
        </dependency>

* configuration in spring-shiro.xml

  <bean id="ehcacheshiro" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
    </bean>

* click permission test one again, no access to the database

 

* hidden bug resolution

If you know the principle, you can access other URLs directly through your browser after the login authentication

* solutions

CREATE TABLE roles_urls(
  id BIGINT AUTO_INCREMENT,
  role_name VARCHAR(100),
  url VARCHAR(50),
  CONSTRAINT pk_roles_urls PRIMARY KEY(id)
) CHARSET=utf8 ENGINE=INNODB;

   /**
* query the accessible url by role name
     * @param roleName
     * @return
     */
    Set<RoleUrls> queryRoleUrlsByUserName(String username);
  <select id="queryRoleUrlsByUserName" parameterType="string" resultType="RoleUrls">
        SELECT id,role_name as roleName,url FROM roles_urls WHERE role_name =(SELECT role_name FROM user_roles WHERE username=#{username});
    </select>

/**
 * @author xiaozhao
 */
public class MFormAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private UserMapper mUserMapper;
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        String successUrl = getSuccessUrl();
        if(successUrl==null || successUrl.trim().length()==0){
            throw new IllegalStateException("Success URL not available via saved request or via the " +
                    "successUrlFallback method parameter. One of these must be non-null for " +
                    "issueSuccessRedirect() to work.");
        }
        String username= (String) subject.getPrincipal();
        Set<RoleUrls> roleUrls = mUserMapper.queryRoleUrlsByUserName(username);
        HttpServletRequest req= (HttpServletRequest) request;
        List<String> urls=new ArrayList<String>();
        for(RoleUrls roleUrl:roleUrls){
            urls.add(roleUrl.getUrl());
        }
        req.getSession().setAttribute(username,urls);
        HttpServletResponse res= (HttpServletResponse) response;
        res.sendRedirect(request.getServletContext().getContextPath()+successUrl);
        return false;
    }
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        HttpServletRequest req= (HttpServletRequest) request;
        Object attr = req.getSession().getAttribute((String) subject.getPrincipal());
        boolean match=false;
        if(attr!=null){
            String uri=req.getRequestURI();
            System.out.println("uri:"+uri);
            List<String> urls= (List<String>) attr;
            System.out.println(urls);
            if(urls.contains("*")){
                match=true;
            }
            for(String url:urls){
                if(uri.contains(url)){
                    match=true;
                }
            }
        }
        return (subject.isAuthenticated() || subject.isRemembered()) && match;
    }
}

 

* access to url without permission will jump to login page

 

 

Tags: Programming Shiro Apache JSP xml

Posted on Sun, 01 Dec 2019 07:19:10 -0800 by ProblemHelpPlease