目录
步骤:
1. pom依赖
2.web配置
3. 自定义Realm(重点)
4.对应mapper编写
5.Spring与shiro整合(注意)
6.登录测试
导入pom依赖
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-coreartifactId>
- <version>1.3.2version>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-webartifactId>
- <version>1.3.2version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-springartifactId>
- <version>1.3.2version>
- dependency>
web.xml配置
- <filter>
- <filter-name>shiroFilterfilter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
- <init-param>
-
- <param-name>targetFilterLifecycleparam-name>
- <param-value>trueparam-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>shiroFilterfilter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
逆向生成对应的代码

在UserMapper.xml中新增
- select
-
"Base_Column_List" /> - from t_shiro_user
- where userName = #{userName}
建立业务逻辑层
- package com.dengxiyan.ssm.Biz;
-
- import com.dengxiyan.ssm.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(String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
- }
实现类
- package com.dengxiyan.ssm.Biz.impl;
-
- import com.dengxiyan.ssm.Biz.UserBiz;
- import com.dengxiyan.ssm.mapper.UserMapper;
- import com.dengxiyan.ssm.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- /**
- * @author dxy
- * @site www.javadxy.com
- * @company ds公司
- * @create 2022-08-25 13:49
- */
- @Service("userBiz")
- 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 userName) {
- return userMapper.queryByName(userName);
- }
-
- @Override
- public int updateByPrimaryKeySelective(User record) {
- return userMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(User record) {
- return updateByPrimaryKey(record);
- }
- }
Myrealm
MyRealm要使用业务层,因为realm是属于shiro的,这样使得没办法使用Spring里面的@Autowired注解,同时也没办法直接交给Spring进行管理,所以我们需要通过实现类里的@Service里面添加标记(biz中的属性名)
- package com.dengxiyan.ssm.shiro;
-
- import com.dengxiyan.ssm.Biz.UserBiz;
- import com.dengxiyan.ssm.mapper.UserMapper;
- import com.dengxiyan.ssm.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;
-
- /**
- * @author dxy
- * @site www.javadxy.com
- * @company ds公司
- * @create 2022-08-25 13:56
- */
- public class MyRealm extends AuthorizingRealm {
-
- private UserBiz userBiz;
-
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- /**
- * 授权
- * @param principals
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- return null;
- }
-
- /**
- * 认证
- * @param token
- * @return
- * @throws AuthenticationException
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- //拿到用户名
- String username = token.getPrincipal().toString();
- //拿到密码
- String password = token.getCredentials().toString();
- User user = userBiz.queryByName(username);
- //拿到数据库的用户信息,放入token凭证中,用于controler进行对比
- // 需要进行传参
- SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
- user.getUsername(),//用户
- user.getPassword(),//密码
- ByteSource.Util.bytes(user.getSalt()),//拿到盐
- this.getName()//realm的名字
- );
- return info;
- }
- }
LoginController
- package com.dengxiyan.ssm.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;
-
- /**
- * @author dxy
- * @site www.javadxy.com
- * @company ds公司
- * @create 2022-08-19 19:18
- */
- @Controller
- public class LoginController {
- @RequestMapping("/login")
- public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //登入成功 需要保存用户信息
- // String uname = request.getParameter("uname");
- // if ("dengxiyan".equals(uname)) {
- // System.out.println("jsdjsa:"+uname);
- // request.getSession().setAttribute("uname", uname);
- // }
-
- try {
- //拿到用户名及密码
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
- Subject subject = SecurityUtils.getSubject();
- subject.login(usernamePasswordToken);
- // request.getRequestDispatcher("main.jsp").forward(request,response);
- return "mian";
- }catch (Exception e){
- request.setAttribute("message","用户名或密码错误");
- // request.getRequestDispatcher("login.jsp").forward(request,response);
- return "login";
- }
- }
-
-
- @RequestMapping("/logout")
- public String logout(HttpServletRequest request,HttpServletResponse response) {
- // request.getSession().invalidate();
- // return "index";
- Subject subject = SecurityUtils.getSubject();
- subject.logout();
- try{
- response.sendRedirect(request.getContextPath()+"/login.jsp");
- }catch (Exception e){
- e.printStackTrace();
- }
- return null;
- }
- }
将所需界面自行搭建好之后运行即可。
《效果图》


1.生成加密密码PasswordHelper类(盐加密)
2.修改applicationContext-shirod的自定义Realm配置
步骤:
1.获取用户及密码
2.传递啊到后台
3.利用 原始密码+生成随机的盐 得到加密后的密码最后执行insert语句
PasswordHelper类
- package com.dengxiyan.shrio;
-
-
- 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);
- }
- }
《效果图》
解析:
首先在方法中随机生成盐 ,拿到用户和密码,然后拿到密码进行盐加密,得到的是一个加密过后的盐,再获取长度,最后拿到加密后的密码和盐以及最初的密码进行比较,返回的是true则加密成功
applicationContext-shirod配置
- "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.javaxl.ssm.shiro.MyRealm">
- <property name="shiroUserService" ref="shiroUserService" />
-
-
-
-
- <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>
总结:
1. pom依赖
2.web配置
3. 自定义Realm(重点)
4.对应mapper编写
5.Spring与shiro整合(注意)(1)shiro在加载的时候,Spring上下文还没有记载完毕,所以Component与@autowised是不能使用的
(2)Spring-shiro,xml文件中,MyRealm需要依赖的业务类
由于没有被Spring配置,所以需要指定bean的id,通过Service(“具体名”)
6.登录测试
结论:doGetAuthorizationInfo认证方法是web层秩序subject.login出发的