SpringBoot学习(六)————简单的shiro启动、登录拦截、用户认证、整合Mybatis、实现授权、thymeleaf和shir整合

编程入门 行业动态 更新时间:2024-10-24 20:16:27

SpringBoot学习(六)————<a href=https://www.elefans.com/category/jswz/34/1770983.html style=简单的shiro启动、登录拦截、用户认证、整合Mybatis、实现授权、thymeleaf和shir整合"/>

SpringBoot学习(六)————简单的shiro启动、登录拦截、用户认证、整合Mybatis、实现授权、thymeleaf和shir整合

文章目录

    • Shrio
      • 简单的shiro启动
      • 登录拦截
      • 用户认证
      • 整合Mybatis
      • 实现授权
      • thymeleaf和shiro

Shrio

是Java的安全(权限)框架

可以完成认证,授权,加密,会话管理,web集成,缓存等

简单的shiro启动

导包

<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>
<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId>
</dependency>
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.3</version>
</dependency>

log4j.properties

## Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements.  See the NOTICE file# distributed with this work for additional information# regarding copyright ownership.  The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License.  You may obtain a copy of the License at##     .0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied.  See the License for the# specific language governing permissions and limitations# under the License.#log4j.rootLogger=INFO, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n# General Apache librarieslog4j.logger.apache=WARN# Springlog4j.logger.springframework=WARN# Default Shiro logginglog4j.logger.apache.shiro=INFO# Disable verbose logginglog4j.logger.apache.shiro.util.ThreadContext=WARNlog4j.logger.apache.shiro.cache.ehcache.EhCache=WARN

shiro.ini

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     .0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'delete' (action) the user (type) with
# license plate 'zhangsan' (instance specific id)
goodguy = user:delete:zhangsan

QucikStart.java

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @author wjq* @create 2021-08-02 13:32*/
public class HelloShiro {/*** Simple Quickstart application showing how to use Shiro's API.** @since 0.9 RC2*/private static final transient Logger log = LoggerFactory.getLogger(HelloShiro.class);public static void main(String[] args) {// The easiest way to create a Shiro SecurityManager with configured// realms, users, roles and permissions is to use the simple INI config.// We'll do that by using a factory that can ingest a .ini file and// return a SecurityManager instance:// Use the shiro.ini file at the root of the classpath// (file: and url: prefixes load from files and urls respectively):IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");SecurityManager securityManager = factory.getInstance();// for this simple example quickstart, make the SecurityManager// accessible as a JVM singleton.  Most applications wouldn't do this// and instead rely on their container configuration or web.xml for// webapps.  That is outside the scope of this simple quickstart, so// we'll just do the bare minimum so you can continue to get a feel// for things.SecurityUtils.setSecurityManager(securityManager);// Now that a simple Shiro environment is set up, let's see what you can do:// get the currently executing user://获取当前的Subject,调用SecurityUtils.getSubject()Subject currentUser = SecurityUtils.getSubject();// Do some stuff with a Session (no need for a web or EJB container!!!)//测试使用session,获取session  currentUser.getSession()Session session = currentUser.getSession();//放置属性session.setAttribute("someKey", "aValue");String value = (String) session.getAttribute("someKey");if (value.equals("aValue")) {log.info("---》Retrieved the correct value! [" + value + "]");}// let's login the current user so we can check against roles and permissions://测试当前用户是否已经被认证,即是否已经登录  currentUser.isAuthenticated()if (!currentUser.isAuthenticated()) {//登录失败//System.out.println("Authenticated--->" + currentUser.isAuthenticated());//总是返回false//把用户名和密码封装为UsernamePasswordToken对象UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");//记住我token.setRememberMe(true);try {//执行登录currentUser.login(token);//未知(没指定)的用户名  抛出UnknownAccountException} catch (UnknownAccountException uae) {log.info("There is no user with username of " + token.getPrincipal());//用户存在,未知(没指定)的密码   抛出IncorrectCredentialsException} catch (IncorrectCredentialsException ice) {log.info("Password for account " + token.getPrincipal() + " was incorrect!");//用户被锁定的异常} catch (LockedAccountException lae) {log.info("The account for username " + token.getPrincipal() + " is locked.  " +"Please contact your administrator to unlock it.");}// ... catch more exceptions here (maybe custom ones specific to your application?//所有认证时异常catch (AuthenticationException ae) {//unexpected condition?  error?}}//say who they are://print their identifying principal (in this case, a username):log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");//test a role://测试是否有某一个角色currentUser.hasRole("schwartz")if (currentUser.hasRole("schwartz")) {log.info("May the Schwartz be with you!");} else {log.info("Hello, mere mortal.");}//test a typed permission (not instance-level)//测试是否具有某种行为currentUser.isPermitted("lightsaber:wield")if (currentUser.isPermitted("lightsaber:wield")) {log.info("You may use a lightsaber ring.  Use it wisely.");} else {log.info("Sorry, lightsaber rings are for schwartz masters only.");}//a (very powerful) Instance Level permission:if (currentUser.isPermitted("user:delete:zhangsan")) {log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +"Here are the keys - have fun!");} else {log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");}//all done - log out!//执行注销,调用currentUser.logout()currentUser.logout();//程序结束System.exit(0);}
}

登录拦截

shiro和springboot的整合

导包

<!--        shiro和springboot整合--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.7.1</version></dependency>

ShiroConfig

创建realm—》DefaultWebSecurityManager—》ShiroFilterFactoryBean

@Configuration
public class ShiroConfig {//ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager) {ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();factoryBean.setSecurityManager(securityManager);Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();/*** anon:无需认证即可访问* authc:必须认证才可访问* user:必须拥有记住我功能才能用* perms:拥有对某个资源的权限才能访问* role:拥有某个角色的权限才能访问*///拦截的是url
//        filterChainDefinitionMap.put("/user/add", "authc");
//        filterChainDefinitionMap.put("/user/update", "authc");filterChainDefinitionMap.put("/user/*", "authc");//设置登录的url,即在需要认证但未认证的情况下,会默认走此urlfactoryBean.setLoginUrl("/toLogin");factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);return factoryBean;}//DefaultWebSecurityManager@Bean(name = "securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(userRealm);return securityManager;}//创建realm对象@Beanpublic UserRealm userRealm() {return new UserRealm();}
}

用户认证

@RequestMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, Model model) {//获取用户Subject subject = SecurityUtils.getSubject();//封装用户名和密码UsernamePasswordToken token = new UsernamePasswordToken(username, password);//登录try {subject.login(token);return "index";}catch (UnknownAccountException e) {//用户名不存在model.addAttribute("msg", "用户名不存在");return "login";}catch (IncorrectCredentialsException e) {//密码错误model.addAttribute("msg", "密码错误");return "login";}
}

