Java springboot整合Shiro框架的方法是什么
导读:本文共5772.5字符,通常情况下阅读需要19分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: Shiro介绍Shiro是一款安全框架,主要的三个类Subject、SecurityManager、RealmSubject:表示当前用户SecurityManager:安全管理器,即所有与安全有关的操作都会与SecurityManager交互;且其管理着所有Subject;可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于Spring... ...
目录
(为您整理了一些要点),点击可以直达。Shiro介绍
Shiro是一款安全框架,主要的三个类Subject、SecurityManager、Realm
Subject:表示当前用户
SecurityManager:安全管理器,即所有与安全有关的操作都会与SecurityManager交互;且其管理着所有Subject;可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC中DispatcherServlet的角色
Realm:Shiro从Realm 获取安全数据(如用户、角色、权限)
Shiro框架结构图
Springboot整合Shiro
建项目是勾选spring web,导入依赖
<!--thymeleaf--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!--shiro--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.7.1</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional><version>1.18.2</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><!--mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.1</version></dependency><!--log4j--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!--thymeleaf、shiro整合包--><dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version></dependency>
编写页面及其控制层
转发的设置,全部编写在MVCConfig中的前端控制器中
@ConfigurationpublicclassMyMvcConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddViewControllers(ViewControllerRegistryregistry){registry.addViewController("/").setViewName("index");registry.addViewController("/login.html").setViewName("login");registry.addViewController("/user/add").setViewName("user/add");registry.addViewController("/user/update").setViewName("user/update");registry.addViewController("/loginout").setViewName("login");}}
连接数据库
编写application.yml
spring:datasource:username:***password:***url:jdbc:mysql://localhost:3306/db_2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCdriver-class-name:com.mysql.cj.jdbc.Drivertype:com.alibaba.druid.pool.DruidDataSourceinitialSize:5minIdle:5maxActive:20maxWait:60000timeBetweenEvictionRunsMillis:60000minEvictableIdleTimeMillis:300000validationQuery:SELECT1FROMDUALtestWhileIdle:truetestOnBorrow:falsetestOnReturn:falsepoolPreparedStatements:truefilters:stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize:20useGlobalDataSourceStat:trueconnectionProperties:druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500mybatis:type-aliases-package:com.example.demo.pojo
编写 pojo、dao、service三层,dao层可以直接使Mybatis的注解。
需要的方法就是findByName(String username),通过表单传入的username值进行查询。
编写UserRealm 需要继承AuthorizingRealm
publicclassUserRealmextendsAuthorizingRealm{@AutowiredprivateIuserServiceiuserService;//授权@OverrideprotectedAuthorizationInfodoGetAuthorizationInfo(PrincipalCollectionprincipalCollection){System.out.println("===>授权");SimpleAuthorizationInfoInfo=newSimpleAuthorizationInfo();//获取登录对象Subjectsubject=SecurityUtils.getSubject();userprincipal=(user)subject.getPrincipal();//拿到userInfo.addStringPermission(principal.getPerms());returnInfo;}//认证@OverrideprotectedAuthenticationInfodoGetAuthenticationInfo(AuthenticationTokenauthenticationToken)throwsAuthenticationException{System.out.println("==>认证");UsernamePasswordTokenauthenticationToken1=(UsernamePasswordToken)authenticationToken;userbyName=iuserService.findByName(authenticationToken1.getUsername());if(byName==null){returnnull;//抛出用户名错误的异常}//密码认证shiro自己完成将user对象传递给上面的方法进行授权returnnewSimpleAuthenticationInfo(byName,byName.getPassword(),"");}}
代码的分析:
认证部分:
将表单提交的数据封装成一个对象,通过username从数据库中查询返回一个对象,进行比对
最后将这个查询的对象传递给授权方法。
授权部分:
获取到用户对象,给用户对象进行相应的授权。(传递的user对象中就有权限设置)
编写ShiroConfig
@ConfigurationpublicclassShiroConfig{@Bean//创建对象publicUserRealmuserRealm(){returnnewUserRealm();}@Bean//接管对象@Bean默认使用方法名称publicDefaultWebSecurityManagersecurityManager(@Qualifier("userRealm")Realmrealm){DefaultWebSecurityManagerdefaultWebSecurityManager=newDefaultWebSecurityManager();defaultWebSecurityManager.setRealm(realm);returndefaultWebSecurityManager;}@Bean//交给前端处理publicShiroFilterFactoryBeanshiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManagerdefaultWebSecurityManager){ShiroFilterFactoryBeanshiroFilterFactoryBean=newShiroFilterFactoryBean();shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);HashMap<String,String>hashMap=newHashMap<>();//该路径必须通过认证才能进行访问hashMap.put("/user/*","authc");//进行授权hashMap.put("/user/add","perms[add]");hashMap.put("/user/update","perms[update]");//注销hashMap.put("/logout","logout");shiroFilterFactoryBean.setFilterChainDefinitionMap(hashMap);//设置登录页面的路径shiroFilterFactoryBean.setLoginUrl("/login.html");//设置授权页面shiroFilterFactoryBean.setUnauthorizedUrl("/noLogin");returnshiroFilterFactoryBean;}//完成整合@BeanpublicShiroDialectgetShiroDialect(){returnnewShiroDialect();}}
代码分析
在这个配置类中,配置的方法就是ioc注入。
ShiroFilterFactoryBean中可以配置
资源路径对应的权限
登陆页面
权限不足 无法访问的页面路径
注销
补充: 拦截的属性
anon: 无需认证就可以访问
authc: 必须认证了才能访问
user: 必须拥有记住我功能才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有某个角色权限
编写控制层代码
@Controllerpublicclasslogincontroller{//执行流程前端表单-》控制层代码-》config@PostMapping("/login")publicStringlogin(Stringusername,Stringpassword,Modelmodel){//获取一个用户Subjectsubject=SecurityUtils.getSubject();//封装用户登陆数据UsernamePasswordTokenusernamePasswordToken=newUsernamePasswordToken(username,password);//执行登录方法,如果失败就会抛出异常try{subject.login(usernamePasswordToken);return"index";}catch(UnknownAccountExceptione){model.addAttribute("msg","用户名错误");return"login";}catch(IncorrectCredentialsExceptione){model.addAttribute("msg","密码错误");return"login";}}@GetMapping("/noLogin")@ResponseBodypublicStringnologin(){return"未经授权无法访问";}}
代码分析:
login方法:获取从表单传递的数据,封装从UsernamePasswordToken对象,调用login方法进行登录操作
Shiro整合Thymeleaf
在ShiroConfig需要整合ShiroDialect
//完成整合@BeanpublicShiroDialectgetShiroDialect(){returnnewShiroDialect();}
约束
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
使用方法
shiro:notAuthenticated
:没有进行登录 显示shiro:authenticated:
已经登陆 显示shiro:hasPermission="A"
用户存在A的权限则显示
示例代码:
<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"><head><metacharset="UTF-8"><title>Title</title></head><body><h2>首页</h2><divshiro:notAuthenticated><ath:href="@{/login.html}">登录</a></div><divshiro:authenticated><ath:href="@{/logout}">注销</a></div><divshiro:hasPermission="add"><ath:href="@{/user/add}">ADD</a></div><divshiro:hasPermission="update"><ath:href="@{/user/update}">UPDATE</a></div></body></html>
总结
登录的流程:login表单-》loginController
-》ShiroConfig
-》UserRealm
效果:
点击登录,控制台会显示
进入add/update的页面,也会打印"===>授权",这个也证明了登录的执行流程
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
Java springboot整合Shiro框架的方法是什么的详细内容,希望对您有所帮助,信息来源于网络。