目录
- <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>
- <!-- 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>
- <select id="queryByName" resultType="com.ssr.model.User" parameterType="java.lang.String">
- select
- <include refid="Base_Column_List" />
- from t_shiro_user
- where userName = #{userName}
- </select>
UserBiz.java
- package com.ssr.biz;
-
- import com.ssr.model.User;
- import org.apache.ibatis.annotations.Param;
-
- public interface UserBiz {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryByName(@Param("userName") String uname);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
-
- }
UserBizImpl .java
- package com.ssr.biz.impl;
-
- import com.ssr.biz.UserBiz;
- import com.ssr.mapper.UserMapper;
- import com.ssr.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- @Service("useBiz")
- public class UserBizImpl implements UserBiz {
- @Autowired
- private UserMapper userMapper;
-
- @Override
- public int deleteByPrimaryKey(Integer userid) {
- return userMapper.deleteByPrimaryKey(userid);
- }
-
- @Override
- public int insert(User record) {
- return userMapper.insert(record);
- }
-
- @Override
- public int insertSelective(User record) {
- return userMapper.insertSelective(record);
- }
-
- @Override
- public User selectByPrimaryKey(Integer userid) {
- return userMapper.selectByPrimaryKey(userid);
- }
-
- @Override
- public User queryByName(String uname) {
- return userMapper.queryByName(uname);
- }
-
- @Override
- public int updateByPrimaryKeySelective(User record) {
- return userMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(User record) {
- return userMapper.updateByPrimaryKey(record);
- }
- }
Myrealm.java
- package com.ssr.shiroo;
-
- import com.ssr.biz.UserBiz;
- import com.ssr.model.User;
- 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;
-
- public class Myrealm extends AuthorizingRealm {
-
- private UserBiz userBiz;
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- return null;
- }
-
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- System.out.println("身份认证...");
- String username = token.getPrincipal().toString();
- String password = token.getCredentials().toString();
- User user = userBiz.queryByName(username);
- // 拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
- AuthenticationInfo info = new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName()
- );
- return info;
- }
-
- }
applicationContext-shiro.xml
- "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">
-
-
- <bean id="shiroRealm" class="com.ssr.shiroo.Myrealm">
- <property name="userBiz" ref="useBiz" />
-
-
-
-
- <property name="credentialsMatcher">
- <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
-
- <property name="hashAlgorithmName" value="md5"/>
-
- <property name="hashIterations" value="1024"/>
-
- <property name="storedCredentialsHexEncoded" value="true"/>
- bean>
- property>
- bean>
-
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroRealm" />
- bean>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <property name="securityManager" ref="securityManager" />
-
- <property name="loginUrl" value="/login"/>
-
-
-
- <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
-
- <property name="filterChainDefinitions">
- <value>
-
-
-
-
- /user/login=anon
- /user/updatePwd.jsp=authc
- /admin/*.jsp=roles[admin]
- /user/teacher.jsp=perms["user:update"]
-
- value>
- property>
- bean>
-
-
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
- beans>
LoginController .java
- package com.ssr.controller;
-
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.subject.Subject;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
-
- @Controller
- public class LoginController {
- @RequestMapping("/login")
- public String login(HttpServletRequest req, HttpServletResponse resp){
- String username = req.getParameter("username");
- String password = req.getParameter("password");
- UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
- Subject subject = SecurityUtils.getSubject();
- try {
- subject.login(usernamePasswordToken);
- req.getRequestDispatcher("main.jsp").forward(req, resp);
- } catch (Exception e) {
- req.setAttribute("message", "您的用户名密码输入有误!!!");
- try {
- req.getRequestDispatcher("login.jsp").forward(req, resp);
- } catch (ServletException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- return null;
- }
-
- @RequestMapping("/logout")
- public String logout(HttpServletRequest req, HttpServletResponse resp){
- Subject subject = SecurityUtils.getSubject();
- subject.logout();
- try {
- resp.sendRedirect(req.getContextPath()+"/login.jsp");
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
运行效果:

盐加密工具类,在做新增用户的时候使用,将加密后的密码、及加密时候的盐放入数据库;
本篇博客中的表数据是现成的,暂时用不上这个工具类去生成数据;
盐加密的发展史
盐加密发展史
第一阶段:明文密码
第二阶段:md5加密
第三阶段:md5加密加盐
第四阶段:md5加盐加密加次数
PasswordHelper .java
- package com.javaxl.ssm.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);
- }
- }