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>
通过逆向工程将五张表生成对应的model、mapper
Mapper中新增
<select id="queryByName" resultType="com.liuwenwu.model.ShiroUser" parameterType="java.lang.String"> select <include refid="Base_Column_List" /> from t_shiro_user where username =#{uname} </select>
ShiroUserService
package com.liuwenwu.service; import com.liuwenwu.model.ShiroUser; /** * @author LWW * @site www.lww.com * @company * @create 2019-10-13 16:11 */ public interface ShiroUserService { /** * 用于shiro认证 * @param uname * @return */ public ShiroUser queryByName(String uname); /** * 新增用户 * @param record * @return */ public int insert(ShiroUser record); }
ShiroUserServiceImpl
package com.liuwenwu.service.impl; import com.liuwenwu.mapper.ShiroUserMapper; import com.liuwenwu.model.ShiroUser; import com.liuwenwu.service.ShiroUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author LWW * @site www.lww.com * @company * @create 2019-10-13 16:14 */ @Service("shiroUserService") public class ShiroUserServiceImpl implements ShiroUserService { @Autowired private ShiroUserMapper shiroUserMapper; @Override public ShiroUser queryByName(String uname) { return shiroUserMapper.queryByName(uname); } /** * 新增用户 * @param record * @return */ @Override public int insert(ShiroUser record) { return shiroUserMapper.insert(record); } }
MyRealm.java
package com.liuwenwu.shiro; import com.liuwenwu.model.ShiroUser; import com.liuwenwu.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; /** * @author LWW * @site www.lww.com * @company * @create 2019-10-13 16:02 * * 认证的过程 * 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; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { return null; } /** * 认证 * @param token 从jsp传递过来的用户名,密码组合成的一个token对象 * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // jsp获取用户名,密码 String userName = token.getPrincipal().toString(); String pwd = token.getCredentials().toString(); // 比对 ShiroUser shiroUser = this.shiroUserService.queryByName(userName); // 认证 AuthenticationInfo info= new SimpleAuthenticationInfo( shiroUser.getUsername(),//用户名 shiroUser.getPassword(),//密码 ByteSource.Util.bytes(shiroUser.getSalt()),//盐 this.getName()//当前realm的名字 ); 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.liuwenwu.shiro.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
package com.liuwenwu.controller; import com.liuwenwu.model.ShiroUser; import com.liuwenwu.service.ShiroUserService; import com.liuwenwu.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; /** * @author LWW * @site www.lww.com * @company * @create 2019-10-13 16:52 */ @Controller public class ShiroUserController { @Autowired private ShiroUserService shiroUserService; /** * 登录 * @param req * @param resp * @return */ @RequestMapping("/login") public String login(HttpServletRequest req, HttpServletResponse resp){ Subject subject = SecurityUtils.getSubject();//拿到登录主体 // 拿到jsp传递过来的用户名,密码 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"; } } /** * 登出 * @param req * @param resp * @return */ @RequestMapping("/logout") public String logout(HttpServletRequest req, HttpServletResponse resp){ Subject subject = SecurityUtils.getSubject();//拿到登录主体 subject.logout(); return "login"; } /** * 新增用户 * @param shiroUser * @param req * @param resp * @return */ @RequestMapping("/add") public String add(ShiroUser shiroUser, HttpServletRequest req, HttpServletResponse resp){ // 获取前台出过来的用户名和密码 String uname =req.getParameter("username1"); String pwd = req.getParameter("password1"); shiroUser.setUsername(uname); // 使用工具类生成盐 String salt = PasswordHelper.createSalt(); shiroUser.setSalt(salt); // 盐加密后得到的密码 String credentials = PasswordHelper.createCredentials(pwd, salt); shiroUser.setPassword(credentials); // 新增 int aa =this.shiroUserService.insert(shiroUser); if(aa>0){ req.setAttribute("message","成功"); return "login"; } else{ req.setAttribute("message","失败"); return "login"; } } }
PasswordHelper工具类
package com.liuwenwu.util; import org.apache.shiro.crypto.RandomNumberGenerator; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.SimpleHash; 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("123", salt); System.out.println(credentials); System.out.println(credentials.length()); boolean b = checkCredentials("123", salt, credentials); System.out.println(b); } }
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="reset" value="重置"> <input type="button" onclick="window.location='add.jsp'" value="注册"> </form> </body> </html>
add.jsp
<%-- Created by IntelliJ IDEA. User: ASUS Date: 2019/10/13 Time: 18:24 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <div style="color: red">${message}</div> <form action="${pageContext.request.contextPath}/add" method="post"> 帐号:<input type="text" name="username1"><br> 密码:<input type="password" name="password1"><br> <input type="submit" value="确定"> <input type="reset" value="重置"> </form> </body> </html>
登录认证
新增效果:每个新增用户的密码都是123,但生成的加密密码 和盐都是不一样的