zoukankan      html  css  js  c++  java
  • 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>

    然后使用逆向工厂生成相关代码

    Mapper.xml中加

    <select id="queryByName" resultType="com.javaxl.ssm.model.ShiroUser" parameterType="java.lang.String">
      select
      <include refid="Base_Column_List" />
      from t_shiro_user
      where userName = #{userName}
    </select>

    ShiroUserService

    package com.cjh.service;
    
            import com.cjh.model.ShiroUser;
    
    /**
     * @author
     * @site
     * @company
     * @create 2019-10-13 16:29
     */
    public interface ShiroUserService {
        /**
         * 用于shiro认证
         * @param uname
         * @return
         */
        public ShiroUser queryByName(String uname);
    
        int insert(ShiroUser record);
    
    }

    实现类

    package com.cjh.service.Impl;
    
    import com.cjh.mapper.ShiroUserMapper;
    import com.cjh.model.ShiroUser;
    import com.cjh.service.ShiroUserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    /**
     * @author
     * @site
     * @company
     * @create 2019-10-13 16:31
     */
    @Service("shiroUserService")
    public class ShiroUserServiceImpl implements ShiroUserService {
        @Autowired
        private ShiroUserMapper shiroUserMapper;
        @Override
        public ShiroUser queryByName(String uname) {
            return shiroUserMapper.queryByName(uname);
        }
    
        @Override
        public int insert(ShiroUser record) {
            return shiroUserMapper.insert(record);
        }
    
    
    }

    Myrealm.java

    package com.cjh.shiro;
    
    import com.cjh.model.ShiroUser;
    import com.cjh.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
     * @site
     * @company
     * @create 2019-10-13 16:19
     * 认证过程
     * 1.数据原(ini-》数据库)
     * 2.doGetAuthenticationInfo将数据库的用户信息个shbjet主体认证
     *    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 principals
         * @return
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            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.getPrincipal().toString();
            ShiroUser shiroUser = this.shiroUserService.queryByName(userName);
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    shiroUser.getUsername(),
                    shiroUser.getPassword(),
                    ByteSource.Util.bytes(shiroUser.getSalt()),
                    this.getName()
            );
            return info;
        }
    }

    ShiroUserController

    package com.cjh.controller;
    
    import com.cjh.model.ShiroUser;
    import com.cjh.service.ShiroUserService;
    import com.cjh.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
     * @site
     * @company
     * @create 2019-10-13 16:57
     */
    @Controller
    public class ShiroUserController {
        @Autowired
        private ShiroUserService shiroUserService;
    
        @RequestMapping("/login")
        public  String login(HttpServletRequest request, HttpServletResponse response){
            Subject subject = SecurityUtils.getSubject();
            String uname= request.getParameter("username");
            String pwd= request.getParameter("password");
            UsernamePasswordToken token = new UsernamePasswordToken(uname,pwd);
            try {
                subject.login(token);
                return "main";
            }catch (Exception e) {
              request.setAttribute("message", "用户或密码错误!!");
                return "login";
            }
        }
    
    
        @RequestMapping("/logout")
        public  String logout(HttpServletRequest request, HttpServletResponse response) {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return "login";
        }
    
        @RequestMapping("/add")
        public String adduser (HttpServletRequest request,HttpServletResponse response){
            String uname= request.getParameter("username");
            String pwd= request.getParameter("password");
            //
            String salt = PasswordHelper.createSalt();
            //凭证+盐加密后得到的密码
            String pwd1 = PasswordHelper.createCredentials(pwd, salt);
            ShiroUser shiroUser = new ShiroUser();
            shiroUser.setUsername(uname);
            shiroUser.setPassword(pwd1);
            shiroUser.setSalt(salt);
            int insert = shiroUserService.insert(shiroUser);
            if (insert>0){
                request.setAttribute("message", "注册成功!!");
                return  "login";
            }else{
                request.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="reset" value="重置">
            <input type="button" value="注册" onclick="location.href='${pageContext.request.contextPath}/add.jsp'">
        </form>
    
    </body>
    </html>

    add.jsp

    <%--
      Created by IntelliJ IDEA.
      User: dell
      Date: 2019/10/13
      Time: 19:07
      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>
    <h1>用户注册</h1>
    <form action="${pageContext.request.contextPath}/add" 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>

    新增进去的不在是数字而是一个32位的字符串

  • 相关阅读:
    2019年9月15日晚间测试-T1
    机房巨佬的随机名称生成器
    初来乍到
    GKurumi记
    GKurumi记
    小P的团战
    什么才算是真正的编程能力?
    java冒泡排序和快速排序
    “转行做程序员”很难?这里有4个重要建议
    Linux文件I/O(一)
  • 原文地址:https://www.cnblogs.com/chenjiahao9527/p/11668082.html
Copyright © 2011-2022 走看看