springboot整合shiro實現(xiàn)登錄驗證授權(quán)的過程解析
springboot整合shiro實現(xiàn)登錄驗證授權(quán),內(nèi)容如下所示:
1.添加依賴:
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>2.yml配置:
#配置服務(wù)端口
server:
port: 8080
servlet:
encoding:
charset: utf-8
enabled: true
force: true
context-path: /cxh/
spring:
#配置數(shù)據(jù)源
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/cxh_mall_service?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
#配置頁面
mvc:
view:
prefix: /WEB-INF/page/
suffix: .jsp
#配置上傳文件大小
servlet:
multipart:
max-file-size: 10MB
#配置Mybatis
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.cxh.mall.entity3.shiro配置:
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
defaultAAP.setProxyTargetClass(true);
return defaultAAP;
}
//憑證匹配器, 密碼校驗交給Shiro的SimpleAuthenticationInfo進(jìn)行處理
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("MD5");//散列算法:這里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次數(shù);
return hashedCredentialsMatcher;
//將自己的驗證方式加入容器
public LoginRealm myShiroRealm() {
LoginRealm loginRealm = new LoginRealm();
//加入密碼管理
loginRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return loginRealm;
//權(quán)限管理,配置主要是Realm的管理認(rèn)證
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
//Filter工廠,設(shè)置對應(yīng)的過濾條件和跳轉(zhuǎn)條件
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> map = new HashMap<>();
//登出
map.put("/logout", "logout");
//登錄
map.put("/loginSubmit", "anon");
//靜態(tài)文件包
map.put("/res/**", "anon");
//對所有用戶認(rèn)證
map.put("/**", "authc");
shiroFilterFactoryBean.setLoginUrl("/login");
//首頁
shiroFilterFactoryBean.setSuccessUrl("/index");
//錯誤頁面,認(rèn)證不通過跳轉(zhuǎn)
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}4.shiro登錄驗證授權(quán):
import com.cxh.mall.entity.SysUser;
import com.cxh.mall.service.SysMenuService;
import com.cxh.mall.service.SysRoleService;
import com.cxh.mall.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.Set;
public class LoginRealm extends AuthorizingRealm {
@Autowired
@Lazy
private SysUserService sysUserService;
private SysRoleService sysRoleService;
private SysMenuService sysMenuService;
/**
* 授權(quán)
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
String username = (String) arg0.getPrimaryPrincipal();
SysUser sysUser = sysUserService.getUserByName(username);
// 角色列表
Set<String> roles = new HashSet<String>();
// 功能列表
Set<String> menus = new HashSet<String>();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
roles = sysRoleService.listByUser(sysUser.getId());
menus = sysMenuService.listByUser(sysUser.getId());
// 角色加入AuthorizationInfo認(rèn)證對象
info.setRoles(roles);
// 權(quán)限加入AuthorizationInfo認(rèn)證對象
info.setStringPermissions(menus);
return info;
}
* 登錄認(rèn)證
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
return null;
}
//獲取用戶信息
String username = authenticationToken.getPrincipal().toString();
if (username == null || username.length() == 0)
{
SysUser user = sysUserService.getUserByName(username);
if (user == null)
throw new UnknownAccountException(); //未知賬號
//判斷賬號是否被鎖定,狀態(tài)(0:禁用;1:鎖定;2:啟用)
if(user.getStatus() == 0)
throw new DisabledAccountException(); //帳號禁用
if (user.getStatus() == 1)
throw new LockedAccountException(); //帳號鎖定
//鹽
String salt = "123456";
//驗證
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
username, //用戶名
user.getPassword(), //密碼
ByteSource.Util.bytes(salt), //鹽
getName() //realm name
);
return authenticationInfo;
public static void main(String[] args) {
String originalPassword = "123456"; //原始密碼
String hashAlgorithmName = "MD5"; //加密方式
int hashIterations = 2; //加密的次數(shù)
//加密
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, originalPassword, salt, hashIterations);
String encryptionPassword = simpleHash.toString();
//輸出加密密碼
System.out.println(encryptionPassword);
}5.登錄控制器:
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
@Controller
@Slf4j
public class LoginController {
/**
* 登錄頁面
*/
@GetMapping(value={"/", "/login"})
public String login(){
return "admin/loginPage";
}
* 登錄操作
@RequestMapping("/loginSubmit")
public String login(String username, String password, ModelMap modelMap)
{
//參數(shù)驗證
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
{
modelMap.addAttribute("message", "賬號密碼必填!");
return "admin/loginPage";
}
//賬號密碼令牌
AuthenticationToken token = new UsernamePasswordToken(username, password);
//獲得當(dāng)前用戶到登錄對象,現(xiàn)在狀態(tài)為未認(rèn)證
Subject subject = SecurityUtils.getSubject();
try
//將令牌傳到shiro提供的login方法驗證,需要自定義realm
subject.login(token);
//沒有異常表示驗證成功,進(jìn)入首頁
return "admin/homePage";
catch (IncorrectCredentialsException ice)
modelMap.addAttribute("message", "用戶名或密碼不正確!");
catch (UnknownAccountException uae)
modelMap.addAttribute("message", "未知賬戶!");
catch (LockedAccountException lae)
modelMap.addAttribute("message", "賬戶被鎖定!");
catch (DisabledAccountException dae)
modelMap.addAttribute("message", "賬戶被禁用!");
catch (ExcessiveAttemptsException eae)
modelMap.addAttribute("message", "用戶名或密碼錯誤次數(shù)太多!");
catch (AuthenticationException ae)
modelMap.addAttribute("message", "驗證未通過!");
catch (Exception e)
//返回登錄頁
* 登出操作
@RequestMapping("/logout")
public String logout()
//登出清除緩存
subject.logout();
return "redirect:/login";
}6.前端登錄頁面:
<div>
<div><p>cxh電商平臺管理后臺</p></div>
<div>
<form name="loginForm" method="post" action="/cxh/loginSubmit" onsubmit="return SubmitLogin()" autocomplete="off">
<input type="text" name="username" placeholder="用戶名"/>
<input type="password" name="password" placeholder="密碼" autocomplete="on">
<span>${message}</span>
<input type="submit" value="登錄"/>
</form>
</div>
</div>//提交登錄
function SubmitLogin() {
//判斷用戶名是否為空
if (!loginForm.username.value) {
alert("請輸入用戶姓名!");
loginForm.username.focus();
return false;
}
//判斷密碼是否為空
if (!loginForm.password.value) {
alert("請輸入登錄密碼!");
loginForm.password.focus();
return false;
}
return true;
}到此這篇關(guān)于springboot整合shiro實現(xiàn)登錄驗證授權(quán)的文章就介紹到這了,更多相關(guān)springboot整合shiro登錄驗證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用JWT實現(xiàn)登錄驗證的方法示例
- SpringBoot登錄驗證碼實現(xiàn)過程詳解
- SpringBoot Security前后端分離登錄驗證的實現(xiàn)
- Springboot2.1.6集成activiti7出現(xiàn)登錄驗證的實現(xiàn)
- vue+springboot實現(xiàn)登錄驗證碼
- SpringBoot登錄驗證token攔截器的實現(xiàn)
- Springboot登錄驗證的統(tǒng)一攔截處理的實現(xiàn)
- SpringBoot集成JWT實現(xiàn)Token登錄驗證的示例代碼
- SpringBoot中過濾器Filter+JWT令牌實現(xiàn)登錄驗證
相關(guān)文章
Spring?Boot?集成Redisson實現(xiàn)分布式鎖詳細(xì)案例
這篇文章主要介紹了Spring?Boot?集成Redisson實現(xiàn)分布式鎖詳細(xì)案例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-08-08
springmvc學(xué)習(xí)筆記-返回json的日期格式問題的解決方法
本篇文章主要介紹了springmvc學(xué)習(xí)筆記-返回json的日期格式問題的解決方法,解決了日期格式的輸出,有興趣的可以了解一下。2017-01-01
基于SpringMVC攔截器實現(xiàn)接口耗時監(jiān)控功能
本文呢主要介紹了基于SpringMVC攔截器實現(xiàn)的接口耗時監(jiān)控功能,統(tǒng)計接口的耗時情況屬于一個可以復(fù)用的功能點,因此這里直接使用 SpringMVC的HandlerInterceptor攔截器來實現(xiàn),需要的朋友可以參考下2024-02-02
Java的StringBuilder在高性能場景下的正確用法
StringBuilder?對字符串的操作是直接改變字符串對象本身,而不是生成新的對象,所以新能開銷小.與StringBuffer相比StringBuilder的性能略高,StringBuilder則沒有保證線程的安全,從而性能略高于StringBuffer,需要的朋友可以參考下2023-05-05
在SpringBoot中無縫整合Dubbo的實現(xiàn)過程
微服務(wù)架構(gòu)已經(jīng)成為現(xiàn)代應(yīng)用開發(fā)的熱門趨勢,而Dubbo作為一款強大的分布式服務(wù)框架,與Spring?Boot的結(jié)合是構(gòu)建高性能微服務(wù)應(yīng)用的理想選擇,本文將詳細(xì)介紹如何在SpringBoot中無縫整合Dubbo,需要的朋友可以參考下2024-01-01

