springboot中動態(tài)權(quán)限實時管理的實現(xiàn)詳解
以下這個案例將涉及到一個權(quán)限管理場景,假設(shè)我們有一個內(nèi)部管理系統(tǒng),管理員可以動態(tài)變更用戶的權(quán)限。我們將演示在用戶訪問某個資源時,權(quán)限發(fā)生變更后,系統(tǒng)自動響應(yīng)并及時反饋權(quán)限的變化。
場景描述
在這個場景中,用戶有一個可以管理資源的頁面,比如一個“訂單管理系統(tǒng)”,用戶可以創(chuàng)建、編輯、刪除訂單。系統(tǒng)管理員可以動態(tài)更改用戶的權(quán)限,比如撤銷其“刪除訂單”的權(quán)限。當(dāng)管理員更改用戶權(quán)限后,前端頁面會監(jiān)聽這個權(quán)限的變化。通過瀏覽器端訂閱消息隊列(MQ)的方式,實時地收到權(quán)限變化通知,并根據(jù)權(quán)限變動做出相應(yīng)操作。
如果用戶的權(quán)限被撤銷,前端會立即更新顯示。若用戶嘗試進行不允許的操作(例如刪除操作),系統(tǒng)會彈出權(quán)限不足的提示。
技術(shù)要點
Spring Boot作為后端框架。
RabbitMQ作為消息隊列,實現(xiàn)權(quán)限變更的通知。
前端使用WebSocket訂閱RabbitMQ隊列,監(jiān)聽權(quán)限變更。
使用Spring Security進行權(quán)限控制。
復(fù)雜場景:權(quán)限動態(tài)變更后,實時限制用戶操作(刪除按鈕隱藏,彈出權(quán)限變更通知)。
解決方案
Spring Boot后端處理權(quán)限變更: 當(dāng)管理員修改了某個用戶的權(quán)限,系統(tǒng)會將權(quán)限變更的消息發(fā)送到RabbitMQ隊列,前端會通過WebSocket接收并實時更新頁面。
前端處理權(quán)限變更: 用戶頁面通過WebSocket連接到后端,監(jiān)聽權(quán)限的變更。一旦收到權(quán)限變更消息,前端立即更新用戶界面。
MQ訂閱與前端動態(tài)變動: WebSocket與RabbitMQ的結(jié)合使得權(quán)限變更可以及時反映在前端,無需手動刷新。若用戶嘗試操作失去權(quán)限的功能,會出現(xiàn)提示框告知用戶權(quán)限不足。
實際代碼實現(xiàn)
1. Spring Boot配置
配置RabbitMQ
在Spring Boot中配置RabbitMQ的連接和隊列。
application.yml:
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
創(chuàng)建消息隊列配置類
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
public static final String PERMISSION_CHANGE_QUEUE = "permission_change_queue";
@Bean
public Queue permissionChangeQueue() {
return new Queue(PERMISSION_CHANGE_QUEUE);
}
}
權(quán)限變更服務(wù)
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PermissionChangeService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void notifyPermissionChange(String userId) {
// 發(fā)送權(quán)限變更消息到隊列
rabbitTemplate.convertAndSend(RabbitConfig.PERMISSION_CHANGE_QUEUE, userId);
}
}
模擬權(quán)限變更控制器
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AdminController {
@Autowired
private PermissionChangeService permissionChangeService;
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/changePermission")
public String changePermission(@RequestParam String userId, @RequestParam String newPermission) {
// 修改數(shù)據(jù)庫中的權(quán)限邏輯(省略)
// 通知權(quán)限變更
permissionChangeService.notifyPermissionChange(userId);
return "Permissions updated for user: " + userId;
}
}
WebSocket配置類
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
}
WebSocket消息發(fā)送服務(wù)
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
@Service
public class WebSocketNotificationService {
private final SimpMessagingTemplate messagingTemplate;
public WebSocketNotificationService(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
public void notifyUser(String userId, String message) {
messagingTemplate.convertAndSend("/topic/permission/" + userId, message);
}
}
消費者監(jiān)聽權(quán)限變更消息
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PermissionChangeListener {
@Autowired
private WebSocketNotificationService webSocketNotificationService;
@RabbitListener(queues = RabbitConfig.PERMISSION_CHANGE_QUEUE)
public void handlePermissionChange(String userId) {
// 通知前端權(quán)限變更
webSocketNotificationService.notifyUser(userId, "Your permissions have been changed. Please refresh.");
}
}
2. 前端代碼
WebSocket連接和權(quán)限監(jiān)聽
假設(shè)使用Vue.js前端框架。
WebSocket.js:
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
let stompClient = null;
export function connect(userId, onPermissionChange) {
const socket = new SockJS('/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, function () {
stompClient.subscribe('/topic/permission/' + userId, function (message) {
onPermissionChange(JSON.parse(message.body));
});
});
}
export function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
}
Vue組件中的使用
<template>
<div>
<h1>Order Management</h1>
<button v-if="canDelete" @click="deleteOrder">Delete Order</button>
<p v-if="!canDelete" style="color:red">You do not have permission to delete orders</p>
</div>
</template>
<script>
import { connect, disconnect } from '@/websocket';
export default {
data() {
return {
canDelete: true
};
},
created() {
const userId = this.$store.state.user.id;
connect(userId, this.handlePermissionChange);
},
beforeDestroy() {
disconnect();
},
methods: {
handlePermissionChange(message) {
alert(message);
this.canDelete = false; // 動態(tài)撤銷刪除權(quán)限
},
deleteOrder() {
if (this.canDelete) {
// 發(fā)送刪除請求
} else {
alert('You do not have permission to delete this order.');
}
}
}
};
</script>
運行流程
用戶登錄系統(tǒng),進入“訂單管理”頁面。
管理員在后臺更改用戶權(quán)限,撤銷其“刪除訂單”的權(quán)限。
后端通過RabbitMQ發(fā)送權(quán)限變更的消息,消息通過WebSocket通知前端用戶。
前端頁面接收到消息后,自動禁用“刪除訂單”按鈕,用戶再也無法點擊該按鈕。
若用戶試圖刪除訂單,系統(tǒng)會彈出權(quán)限不足的提示。
總結(jié)
這個案例展示了如何使用Spring Boot結(jié)合RabbitMQ和WebSocket處理權(quán)限動態(tài)變更的場景。通過實時監(jiān)聽權(quán)限變更并及時在前端做出反饋,可以確保用戶操作權(quán)限的準(zhǔn)確性,同時提高用戶體驗。
到此這篇關(guān)于springboot中動態(tài)權(quán)限實時管理的實現(xiàn)詳解的文章就介紹到這了,更多相關(guān)springboot動態(tài)權(quán)限實時管理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Java應(yīng)用程序添加或刪除 PDF 中的附件
當(dāng)我們在制作PDF文件或者PPT演示文稿的時候,為了讓自己的文件更全面詳細,就會在文件中添加附件,那么如何添加或刪除PDF中的附件呢,今天通過本文給大家詳細講解,需要的朋友參考下吧2023-01-01
使用IDEA創(chuàng)建Java Web項目并部署訪問的圖文教程
本文通過圖文并茂的形式給大家介紹了使用IDEA創(chuàng)建Java Web項目并部署訪問的教程,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
Spring實戰(zhàn)之使用c:命名空間簡化配置操作示例
這篇文章主要介紹了Spring實戰(zhàn)之使用c:命名空間簡化配置操作,結(jié)合實例形式詳細分析了Spring使用c:命名空間簡化配置的相關(guān)接口與配置操作技巧,需要的朋友可以參考下2019-12-12

