shiro 身份認證與鹽加密

shiro認證,鹽加密

整合ssm和shiro
導入pom依賴

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.3.2</version>
</dependency>

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

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

配置web.xml

<!-- shiro過濾器定義 -->
<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  <init-param>
    <!-- 該值缺省爲false,表示生命週期由SpringApplicationContext管理,設置爲true則表示由ServletContainer管理 -->
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>shiroFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

逆向生成ShiroUser,此處的代碼就不一 一發出來了
在這裏插入圖片描述

ShiroUserService

package com.lst.service;

import com.lst.model.ShiroUser;

/**
 * @create 2019-10-13 16:12
 */
public interface ShiroUserService {
    /**
     * 用於shiro認證的
     * @param uname
     * @return
     */
    public ShiroUser queryByName(String uname);
	/**
     * 用於註冊用戶
     * @param shiroUser
     * @return
     */
    int insertUser(ShiroUser shiroUser);
}

MyRealm,調用queryByName獲取用戶信息,然後對用戶名和密碼進行判斷

package com.lst.shiro;

import com.lst.model.ShiroUser;
import com.lst.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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @create 2019-10-13 16:02
 *
 * 認證的過程
 * 1、數據源(ini-》數據庫)
 * 2、doGetAuthorizationInfo將數據庫的用戶信息給subject主體做shiro認證的
 *      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 principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 認證
     * @param token            從jsp傳遞過來的用戶名密碼組成的一個token對象
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = token.getPrincipal().toString();
        String pwd = token.getCredentials().toString();
        ShiroUser shiroUser = shiroUserService.queryByName(userName);
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()
        );
        return info;
    }
}

ShiroUserController

package com.lst.controller;

import com.lst.model.ShiroUser;
import com.lst.service.ShiroUserService;
import com.lst.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @create 2019-10-13 16:48
 */
@Controller
public class ShiroUserController {
    @Autowired
    private ShiroUserService shiroUserService;

    @RequestMapping("/login")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        Subject subject = SecurityUtils.getSubject();
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(uname, pwd);
        try {
            subject.login(token);
            return "main";
        } catch (Exception e) {
            req.setAttribute("message", "用戶名或者密碼有誤!!!");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    /**
     * 註冊
     * 把加密後的密碼存入數據庫中
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping("/register")
    public String register(HttpServletRequest req, HttpServletResponse resp){
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        String salt = PasswordHelper.createSalt();
        String credentials = PasswordHelper.createCredentials(pwd, salt);

        ShiroUser shiroUser=new ShiroUser();
        shiroUser.setUsername(uname);
        shiroUser.setPassword(credentials);
        shiroUser.setSalt(salt);
        int n = shiroUserService.insertUser(shiroUser);
        if(n>0){
            req.setAttribute("message","註冊成功");
            return "login";
        }
        else{
            req.setAttribute("message","註冊失敗");
            return "login";
        }
    }
}

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用戶登錄</title>
</head>
<body>
    <h1>用戶登陸</h1>
    <div style="color: red">${message}</div>
    <form action="${pageContext.request.contextPath}/login" method="post">
        帳號:<input type="text" name="username"><br>
        密碼:<input type="password" name="password"><br>
        <input type="submit" value="確定">
        <input type="reset" value="重置">
    </form>
</body>
</html

register.sjp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用戶註冊</title>
</head>
<body>
    <h1>用戶註冊</h1>
    <div style="color: red">${message}</div>
    <form action="${pageContext.request.contextPath}/register" method="post">
        帳號:<input type="text" name="username"><br>
        密碼:<input type="password" name="password"><br>
        <input type="submit" value="註冊">
        <input type="reset" onclick="location.href='${pageContext.request.contextPath}/login.jsp'" value="返回">
    </form>
</body>
</html>

註冊界面效果:
在這裏插入圖片描述
在這裏插入圖片描述
我們在界面上輸入的密碼是‘123’,但是存在數據庫內的密碼是經過加密後的隨機字符串
over。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章