UserRealm

/*** realm充当了Shiro和应用程序数据之间桥梁,* 当我们进行认证和授权时,哪些用户可以登录,有什么角色,角色又有什么权限都是通过realm知晓的,所以应该至少有一个realm*/
//自定义realm
public class UserRealm extends AuthorizingRealm {//授权处理@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {//调用hasRole()/isPermit()时触发System.out.println("--->授权enter Authorization");return null;}//认证处理@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {//调用SecurityUtils.getSubject() subject.login(token)时触发System.out.println("--->认证enter Authentication");String username = "root";String password = "123";//可以从authenticationToken中获取MyController中的token中的值UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;//认证用户名if (!token.getUsername().equals(username)) {return null;//此处返回的null会触发UnknownAccountException}//认证密码,认证失败会触发IncorrectCredentialsException//用户名–此处传的是用户对象  密码—从数据库中获取的密码  当前的realm名return new SimpleAuthenticationInfo("", password, "");//会和token中的password进行匹配,匹配上了就通过,匹配不上就报异常}
}

整合Mybatis

导包

<!--        整合Mybatis-->
<dependency>    
<groupId>mysql</groupId>    
<artifactId>mysql-connector-java</artifactId>
</dependency><dependency> 
<groupId>log4j</groupId>    
<artifactId>log4j</artifactId>    
<version>1.2.17</version>
</dependency><dependency>  
<groupId>com.alibaba</groupId>    
<artifactId>druid</artifactId>    
<version>1.2.2</version>
</dependency><dependency>   
<groupId>org.mybatis.spring.boot</groupId>    
<artifactId>mybatis-spring-boot-starter</artifactId>    
<version>2.2.0</version>
</dependency>

UserRealm

/* * realm充当了Shiro和应用程序数据之间桥梁,* 当我们进行认证和授权时,哪些用户可以登录,有什么角色,角色又有什么权限都是通过realm知晓的,所以应该至少有一个realm*/
//自定义realm
public class UserRealm extends AuthorizingRealm {@Autowiredprivate UserServiceImpl userService;//授权处理@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {//调用hasRole()/isPermit()/factoryBean.setUnauthorizedUrl("/unauth")时触发System.out.println("--->授权enter Authorization");Subject subject = SecurityUtils.getSubject();User user = (User) subject.getPrincipal();//可以从SimpleAuthenticationInfo()的第一个参数中获得SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.addStringPermission(user.getPerms());return info;}//认证处理@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {//调用SecurityUtils.getSubject() subject.login(token)时触发System.out.println("--->认证enter Authentication");//可以从authenticationToken中获取MyController中的token中的值UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;//连接真实数据库User user = userService.queryByName(token.getUsername());if (user == null) {return null;//此处返回的null会触发UnknownAccountException}//加密默认为SimpleCredentialsMatcher,还有HashedCredentialsMatcher加密,好像没有MD5加密,盐值return new SimpleAuthenticationInfo(user, user.getPwd(), "");//这个要String类型//        未连接数据库//        String username = "root";
//        String password = "123";//认证用户名
//        if (!token.getUsername().equals(username)) {
//            return null;//此处返回的null会触发UnknownAccountException
//        }//认证密码,认证失败会触发IncorrectCredentialsException//用户名–此处传的是用户对象  密码—从数据库中获取的密码  当前的realm名
//        return new SimpleAuthenticationInfo("", password, "");//会和token中的password进行匹配,匹配上了就通过,匹配不上就报异常}
}

