Spring Security 強制退出指定用戶的方法
應用場景
最近社區(qū)總有人發(fā)文章帶上小廣告,嚴重影響社區(qū)氛圍,好氣!對于這種類型的用戶,就該永久拉黑!
社區(qū)的安全框架使用了 spring-security 和 spring-session,登錄狀態(tài) 30 天有效,session 信息是存在 redis 中,如何優(yōu)雅地處理這些不老實的用戶呢?
首先,簡單劃分下用戶的權(quán)限:
- 管理員(ROLE_MANAGER):基本操作 + 管理操作
- 普通用戶(ROLE_USER):基本操作
- 拉黑用戶(ROLE_BLACK):不允許登錄
然后,拉黑指定用戶(ROLE_USER -> ROLE_BLACK),再強制該用戶退出即可(刪除該用戶在 redis 中 session 信息)。
項目相關依賴及配置
Maven 依賴
<!-- 安全 Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Spring Session Redis -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
Spring Session 策略配置 application.yml
# 此處省略 redis 連接相關配置 spring: session: store-type: redis
Spring Security 配置代碼示例
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/manager/**").hasAnyRole(RoleEnum.MANAGER.getMessage())
.anyRequest().permitAll()
.and().formLogin().loginPage("/login").permitAll()
.and().logout().permitAll()
.and().csrf().disable();
}
}
強制退出指定給用戶接口
import com.spring4all.bean.ResponseBean;
import com.spring4all.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@AllArgsConstructor
public class UserManageApi {
private final FindByIndexNameSessionRepository<? extends Session> sessionRepository;
private final RedisOperationsSessionRepository redisOperationsSessionRepository;
private final UserService userService;
/**
* 管理指定用戶退出登錄
* @param userId 用戶ID
* @return 用戶 Session 信息
*/
@PreAuthorize("hasRole('MANAGER')")
@GetMapping("/manager/logout/{userId}")
public ResponseBean data(@PathVariable() Long userId){
// 查詢 PrincipalNameIndexName(Redis 用戶信息的 key),結(jié)合自身業(yè)務邏輯來實現(xiàn)
String indexName = userService.getPrincipalNameIndexName(userId);
// 查詢用戶的 Session 信息,返回值 key 為 sessionId
Map<String, ? extends Session> userSessions = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, indexName);
// 移除用戶的 session 信息
List<String> sessionIds = new ArrayList<>(userSessions.keySet());
for (String session : sessionIds) {
redisOperationsSessionRepository.deleteById(session);
}
return ResponseBean.success(userSessions);
}
}
說明 indexName 為 Principal.getName() 的返回值。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java實現(xiàn)創(chuàng)建Zip壓縮包并寫入文件
這篇文章主要為大家詳細介紹了Java實現(xiàn)創(chuàng)建Zip壓縮包并寫入文件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
Spring WebFlux使用函數(shù)式編程模型構(gòu)建異步非阻塞服務
這篇文章主要介紹了Spring WebFlux使用函數(shù)式編程模型構(gòu)建異步非阻塞服務,重點介紹如何使用函數(shù)式編程模型創(chuàng)建響應式 RESTful 服務,這種編程模型與傳統(tǒng)的基于 Spring MVC 構(gòu)建 RESTful 服務的方法有較大差別,感興趣的朋友跟隨小編一起看看吧2023-08-08

