Shiro -- Integrated SSM framework

1. Configure web.xml

 <!-- Shiro Frame entrance -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
 
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/actions/*</url-pattern>
    </filter-mapping>

2. Configure shiro.xml

<! -- the id of this bean is consistent with shiro related configuration in web.xml -- >
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <! -- redirect location after no authentication -- >
        <property name="loginUrl" value="/login.jsp"/>
        <! -- where the login successfully jumps -- >
        <property name="successUrl" value="/home.jsp"/>
        <! -- location without permission to jump -- >
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <! -- intercept request -- >
        <property name="filterChainDefinitions">
            <value>
                <! -- login request is not blocked -- >
                /actions/security/login = anon
                <! -- access to admin related requests requires authentication,
                     After the user-defined interceptor permissionFilter, you need the code permission -- >
                /actions/admin/** = authc,permissionFilter,roles[coder]
                /actions/logout = logout
                /actions/** = authc
            </value>
        </property>
        <! -- user defined fi lt er -- >
        <property name="filters">
            <map>
                <entry key="permissionFilter" value-ref="userAccessControlFilter"/>
                <!--<entry key="logout" value-ref="logoutFilter"/>-->
            </map>
        </property>
    </bean>

3. Introducing shiro.xml into spring's configuration file

 <! -- import shiro's configuration file -- >
    <import resource="shiro.xml"/>

4. Custom Realm and custom interceptor

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * Authentication method of forced rewrite
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //Remember, token It encapsulates the account password of the client. The Subject Pull customers and finally bring them here
        String clientUsername = (String) token.getPrincipal();
        //Query account password from database
        String passwordFromDB = userService.findPasswordByName(clientUsername);
        if (passwordFromDB == null) {
            //If no relevant password is found in the database according to the user name entered by the user
            throw new UnknownAccountException();
        }

        /**
         * Returns a credential found in the database. The user name is clientUsername and the password is passwordFromDB. Encapsulate as current return value
         * The next thing the shiro framework does is very simple.
         * It will compare the token you entered with the current database certificate SimpleAuthenticationInfo returned
         * See if it is the same. If the user's account password is the same as the data found in the database, the login is successful
         * Otherwise, your password is wrong
         */
        return new SimpleAuthenticationInfo(clientUsername, passwordFromDB, "UserRealm");
    }

    //To grant authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String yourInputUsername = (String) principals.getPrimaryPrincipal();
        //Construct an authorization certificate
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //Through your user name query database, get your permission information and role information. And stored in the authority voucher
        info.addRole(getYourRoleByUsernameFromDB(yourInputUsername));
        info.addStringPermissions(getYourPermissionByUsernameFromDB(yourInputUsername));
        //Return your permission information
        return info;
    }

    private String getYourRoleByUsernameFromDB(String username) {
        return "coder";
    }

    private List<String> getYourPermissionByUsernameFromDB(String username) {
        return Arrays.asList("code: insert", "code: update");
    }

}
@Component("userAccessControlFilter")
public final class UserAccessControlFilter extends AccessControlFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserAccessControlFilter.class);

    /**
     * That is, whether access is allowed. Return true to indicate whether access is allowed
     * If false is returned, enter the onAccessDenied method of this class for processing
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object object)
            throws Exception {
        final Subject subject = SecurityUtils.getSubject();

        //Judge whether the user has login authentication. If not, return to the login page
        if (subject.getPrincipal() == null || !subject.isAuthenticated()) {
            return Boolean.FALSE;
        }

        final String requestURI = this.getPathWithinApplication(request);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("request URL by:{}", requestURI);
        }
        final String requestHeader = ((HttpServletRequest) request).getHeader("Referer");

        //Anti theft chain handling
        if (requestHeader == null || "".equals(requestHeader)) {
            return Boolean.FALSE;
        }

        //Here you can write the code to judge whether the user has the relevant permission
        //subject.hasRole("Roles required");
        //subject.isPermitted("Required permissions");
        return Boolean.TRUE;
    }

    /**
     * If true is returned, continue with other interceptors
     * If false is returned, the request will be blocked, and the code specifies that the processing method is to redirect to the login page
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse)
            throws Exception {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("The current account does not have corresponding permission!");
        }

        //Redirect to login page
        this.redirectToLogin(servletRequest, servletResponse);
        return Boolean.FALSE;
    }
}

5.login.jsp and Controller

<form action="<c:url value="/actions/security/login"/>" method="post">
    //User name<input type="text" name="username"><br>
    //Password<input type="password" name="password"><br>
    <input type="submit" value="Submission">
</form>
 @RequestMapping(value = "security/login", method = {RequestMethod.POST})
    public String login(@RequestParam("username") String userName, @RequestParam("password") String password) {
        //Get to Subject Facade Object
        Subject subject = getSubject();
        try {
            //Deliver user data to Shiro Frame to do
            //You can customize Realm Authentication method in doGetAuthenticationInfo()Make a breakpoint
            subject.login(new UsernamePasswordToken(userName, password));
        } catch (AuthenticationException exception) {
            if (!subject.isAuthenticated()) {
                //Login failed
                return "fail";
            }
        }
        //Login successfully
        return "home";

    }

    @RequestMapping(value = "admin")
    public String enterAdmin() {
        //Jump to web-inf/pages/admin.jsp page
        return "admin";
    }

6.index. jsp

<a href="<c:url value="/actions/obtainAllUsers"/> ">Test hyperlink</a><br>
<a href="<c:url value="/actions/admin"/> ">Enter administrator page</a><br>
<a href="<c:url value="/actions/logout"/> ">Sign out</a>

 

 

You can only access other links if you log in successfully. Otherwise, all links are login

 

 

 

 

 

 


https://github.com/1017020555/SSM-Shiro.git

Tags: Java Shiro JSP Database xml

Posted on Sat, 07 Mar 2020 07:06:24 -0800 by gabe