目的:
Shiro認證
鹽加密工具類
Shiro認證
1.導入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>
2.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>
設置五個表並且用逆向生成相應的mapper
generatorConfig.xml
<table schema="" tableName="t_shiro_permission" domainObjectName="ShiroPermission" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table schema="" tableName="t_shiro_role" domainObjectName="ShiroRole" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table schema="" tableName="t_shiro_role_permission" domainObjectName="ShiroRolePermission" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table schema="" tableName="t_shiro_user" domainObjectName="ShiroUser" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table schema="" tableName="t_shiro_user_role" domainObjectName="ShiroUserRole" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table>
ShiroUserMapper
@Repository public interface ShiroUserMapper { int deleteByPrimaryKey(Integer userid); int insert(ShiroUser record); int insertSelective(ShiroUser record); ShiroUser selectByPrimaryKey(Integer userid); int updateByPrimaryKeySelective(ShiroUser record); int updateByPrimaryKey(ShiroUser record); ShiroUser queryByName(String userName); }
ShiroUserMapper.xml
<select id="queryByName" resultType="com.huangting.model.ShiroUser" parameterType="java.lang.String"> select <include refid="Base_Column_List" /> from t_shiro_user where username = #{username} </select>
ShiroUserService
/** * @author 黃大娘 * @company dogsun * @oreata 2019-10-13 20:19 */ public interface ShiroUserService{ /** * 用於認證的 * @param userName * @return */ public ShiroUser queryByName(String userName); /** * 注冊 * @param shiroUser * @return */ int insert(ShiroUser shiroUser); }
ShiroUserServiceImpl
/** * @author 黃大娘 * @company dogsun * @oreata 2019-10-13 20:23 */ @Service("shiroUserService") public class ShiroUserServiceImpl implements ShiroUserService { @Autowired private ShiroUserMapper shiroUserMapper; @Override public ShiroUser queryByName(String userName) { return shiroUserMapper.queryByName(userName); } @Override public int insert(ShiroUser shiroUser) { return shiroUserMapper.insert(shiroUser); } }
MyRealm
對新建方法獲取的用戶信息進行認證
/** * @author 黃大娘 * @company dogsun * @oreata 2019-10-13 19:54 * 認證的過程: * 1、數據源(ini=>數據庫) * 2、doGetAuthenticationInfo將數據庫的用戶信息給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 = this.shiroUserService.queryByName(userName); SimpleAuthenticationInfo info = new SimpleAuthenticationInfo( shiroUser.getUsername(), shiroUser.getPassword(), ByteSource.Util.bytes(shiroUser.getSalt()), this.getName() ); return info; } }
applicationContext-shiro.xml
<?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"> <!--配置自定義的Realm--> <bean id="shiroRealm" class="com.huangting.shrio.MyRealm"> <property name="shiroUserService" ref="shiroUserService" /> <!--注意:重要的事情說三次~~~~~~此處加密方式要與用戶注冊時的算法一致 --> <!--注意:重要的事情說三次~~~~~~此處加密方式要與用戶注冊時的算法一致 --> <!--注意:重要的事情說三次~~~~~~此處加密方式要與用戶注冊時的算法一致 --> <!--以下三個配置告訴shiro將如何對用戶傳來的明文密碼進行加密--> <property name="credentialsMatcher"> <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <!--指定hash算法為MD5--> <property name="hashAlgorithmName" value="md5"/> <!--指定散列次數為1024次--> <property name="hashIterations" value="1024"/> <!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存儲--> <property name="storedCredentialsHexEncoded" value="true"/> </bean> </property> </bean> <!--注冊安全管理器--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroRealm" /> </bean> <!--Shiro核心過濾器--> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,這個屬性是必須的 --> <property name="securityManager" ref="securityManager" /> <!-- 身份驗證失敗,跳轉到登錄頁面 --> <property name="loginUrl" value="/login"/> <!-- 身份驗證成功,跳轉到指定頁面 --> <!--<property name="successUrl" value="/index.jsp"/>--> <!-- 權限驗證失敗,跳轉到指定頁面 --> <property name="unauthorizedUrl" value="/unauthorized.jsp"/> <!-- Shiro連接約束配置,即過濾鏈的定義 --> <property name="filterChainDefinitions"> <value> <!-- 注:anon,authcBasic,auchc,user是認證過濾器 perms,roles,ssl,rest,port是授權過濾器 --> <!--anon 表示匿名訪問,不需要認證以及授權--> <!--authc表示需要認證 沒有進行身份認證是不能進行訪問的--> <!--roles[admin]表示角色認證,必須是擁有admin角色的用戶才行--> /user/login=anon /user/updatePwd.jsp=authc /admin/*.jsp=roles[admin] /user/teacher.jsp=perms["user:update"] <!-- /css/** = anon /images/** = anon /js/** = anon / = anon /user/logout = logout /user/** = anon /userInfo/** = authc /dict/** = authc /console/** = roles[admin] /** = anon--> </value> </property> </bean> <!-- Shiro生命周期,保證實現了Shiro內部lifecycle函數的bean執行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans>
ShiroUserController
/** * @author 黃大娘 * @company dogsun * @oreata 2019-10-14 21:28 */ @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"; } @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 insert = shiroUserService.insert(shiroUser); if(insert>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</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="button" onclick="location.href='${pageContext.request.contextPath}/register.jsp'" value="注冊"> <input type="reset" value="重置"> </form> </body> </html>
register.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2019/10/14 Time: 21:33 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>用戶注冊</title> </head> <body> <h1>用戶注冊</h1> <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="button" onclick="location.href='login.jsp'" value="返回"> </form> </body> </html>
鹽加密工具類
PasswordHelper工具類
import org.apache.shiro.crypto.RandomNumberGenerator; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.SimpleHash; /** * 用於shiro權限認證的密碼工具類 */ public class PasswordHelper { /** * 隨機數生成器 */ private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator(); /** * 指定hash算法為MD5 */ private static final String hashAlgorithmName = "md5"; /** * 指定散列次數為1024次,即加密1024次 */ private static final int hashIterations = 1024; /** * true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存儲 */ private static final boolean storedCredentialsHexEncoded = true; /** * 獲得加密用的鹽 * * @return */ public static String createSalt() { return randomNumberGenerator.nextBytes().toHex(); } /** * 獲得加密后的憑證 * * @param credentials 憑證(即密碼) * @param salt 鹽 * @return */ public static String createCredentials(String credentials, String salt) { SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations); return storedCredentialsHexEncoded ? simpleHash.toHex() : simpleHash.toBase64(); } /** * 進行密碼驗證 * * @param credentials 未加密的密碼 * @param salt 鹽 * @param encryptCredentials 加密后的密碼 * @return */ public static boolean checkCredentials(String credentials, String salt, String encryptCredentials) { return encryptCredentials.equals(createCredentials(credentials, salt)); } public static void main(String[] args) { //鹽 String salt = createSalt(); System.out.println(salt); System.out.println(salt.length()); //憑證+鹽加密后得到的密碼 String credentials = createCredentials("123456", salt); System.out.println(credentials); System.out.println(credentials.length()); boolean b = checkCredentials("123456", salt, credentials); System.out.println(b); } }