一、什麼是Shiro?
Shiro是一個強大、易用的Java安全框架,用於身份驗證、授權、密碼和會話管理。Shiro的優點是簡單直接,能夠輕鬆地集成到任何Java應用程序中。
二、為什麼要使用Spring Boot集成Shiro?
Spring Boot是一個快速開發框架,它提供了很多內置的特性,包括自動配置、自動裝配、功能強大的監視和管理功能等。集成Shiro可以讓Spring Boot應用程序更加安全、可靠和易於維護。
三、Spring Boot集成Shiro的步驟
1. 添加依賴
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.6.0</version>
</dependency>
2. 配置Shiro
在application.yml中添加以下配置:
shiro:
filter-chain-definitions:
/login: anon
/logout: anon
/**: authc
login-url: /login
success-url: /index
unauthorized-url: /unauthorized
這裡定義了Shiro的過濾器鏈和一些默認的URL。/login和/logout是匿名訪問的,其他的URL需要身份驗證。
3. 自定義ShiroRealm
創建一個名為MyRealm的類:
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principals.getPrimaryPrincipal();
for (Role role : user.getRoles()) {
authorizationInfo.addRole(role.getRoleName());
for (Permission permission : role.getPermissions()) {
authorizationInfo.addStringPermission(permission.getPermissionName());
}
}
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException("用戶名或密碼錯誤!");
}
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
}
通過繼承AuthorizingRealm和實現doGetAuthenticationInfo和doGetAuthorizationInfo方法,我們就可以定製化ShiroRealm了。
4. 自定義密碼加密方式
創建一個名為MyHashedCredentialsMatcher的類:
public class MyHashedCredentialsMatcher extends HashedCredentialsMatcher {
public MyHashedCredentialsMatcher() {
super.setHashAlgorithmName("SHA-256"); // 哈希算法
super.setHashIterations(5); // 哈希次數
super.setStoredCredentialsHexEncoded(true); // 存儲16進制格式
}
}
通過繼承HashedCredentialsMatcher,我們可以自定義密碼加密方式。在MyRealm類中重寫該方法:
@Override
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
HashedCredentialsMatcher hashedCredentialsMatcher = new MyHashedCredentialsMatcher();
super.setCredentialsMatcher(hashedCredentialsMatcher);
}
5. 配置ShiroFilter
在@Configuration註解的配置類中添加以下代碼:
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
factoryBean.setSecurityManager(securityManager);
factoryBean.setLoginUrl("/login");
factoryBean.setSuccessUrl("/index");
factoryBean.setUnauthorizedUrl("/unauthorized");
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("https://static.506064.com/favicon.ico", "anon");
filterChainDefinitionMap.put("/**", "authc");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return factoryBean;
}
這裡我們定義了一個ShiroFilter,設置了默認的登錄、成功和未授權的URL,還有過濾器鏈,即哪些URL需要被驗證。通常情況下靜態資源,如CSS、JS和圖片,是允許匿名訪問的。
6. 配置SecurityManager
在@Configuration註解的配置類中添加以下代碼:
@Bean
public SecurityManager securityManager(@Qualifier("authRealm") MyRealm authRealm) {
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(authRealm);
manager.setSessionManager(sessionManager());
return manager;
}
@Bean
public SessionManager sessionManager() {
DefaultWebSessionManager manager = new DefaultWebSessionManager();
manager.setGlobalSessionTimeout(30 * 60 * 1000); // 會話過期時間
manager.setDeleteInvalidSessions(true); // 刪除無效的會話
return manager;
}
@Bean(name = "authRealm")
public MyRealm authRealm(@Qualifier("hashedCredentialsMatcher") MyHashedCredentialsMatcher hashedCredentialsMatcher) {
MyRealm realm = new MyRealm();
realm.setCredentialsMatcher(hashedCredentialsMatcher); // 密碼加密方式
return realm;
}
@Bean(name = "hashedCredentialsMatcher")
public MyHashedCredentialsMatcher hashedCredentialsMatcher() {
return new MyHashedCredentialsMatcher();
}
這裡我們定義了一個SecurityManager,啟用了我們自己定製的MyRealm,並設置了密碼加密方式和會話管理器。會話過期時間可以根據需要自行調整。
四、總結
Spring Boot集成Shiro需要哪些步驟?首先添加依賴,然後配置Shiro、自定義ShiroRealm、自定義密碼加密方式、配置ShiroFilter和SecurityManager。
集成Shiro能讓我們的Spring Boot應用程序更加安全和可靠,並提供了更多的身份驗證、密碼和會話管理功能。
原創文章,作者:DJZXU,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/343230.html