天天看點

好好程式設計-物流項目13【登入認證-shiro實作】

我們已經完成了使用者的CRUD操作。本文我們來介紹下基于Shiro的登入認證操作。

登入認證

1.整合shiro

1.1 添加依賴

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

1.2 web.xml中注冊

<!-- shiro過慮器,DelegatingFilterProxy通過代理模式将spring容器中的bean和filter關聯起來 -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <!-- 設定true由servlet容器控制filter的生命周期 -->
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param> 
    <!-- 設定spring容器filter的bean id,如果不設定則找與filter-name一緻的bean -->
    <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>shiro</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>      

1.3 自定義Realm

/**
 * 自定義的Realm
 * @author 波波烤鴨
 *
 * [email protected]
 */
public class MyRealm extends AuthorizingRealm{

    /**
     * 認證的方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // TODO Auto-generated method stub
        return null;
    }
    
    /**
     * 授權的方法
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // TODO Auto-generated method stub
        return null;
    }

}      

1.4 添加shiro的配置檔案

好好程式設計-物流項目13【登入認證-shiro實作】
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
 
    <!-- 注冊自定義Realm -->
    <bean class="com.bobo.realm.MyRealm" id="myRealm">
    </bean>
    
    <!-- 注冊SecurityManager -->
    <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
        <!-- 配置自定義Realm -->
        <property name="realm" ref="myRealm"/>
    </bean>
    
    <!-- 注冊ShiroFilterFactoryBean 注意id必須和web.xml中注冊的targetBeanName的值一緻 -->
    <bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiro">
        <!-- 注冊SecurityManager -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 登入位址 如果使用者請求的的位址是 login.do 那麼會對該位址認證-->
        <property name="loginUrl" value="/login.do"/>
        <!-- 登入成功的跳轉位址 -->
        <property name="successUrl" value="/main"/>
        <!-- 通路未授權的頁面跳轉的位址 -->
        <property name="unauthorizedUrl" value="/jsp/refuse.jsp"/>
        <!-- 設定 過濾器鍊 -->
        <property name="filterChainDefinitions">
            <value>
                <!--加載順序從上往下。
                    authc需要認證
                    anon可以匿名通路的資源
                 -->
                 / = anon
                /login = anon
                /images/** = anon
                /css/** = anon
                /js/** = anon
                /lib/** = anon
                /login.do = authc
                /** = authc
            </value>
        </property>
    </bean>
</beans>      

2.登入實作

好好程式設計-物流項目13【登入認證-shiro實作】

2.1登入界面

http://localhost:8082/ 或者 http://localhost:8082/login

好好程式設計-物流項目13【登入認證-shiro實作】
好好程式設計-物流項目13【登入認證-shiro實作】

登入頁面代碼:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>歡迎登入背景管理系統</title>
<link href="/css/style.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" src="/js/jquery.js"></script>
<script src="/js/cloud.js" type="text/javascript"></script>
<script language="javascript">
    $(function() {
        $('.loginbox').css({
            'position' : 'absolute',
            'left' : ($(window).width() - 692) / 2
        });
        $(window).resize(function() {
            $('.loginbox').css({
                'position' : 'absolute',
                'left' : ($(window).width() - 692) / 2
            });
        })
    });
</script>
</head>

<body
    style="background-color: #1c77ac; background-image: url(/images/light.png); background-repeat: no-repeat; background-position: center top; overflow: hidden;">
    <div id="mainBody">
        <div id="cloud1" class="cloud"></div>
        <div id="cloud2" class="cloud"></div>
    </div>

    <div class="logintop">
        <span>歡迎登入背景管理界面平台</span>
        <ul>
            <li><a href="#">回首頁</a></li>
            <li><a href="#">幫助</a></li>
            <li><a href="#">關于</a></li>
        </ul>
    </div>

    <div class="loginbody">
        <span class="systemlogo"></span>
        <div class="loginbox">
            <form action="/login.do" method="post">
                <ul>
                    <li><input name="username" type="text" class="loginuser" />
                    </li>
                    <li><input name="password" type="password" class="loginpwd" />
                    </li>
                    <li><input name="" type="submit" class="loginbtn" value="登入"/>
                        <label>
                            <input name="" type="checkbox" value="" checked="checked" />記住密碼
                        </label>
                        <label>
                            <ahref="#">忘記密碼?</a>
                        </label>
                    </li>
                </ul>
            </form>
        </div>
    </div>

    <div style="display: none">
        <script src='http://v7.cnzz.com/stat.php?id=155540&web_id=155540'
            language='JavaScript' charset='gb2312'></script>
    </div>
</body>
</html>      

2.2登入認證

UserServiceImpl中修改query方法

@Override
public List<User> query(User user) {
    UserExample example = new UserExample();
    if(user!=null){
        if(!"".equals(user.getUserName()) && user.getUserName()!= null){
            // 根據賬号查詢
            example.createCriteria().andUserNameEqualTo(user.getUserName());
        }
    }
    return userMapper.selectByExample(example);
}      

自定義Realm中完成認證的邏輯

@Resource
private IUserService userService;

/**
 * 認證的方法
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    // 擷取送出的賬号
    UsernamePasswordToken t = (UsernamePasswordToken) token;
    // 擷取登入的賬号
    String userName = t.getUsername();
    User user = new User();
    user.setUserName(userName);
    List<User> list = userService.query(user);
    if(list == null || list.size() > 1){
        // 賬号不存在或者使用者過多都傳回null
        return null;
    }
    user = list.get(0);
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),"bobo");
    return info;
}      

完成controller邏輯

@Controller
public class LoginController {

    /**
     * 設定登入失敗跳轉的資源以及擷取失敗的資訊
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/login.do")
    public String login(Model model, HttpServletRequest request) {
        Object ex = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        if (ex != null) {
            System.out.println(ex.toString() + "----------");
        }
        if (UnknownAccountException.class.getName().equals(ex)) {
            System.out.println("----賬号不正确----->");
            model.addAttribute("msg", "賬号不正确");
        } else if (IncorrectCredentialsException.class.getName().equals(ex)) {
            System.out.println("----密碼不正确----->");
            model.addAttribute("msg", "密碼不正确");
        } else {
            System.out.println("----其他錯誤----->");
            model.addAttribute("msg", "其他錯誤");
        }
        return "login";
    }
}      

3.測試

 啟動後随便輸入一個位址,會發現重新跳回了登入頁面

http://localhost:8082/aaabcc

好好程式設計-物流項目13【登入認證-shiro實作】

登入測試

好好程式設計-物流項目13【登入認證-shiro實作】
好好程式設計-物流項目13【登入認證-shiro實作】

賬号密碼正确的情況下進入了main.jsp頁面

好好程式設計-物流項目13【登入認證-shiro實作】

4.退出功能

好好程式設計-物流項目13【登入認證-shiro實作】

top.jsp中修改

好好程式設計-物流項目13【登入認證-shiro實作】

LoginController中添加退出的方法

/**
 * 登出
 * @return
 */
@RequestMapping("/logout.do")
public String logout(){
    SecurityUtils.getSubject().logout();
    return "login";
}      

操作測試即可

繼續閱讀