Springboot中怎么加入shiro支持

发布时间:2021-07-23 16:56:19 作者:Leah
来源:亿速云 阅读:132

本篇文章给大家分享的是有关Springboot中怎么加入shiro支持,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

在项目添加依赖

<!-- shiro spring. --><dependency>  <groupId>org.apache.shiro</groupId>  <artifactId>shiro-spring</artifactId>  <version>1.4.0</version></dependency><!-- shiro core --><dependency>  <groupId>org.apache.shiro</groupId>  <artifactId>shiro-core</artifactId>  <version>1.4.0</version></dependency>

配置文件目录下新建spring文件夹,在文件夹内新建spring-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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    <!-- ref对应我们写的realm myRealm -->    <property name="realm" ref="AuthRealm" />    <!-- 使用下面配置的缓存管理器 -->    <!-- <property name="cacheManager" ref="shiroEncacheManager" /> -->  </bean>      <!-- 安全认证过滤器 -->  <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    <!-- 调用我们配置的权限管理器 -->    <property name="securityManager" ref="securityManager" />    <!-- 配置我们的登录请求地址 -->    <property name="loginUrl" value="/toLogin" />    <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->    <property name="successUrl" value="/" />    <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->    <property name="unauthorizedUrl" value="/html/403.html" />    <property name="filterChainDefinitions">      <value>      <!-- anon是允许通过 authc相反 -->        /statics/**=anon        /login=anon        /** = authc      </value>    </property>  </bean>    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />   <!-- AOP式方法级权限检查 -->  <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">    <property name="proxyTargetClass" value="true" />  </bean>  <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">    <property name="securityManager" ref="securityManager" />  </bean></beans>

在主入口加载spring-shiro.xml

@ImportResource({ "classpath:spring/spring-shiro.xml" })

在登录Controller内更改成

//构造登录参数UsernamePasswordToken token = new UsernamePasswordToken(name, pwd);try {  //交给Realm类处理  SecurityUtils.getSubject().login(token);} catch (UnknownAccountException uae) {  map.put("msg", "未知用户");  return "login";} catch (IncorrectCredentialsException ice) {  map.put("msg", "密码错误");  return "login";} catch (AuthenticationException ae) {  // unexpected condition? error?  map.put("msg", "服务器繁忙");  return "login";} return "redirect:/toIndex";

看5行就知道登录交给了Realm类处理了,所以我们要有Realm类

在可以被主入口扫描到的地方新建AuthRealm类并且继承AuthorizingRealm,重写doGetAuthenticationInfo(登录逻辑),重写doGetAuthorizationInfo(授权逻辑)

import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection; public class AuthRealm extends AuthorizingRealm {   @Override  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {    // TODO Auto-generated method stub    return null;  }   @Override  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {    // TODO Auto-generated method stub    return null;  } }

登录验证在doGetAuthenticationInfo方法写入

// 获取TokenUsernamePasswordToken token2 = (UsernamePasswordToken) token;//获取用户名String userName = token2.getUsername();//获取密码String pwd = new String(token2.getPassword());//下面我使用的是MyBatis-puls3.0//查询条件对象QueryWrapper<User> queryWrapper = new QueryWrapper();//查询该用户queryWrapper.eq("name", userName).or().eq("phone", userName);//查询User user = iUserService.getOne(queryWrapper);//查回的对象为空if (CommonUtil.isBlank(user)) {  //抛出未知的账户异常  throw new UnknownAccountException();}//查回的对象密码和输入密码不相等if (!CommonUtil.isEquals(user.getPwd(), pwd)) {  //抛出凭证不正确异常  throw new IncorrectCredentialsException();}//上面都通过了就说明该用户存在并且密码相等// 验证成功了SecurityUtils.getSubject().getSession().setAttribute(Constant.SESSION_USER_KEY, user);// 返回shiro用户信息// token传过来的密码,一定要跟验证信息传进去的密码一致,加密的密码一定要加密后传过来 return new SimpleAuthenticationInfo(user, user.getPwd(), getName());

如果要设置权限,就在对应的Controllerf方法加上

@RequiresPermissions("/system/user/list")

再doGetAuthorizationInfo方法内写

//创建简单的授权信息对象SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();//授予权限simpleAuthorizationInfo.addStringPermission("/system/user/list"); return simpleAuthorizationInfo;

当所有Controller都加了@RequiresPermissions注解后,如果访问到没有授权的Controller会报错。

以上就是Springboot中怎么加入shiro支持,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. springboot+shiro+jwt
  2. Shiro-SpringBoot(一)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot shiro

上一篇:android怎么处理配置变更问题

下一篇:TypeScript怎么定义接口

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》