1.首先编写xml配置文件

<!--  定义用户自定义的realm--><bean id="myrealm" class="com.hfxt.controller.shiro.UserRealm">  <!--     设置加密匹配器--><property name="credentialsMatcher"><bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"><property name="hashIterations" value="1024"></property><property name="hashAlgorithmName" value="md5"></property></bean></property></bean><!--    引用了工具类--><bean id="roleOrFillter" class="com.hfxt.controller.shiro.CustomRolesAuthorizationFilter"/>
<!-- 配置权限管理器--><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realms" ><list><ref bean="myrealm"/></list></property></bean>
<!-- logout过滤器--><bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter"><property name="redirectUrl" value="/loginAjax.jsp" /></bean>
<!-- 配置过滤器工厂--><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--     调用配置好的过滤管理器--><property name="securityManager" ref="securityManager"/><!--        登录页面--><property name="loginUrl" value="/login/tologin.html"/><!--        登陆成功页面--><property name="successUrl" value="/filmInfo/index.html"/><!--       权限不足页面--><property name="unauthorizedUrl" value="/login/unauthorized"/><!--       引用工具类实现满足一个角色权限即可["buyer,operator"]--><property name="filters" ><map><entry key="roleOrFilter" value-ref="roleOrFillter"/></map></property>
<!--     权限配置--><property name="filterChainDefinitions"><!--          anno可以匿名访问,即可以不用登录就可以访问;-->
<!--         authc必须登录之后才可以访问;-->
<!--         logout 退出 由于shiro有缓存机制 必须登出--><value>/login/**=anon/filmInfo/**=authc,roles["buyer,operator"]                      /filmInfo/**=authc,roleOrFilter["buyer,operator"]/shop/**=authc/echar.jsp=authc/logout.jsp = logout</value></property></bean>

2.实现shiro角色 引用工具类实现满足一个角色权限即可[“buyer,operator”]的工具类

package com.hfxt.controller.shiro;import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;public class CustomRolesAuthorizationFilter extends AuthorizationFilter {protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)throws Exception {Subject subject = getSubject(request, response);String[] rolesArray = (String[]) mappedValue;//没有角色限制,有权限访问if (rolesArray == null || rolesArray.length == 0) {return true;}for (int i = 0; i < rolesArray.length; i++) {//若当前用户是rolesArray中的任何一个,则有权限访问if (subject.hasRole(rolesArray[i])) {return true;}}return false;}}

3.对UsernamePasswordToken类进行封装的工具类

package com.hfxt.controller.shiro;import org.apache.shiro.authc.UsernamePasswordToken;public class CustomToken extends UsernamePasswordToken {public CustomToken() {super();}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted during an authentication attempt, with a <tt>null</tt>* {@link #getHost() host} and a <tt>rememberMe</tt> default of <tt>false</tt>.* * @param username*        the username submitted for authentication* @param password*        the password character array submitted for authentication*/public CustomToken(final String username, final char[] password) {this(username, password, false, null);}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted during an authentication attempt, with a <tt>null</tt>* {@link #getHost() host} and a <tt>rememberMe</tt> default of <tt>false</tt>* <p/>* <p>* This is a convience constructor and maintains the password internally via a character array, i.e. <tt>password.toCharArray();</tt>. Note that storing a* password as a String in your code could have possible security implications as noted in the class JavaDoc.* </p>* * @param username*        the username submitted for authentication* @param password*        the password string submitted for authentication*/public CustomToken(final String username, final String password) {this(username, password != null ? password.toCharArray() : null, false, null);}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted, the inetAddress from where the attempt is occurring, and a* default <tt>rememberMe</tt> value of <tt>false</tt>* * @param username*        the username submitted for authentication* @param password*        the password string submitted for authentication* @param host*        the host name or IP string from where the attempt is occuring* @since 0.2*/public CustomToken(final String username, final char[] password, final String host) {this(username, password, false, host);}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted, the inetAddress from where the attempt is occurring, and a* default <tt>rememberMe</tt> value of <tt>false</tt>* <p/>* <p>* This is a convience constructor and maintains the password internally via a character array, i.e. <tt>password.toCharArray();</tt>. Note that storing a* password as a String in your code could have possible security implications as noted in the class JavaDoc.* </p>* * @param username*        the username submitted for authentication* @param password*        the password string submitted for authentication* @param host*        the host name or IP string from where the attempt is occuring* @since 1.0*/public CustomToken(final String username, final String password, final String host) {this(username, password != null ? password.toCharArray() : null, false, host);}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted, as well as if the user wishes their identity to be remembered* across sessions.* * @param username*        the username submitted for authentication* @param password*        the password string submitted for authentication* @param rememberMe*        if the user wishes their identity to be remembered across sessions* @since 0.9*/public CustomToken(final String username, final char[] password, final boolean rememberMe) {this(username, password, rememberMe, null);}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted, if the user wishes their identity to be remembered across* sessions, and the inetAddress from where the attempt is ocurring.* <p/>* <p>* This is a convience constructor and maintains the password internally via a character array, i.e. <tt>password.toCharArray();</tt>. Note that storing a* password as a String in your code could have possible security implications as noted in the class JavaDoc.* </p>* * @param username*        the username submitted for authentication* @param password*        the password string submitted for authentication* @param rememberMe*        if the user wishes their identity to be remembered across sessions* @param host*        the host name or IP string from where the attempt is occuring* @since 1.0*/public CustomToken(final String username, final String password, final boolean rememberMe, final String host) {this(username, password != null ? password.toCharArray() : null, rememberMe, host);}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted, as well as if the user wishes their identity to be remembered* across sessions.* <p/>* <p>* This is a convience constructor and maintains the password internally via a character array, i.e. <tt>password.toCharArray();</tt>. Note that storing a* password as a String in your code could have possible security implications as noted in the class JavaDoc.* </p>* * @param username*        the username submitted for authentication* @param password*        the password string submitted for authentication* @param rememberMe*        if the user wishes their identity to be remembered across sessions* @since 0.9*/public CustomToken(final String username, final String password, final boolean rememberMe) {this(username, password != null ? password.toCharArray() : null, rememberMe, null);}/*** Constructs a new UsernamePasswordToken encapsulating the username and password submitted, if the user wishes their identity to be remembered across* sessions, and the inetAddress from where the attempt is ocurring.* * @param username*        the username submitted for authentication* @param password*        the password character array submitted for authentication* @param rememberMe*        if the user wishes their identity to be remembered across sessions* @param host*        the host name or IP string from where the attempt is occuring* @since 1.0*/public CustomToken(final String username, final char[] password, final boolean rememberMe, final String host) {super(username, password, rememberMe, host);/*** 增加手机登录验证token.*/}private String mobile;private String verificatecode;public String getMobile() {return mobile;}public void setMobile(String mobile) {this.mobile = mobile;}public String getVerificatecode() {return verificatecode;}public void setVerificatecode(String verificatecode) {this.verificatecode = verificatecode;}public CustomToken(final String username, final String password,final String mobile ,final String verificatecode, final String host) {this(username, password != null ? password.toCharArray() : null, false, host);this.mobile = mobile;this.verificatecode = verificatecode;}/***/public static final int Flag_Front_User  = 1;/***/public static final int Flag_Admin_User  = 2;/***/private int             flagFrontOrAdmin = 0;/***/public int getFlagFrontOrAdmin() {return flagFrontOrAdmin;}/***/public void setFlagFrontOrAdmin(int flagFrontOrAdmin) {this.flagFrontOrAdmin = flagFrontOrAdmin;}}

4.controller 层处理的代码

package com.hfxt.controller;import com.alibaba.fastjson.JSONArray;
import com.hfxt.controller.shiro.CustomToken;
import com.hfxt.entity.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
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 org.springframework.web.bind.annotation.ResponseBody;import java.util.HashMap;
import java.util.Map;@Controller
@RequestMapping("/login")
public class LoginController {@RequestMapping("tologin.html")public String tologin(){return "loginAjax";}@RequestMapping("login.html")@ResponseBodypublic String login(UserVo uservo){Map<String,Object> maps=new HashMap<String, Object>();//创建shiro认证对象try{Subject subject= SecurityUtils.getSubject();
//        封装认证用户 继承usernamepasswordtocken// UsernamePasswordToken token=new UsernamePasswordToken()CustomToken token=new CustomToken(uservo.getUsername(),uservo.getPassword());//提交认证subject.login(token);maps.put("retcode",1);maps.put("retmsg","登录成功");}catch(UnknownAccountException e){maps.put("retcode",-1);maps.put("retmsg","账户不正确");}catch (IncorrectCredentialsException e){maps.put("retcode",-1);maps.put("retmsg","密码不正确");}catch (AuthenticationException e){maps.put("retcode",-1);maps.put("retmsg","认证失败,请联系管理员");}return JSONArray.toJSONString(maps);}@RequestMapping("unauthorized")public String fail(){return "403";}
}

6.授权加认证

package com.hfxt.controller.shiro;import com.hfxt.entity.RoleVo;
import com.hfxt.entity.UserVo;
import com.hfxt.service.RoleVoService;
import com.hfxt.service.UserVoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;
import java.util.List;public class UserRealm extends AuthorizingRealm {@Resourceprotected UserVoService userVoService;@Resourceprotected RoleVoService roleVoService;//授权protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//        声明返回授权对象SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();UserVo userVo= (UserVo) SecurityUtils.getSubject().getPrincipal();//获取角色List<RoleVo> list=roleVoService.getRoleVosByUserid(userVo.getId().intValue());for(RoleVo roleVo :list){info.addRole(roleVo.getRoleCode());}return info;}
//认证protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throwsAuthenticationException {//得到认证对象String username= (String) token.getPrincipal();String password=new String( (char []) token.getCredentials());UserVo userVo=null;try{userVo=userVoService.getUserVoByUserVoName(username);}catch(Exception e){e.printStackTrace();}if (userVo == null) {throw new UnknownAccountException();}//加密算法String newpwd=new Md5Hash(password,userVo.getSalt(),1024).toString();System.out.println("加密之后:"+newpwd);System.out.println("数据库的密码:"+ userVo.getPassword());if(!userVo.getPassword().equals(newpwd)){throw new IncorrectCredentialsException();}//进行认证//第一个参数 user//第二个参数是user.getpassword;//第三个参数(密码加密 salt(盐值)) 可省//第四个参数是当前realm的名字ByteSource sale=ByteSource.Util.bytes(userVo.getSalt());SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(userVo, userVo.getPassword(),sale,getName());return info;}
}

web.xml配置监听器监听

<!--    配置shiro拦截器(权限验证)--><filter><filter-name>shiroFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping><filter-name>shiroFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>

ssm进行shiro认证步骤相关推荐

  1. Shiro认证-身份认证加密

    目录 一.盐加密 什么是盐加密? 数据库密码的发展史 1.1pom依赖 1.2web.xml配置 1.3密码工具类 测试 盐加密新增用户的操作流程: 二.shiro认证 步骤 1.通过逆向工程将五张表 ...

  2. SSM整合Shiro进行登陆认证和授权详细配置

    本篇博客将进行详细介绍Shiro+Spring+SpringMVC+Mybatis+数据库整合并进行登陆认证和授权详细配置. SSM的整合可以参考:https://blog.csdn.net/a745 ...

  3. SSM整合shiro权限框架

    一.SSM整合shiro框架 1.步骤 1.添加shiro框架需要的jar包,包括shiro-core.shiro-web.shiro-spring的关系依赖 <!-- shiro jar包依赖 ...

  4. Shiro认证及加盐加密

    目录 今天的知识是与上次所分享的知识相关联的,在Shiro入门的基础进行编写,上次之前的数据是死数据(放在Shiro.ini)而这次是活数据,可以连接到数据库,运用域Relam知识.同时出于维护用户的 ...

  5. SSM中shiro的基本使用

    shiro 用以网站的授权和认证 配置: 一.shiro基本配置文件 所用的entity user和role 实体类 1 @Entity 2 @Table(name="USER_P" ...

  6. Shiro认证源码解析和工作原理

    先行回顾一下使用shiro的步骤: 1. 创建Subject实例对象currUser: 2. 判断当前currUser是否认证过: 3. 如果没有认证过,那么应当调用currUser的login(to ...

  7. SSM集成shiro权限管理

    这几天在学习了shiro权限管理框架,在刚开始的时候学的时候因为这个配置问题困扰了我很长时间,所以在这篇文章我整合了自己用SSM搭建shiro权限框架的过程. 1.配置 1.1jar包 在项目配置开始 ...

  8. Shiro认证和授权

    shiro介绍 什么是shiro Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权.加密.会话管理等功能,组成了一个通用的安全认证框架. ...

  9. Shiro 认证授权详解

    1     权限管理 1.1用户身份认证 1.1.1  概念 身份认证,就是判断一个用户是否为合法用户的处理过程.最常用的简单身份认证方式是系统通过核对用户输入的用户名和口令,看其是否与系统中存储的该 ...

最新文章

  1. Keypress - 捕获键盘输入的JavaScript库
  2. 真正的飞车-赛道狂飙:日出极限版
  3. 使用C#实现网站用户登录 (转)
  4. 【剑指offer-Java版】31连续子数组的最大和
  5. JavaScript的类型、值和变量
  6. thinkphp中的AJAX返回ajaxReturn()
  7. unity3d Aniso Level 摄像机近地面清楚,远地面模糊
  8. Linux : 文件处理命令
  9. java图像膨胀_java实现的图像腐蚀、膨胀运算 | 学步园
  10. 服务器--apache启用多个端口的方法
  11. HDU1434 幸福列车【模拟+优先队列】
  12. 澳门智能公交调度系统客户端GUI设计
  13. python网络爬虫基础知识
  14. spring注解开发实例
  15. 如何下载网页的FLASH视频
  16. python是面向对象开发_Python开发之路-面向对象
  17. 臭名昭著的Java”
  18. 使用showdown将markdown笔记插入到HTML网页
  19. Win10修改登陆密码
  20. VMware错误:无法更新运行时文件夹共享状态:在客户机操作系统内装载共享文件夹文件系统时出错

热门文章

  1. 逻辑斯谛回归(Logistic Regression):函数、模型及其理论内涵
  2. 怎样看计算机主板,怎么看主板型号
  3. skimage库(一)
  4. 寻找费希尔定位器故障原因方便解决故障
  5. 免装直播姬,自制实时显示直播弹幕软件,效果满分!
  6. MySQL备份——(十)
  7. 数据库建立索引以及索引失效问题
  8. 去除整个字符串中的字符
  9. 支付宝当面付扫码支付支付后不回调_科普帖 | 青蛙?蜻蜓?自助收银?刷脸支付?一文为你解惑...
  10. Oracle gsd服务是什么,如何处理11gR2 RAC下oc4j和gsd服务为OFFLINE状态