GlobalPermissionEvaluator 後,還需要將其註冊到SecurityConfig中!否則Spring會使用預設的Evaluator,其中委派的PermissionEvaluator實作是 DenyAllPermissionEvaluator。// 加入我們的實作
private final GlobalPermissionEvaluator globalPermissionEvaluator;
// 初始化
public SecurityConfiguration(JwtAuthenticationFilter jwtAuthenticationFilter, GlobalPermissionEvaluator globalPermissionEvaluator) {
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
this.globalPermissionEvaluator = globalPermissionEvaluator;
}
// 設置Bean
@Bean
public MethodSecurityExpressionHandler methodSecurityExpressionHandler(){
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(globalPermissionEvaluator);
return expressionHandler;
}
RequirePermission ➝ 針對PermissionCode做檢查。PreAuthorize("hasRole('ADMIN')") 形式。@DeleteMapping("/prod/{merchandiseId}")
public Response<MerchandiseResponse> deleteById(@PathVariable String merchandiseId){
return merchandiseService.deleteById(merchandiseId);
}
// 加入hasPermission
@PreAuthorize("hasPermission(#merchandiseId, 'MERCHANDISE', 'DELETE')")
@DeleteMapping("/prod/{merchandiseId}")
public Response<MerchandiseResponse> deleteById(@PathVariable String merchandiseId){
return merchandiseService.deleteById(merchandiseId);
}
getCategoryById 這種看類別功能,訪客也能請求的路徑,一般會permitAll,因此不符合PreAuthorize的概念,也自然不能使用。@Transactional
public Response<UserResponse> delete(String account, DeleteUserRequest deleteUserRequest){
String id = deleteUserRequest.getId();
User operator = userDao.findByAccount(account).orElseThrow(() -> new AuthException(4001, "UserTokenError"));
User target = userDao.findById(id).orElseThrow(() -> ResourcesException.of(ErrorCode.USER_NOT_FOUND));
boolean isSelf = operator.getId().equals(target.getId());
boolean hasDeletePermission = rolePermissionDao.existsByRoleAndPermissionId(operator.getRole(), PermissionCode.DELETE_USER.getCode());
if (!(isSelf || hasDeletePermission)) return new Response<>("1", "InValidOperation", null);
UserResponse userResponse = new UserResponse(target);
cartDao.findByUser(target).ifPresent(cartDao::delete);
userDao.delete(target);
return isSelf ? new Response<>("0", "Successfully delete " + target.getUsername() + " By " + target.getUsername(), userResponse)
: new Response<>("0", "Successfully delete " + target.getUsername() + " By ADMIN", userResponse);
}
@Transactional
public Response<UserResponse> delete(DeleteUserRequest deleteUserRequest) {
User target = userDao.findById(deleteUserRequest.getId())
.orElseThrow(() -> ResourcesException.of(ErrorCode.USER_NOT_FOUND));
cartDao.findByUser(target).ifPresent(cartDao::delete);
userDao.delete(target);
return new Response<>("0", "Successfully delete " + target.getUsername(), new UserResponse(target));
}
本篇文章出自《每天學Java直到今年結束》Day241,大家可以到我的網站上查看~