实现授权

ShiroConfig

@Configuration
public class ShiroConfig {//ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager) {ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();factoryBean.setSecurityManager(securityManager);Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();/*** anon:无需认证即可访问* authc:必须认证才可访问* user:必须拥有记住我功能才能用* perms:拥有对某个资源的权限才能访问* role:拥有某个角色的权限才能访问*///拦截的是url//正常情况下未授权,会跳转到未授权页面filterChainDefinitionMap.put("/user/add", "perms[user:add]");filterChainDefinitionMap.put("/user/update", "perms[user:update]");filterChainDefinitionMap.put("/user/*", "authc");//需登录//        filterChainDefinitionMap.put("/user/update", "authc");
//        filterChainDefinitionMap.put("/user/add", "authc");//设置登录的url,即在需要认证但未认证的情况下,会默认走此urlfactoryBean.setLoginUrl("/toLogin");//未授权的urlfactoryBean.setUnauthorizedUrl("/unauth");factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);return factoryBean;}//DefaultWebSecurityManager@Bean(name = "securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(userRealm);return securityManager;}//创建realm对象@Beanpublic UserRealm userRealm() {return new UserRealm();}
}

UserRealm

/*** realm充当了Shiro和应用程序数据之间桥梁,* 当我们进行认证和授权时,哪些用户可以登录,有什么角色,角色又有什么权限都是通过realm知晓的,所以应该至少有一个realm*/
//自定义realm
public class UserRealm extends AuthorizingRealm {@Autowiredprivate UserServiceImpl userService;//授权处理@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {//调用hasRole()/isPermit()/factoryBean.setUnauthorizedUrl("/unauth")时触发System.out.println("--->授权enter Authorization");Subject subject = SecurityUtils.getSubject();User user = (User) subject.getPrincipal();//可以从SimpleAuthenticationInfo()的第一个参数中获得SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.addStringPermission(user.getPerms());//从数据库中获取权限return info;}//认证处理@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {//调用SecurityUtils.getSubject() subject.login(token)时触发System.out.println("--->认证enter Authentication");//可以从authenticationToken中获取MyController中的token中的值UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;//连接真实数据库User user = userService.queryByName(token.getUsername());if (user == null) {return null;//此处返回的null会触发UnknownAccountException}//加密默认为SimpleCredentialsMatcher,还有HashedCredentialsMatcher加密,好像没有MD5加密,盐值return new SimpleAuthenticationInfo(user, user.getPwd(), "");//这个要String类型}
}

thymeleaf和shiro

导包

<!--        shrio和thymeleaf-->        
<dependency>            
<groupId>com.github.theborakompanioni</groupId>            
<artifactId>thymeleaf-extras-shiro</artifactId>            
<version>2.0.0</version>        
</dependency>

UserRealm

/*** realm充当了Shiro和应用程序数据之间桥梁,* 当我们进行认证和授权时,哪些用户可以登录,有什么角色,角色又有什么权限都是通过realm知晓的,所以应该至少有一个realm*/
//自定义realm
public class UserRealm extends AuthorizingRealm {@Autowiredprivate UserServiceImpl userService;//授权处理@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {//调用hasRole()/isPermit()/factoryBean.setUnauthorizedUrl("/unauth")时触发System.out.println("--->授权enter Authorization");Subject subject = SecurityUtils.getSubject();User user = (User) subject.getPrincipal();//可以从SimpleAuthenticationInfo()的第一个参数中获得SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.addStringPermission(user.getPerms());//从数据库中获取权限return info;}//认证处理@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {//调用SecurityUtils.getSubject() subject.login(token)时触发System.out.println("--->认证enter Authentication");//可以从authenticationToken中获取MyController中的token中的值UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;//连接真实数据库User user = userService.queryByName(token.getUsername());if (user == null) {return null;//此处返回的null会触发UnknownAccountException}Subject currSubject = SecurityUtils.getSubject();Session session = currSubject.getSession();session.setAttribute("loginUser", user);//加密默认为SimpleCredentialsMatcher,还有HashedCredentialsMatcher加密,好像没有MD5加密,盐值return new SimpleAuthenticationInfo(user, user.getPwd(), "");//这个要String类型}
}

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th=""xmlns:shiro="">
<head><meta charset="UTF-8"><title>首页</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p><!--thymeleaf和shiro结合-->
<div th:if="${session.loginUser==null}"><a th:href="@{/toLogin}">登录</a>
</div><div shiro:hasPermission="user:add"><a th:href="@{/user/add}">add</a>
</div><div shiro:hasPermission="user:update"><a th:href="@{/user/update}">update</a>
</div></body>
</html>

更多推荐

SpringBoot学习(六)————简单的shiro启动、登录拦截、用户认证、整合Mybatis、实现授权、thymeleaf和shir整合

本文发布于:2024-02-11 19:27:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1682927.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单   用户   shiro   SpringBoot   thymeleaf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!