本篇文章為大家展示了springboot如何整合shiro實現登錄驗證授權的過程解析,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
springboot整合shiro實現登錄驗證授權,內容如下所示:
<!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency>
#配置服務端口 server: port: 8080 servlet: encoding: charset: utf-8 enabled: true force: true context-path: /cxh/ spring: #配置數據源 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.entity
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進行處理
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("MD5");//散列算法:這里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次數;
return hashedCredentialsMatcher;
//將自己的驗證方式加入容器
public LoginRealm myShiroRealm() {
LoginRealm loginRealm = new LoginRealm();
//加入密碼管理
loginRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return loginRealm;
//權限管理,配置主要是Realm的管理認證
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
//Filter工廠,設置對應的過濾條件和跳轉條件
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");
//靜態文件包
map.put("/res/**", "anon");
//對所有用戶認證
map.put("/**", "authc");
shiroFilterFactoryBean.setLoginUrl("/login");
//首頁
shiroFilterFactoryBean.setSuccessUrl("/index");
//錯誤頁面,認證不通過跳轉
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}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;
/**
* 授權
*/
@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認證對象
info.setRoles(roles);
// 權限加入AuthorizationInfo認證對象
info.setStringPermissions(menus);
return info;
}
* 登錄認證
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(); //未知賬號
//判斷賬號是否被鎖定,狀態(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; //加密的次數
//加密
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, originalPassword, salt, hashIterations);
String encryptionPassword = simpleHash.toString();
//輸出加密密碼
System.out.println(encryptionPassword);
}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)
{
//參數驗證
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
{
modelMap.addAttribute("message", "賬號密碼必填!");
return "admin/loginPage";
}
//賬號密碼令牌
AuthenticationToken token = new UsernamePasswordToken(username, password);
//獲得當前用戶到登錄對象,現在狀態為未認證
Subject subject = SecurityUtils.getSubject();
try
//將令牌傳到shiro提供的login方法驗證,需要自定義realm
subject.login(token);
//沒有異常表示驗證成功,進入首頁
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", "用戶名或密碼錯誤次數太多!");
catch (AuthenticationException ae)
modelMap.addAttribute("message", "驗證未通過!");
catch (Exception e)
//返回登錄頁
* 登出操作
@RequestMapping("/logout")
public String logout()
//登出清除緩存
subject.logout();
return "redirect:/login";
}<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;
}上述內容就是springboot如何整合shiro實現登錄驗證授權的過程解析,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。