手机网站淘宝客怎么做网站地图案例

张小明 2026/1/9 16:07:30
手机网站淘宝客怎么做,网站地图案例,html网站开发实例教程,自助网站免费前言 在當今瞬息萬變的 Web 環境中#xff0c;應用程式安全比以往任何時候都更加重要。為保護服務、資料等各項資源#xff0c;不被任意存取。Spring 提供了 Spring Security 驗證框架#xff0c;它能幫助我們開發有關認證與授權等有關安全管理的功能。下面讓我們透過簡單的…前言在當今瞬息萬變的 Web 環境中應用程式安全比以往任何時候都更加重要。為保護服務、資料等各項資源不被任意存取。Spring 提供了 Spring Security 驗證框架它能幫助我們開發有關認證與授權等有關安全管理的功能。下面讓我們透過簡單的例子初窺如何運用。專案實作註: 基於 初探 Vue 與 Spring boot 的對話之Backend (SpringBoot-Backend)文章 專案延生1. 新增 相關 DependenciesPom.xmldependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-security/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-security-test/artifactId scopetest/scope /dependency備註:spring-security-test 官方提供的測試套件用來在 單元測試 與整合測試 中方便地測試與 Spring Security 相關的功能2.增修相關代碼增修 Web 安全性, 網路安全配置類別 WebSecurityConfig/* Web 安全性配置, 網路安全配置 */ Configuration EnableWebSecurity EnableMethodSecurity(prePostEnabled true) public class WebSecurityConfig { Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.csrf(csrf - csrf.disable()) .authorizeHttpRequests(auth - auth .requestMatchers(/api/public/**, /login).permitAll() .requestMatchers(/api/user/**).hasAnyRole(USER, ADMIN) .requestMatchers(/api/users/**).hasRole(ADMIN) .requestMatchers(HttpMethod.POST, /api/user).hasRole(ADMIN) .requestMatchers(HttpMethod.DELETE, /api/users/*) .hasRole(ADMIN) .anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) .formLogin(Customizer.withDefaults()) .build(); } /** * 使用 InMemoryUserDetailsManager,建立帳號與密碼並儲存於記憶體中 * 用於測試定義帶有不同權限的用戶。 */ Bean public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) { // ADMIN 用戶擁有 ADMIN 角色 UserDetails admin User .withUsername(admin) .password(passwordEncoder.encode(password)) .roles(ADMIN) .build(); // USER 用戶擁有 USER 角色 UserDetails normalUser User .withUsername(user) .password(passwordEncoder.encode(password)) .roles(USER) .build(); // GUEST 用戶沒有任何角色 UserDetails guest User .withUsername(guest) .password(passwordEncoder.encode(password)) .roles(GUEST) .build(); return new InMemoryUserDetailsManager(admin, normalUser, guest); } Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }備註/api/users 僅匹配 完全相同 的路徑。例子/api/users 匹配/api/users/ 不匹配/api/users/123 不匹配/api/users/** 匹配以 /api/users/ 開頭的 所有路徑無論子路徑有多少層級。例子/api/users 匹配/api/users/ 匹配/api/users/123 匹配/api/users/data/1 匹配增修 Entity增修 Entity Entity Getter Setter NoArgsConstructor AllArgsConstructor Builder Table(name users) public class User { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; Column(name username, nullable false) private String username; Column(name password, nullable false) private String password; Column(name first_name, nullable false) private String firstName; Column(name last_name) private String lastName; Column(name email, nullable false, unique true) private String email; public User(String username, String password, String firstName, String lastName, String email) { this.username username; this.password password; this.firstName firstName; this.lastName lastName; this.email email; } }增修UserRepositoryRepository public interface UserRepository extends JpaRepositoryUser, Long { OptionalUser findByUsername(String username); Boolean existsByUsername(String username); Boolean existsByEmail(String email); }增修UserSericeSlf4j Service public class UserService { Autowired private UserRepository userRepository; Transactional PreAuthorize(hasAnyRole(ADMIN, USER)) public User saveUser(User user) { log.info(Saving user: user.getUsername()); if (user null) { throw new IllegalArgumentException(User must not be null); } return userRepository.save(user); } /* * PreAuthorize: 在方法執行之前決定是否允許訪問 */ PreAuthorize(hasAuthority(ADMIN)) public ListUser getUsers() { ListUser users null; try { users userRepository.findAll(); log.debug(Number of users fetched: users.size()); } catch (Exception e) { e.printStackTrace(); } return users; } public User getUserById(Long uid) { if (uid null) { throw new UserNotFoundException(null); } User user userRepository.findById(uid) .orElseThrow(() - new UserNotFoundException(uid)); return user; } public User updateUser(RequestBody User newUser, PathVariable Long id) { log.info(Updating user with id: id); return userRepository.findById(id) .map(user - { user.setUsername(null newUser.getUsername() ? user.getUsername() : newUser.getUsername()); user.setPassword(null newUser.getPassword() ? user.getPassword() : newUser.getPassword()); user.setFirstName(null newUser.getFirstName() ? user.getFirstName() : newUser.getFirstName()); user.setLastName(null newUser.getLastName() ? user.getLastName() : newUser.getLastName()); user.setEmail(null newUser.getEmail() ? user.getEmail() : newUser.getEmail()); return userRepository.save(user); }) .orElseGet(() - { return userRepository.save(newUser); }); } public void deleteUser(Long uid) { if (uid null) { throw new UserNotFoundException(null); } userRepository.deleteById(uid); } }增修ControllerSlf4j RestController RequestMapping(/api) public class UserController { Autowired private UserService userService; Autowired private UserRepository userRepository; GetMapping(/public) public String publicApi() { return public OK; } PostMapping(/user) public ResponseEntity? createUser(RequestBody User newUser) { User user userService.saveUser(newUser); return ResponseEntity.ok(user); } GetMapping(/user/{uid}) public User getUserById(PathVariable Long uid) { return userService.getUserById(uid); } GetMapping(/users) public ListUser getAllUsers() { ListUser users userRepository.findAll(); return users; } PutMapping(/users/{uid}) User replaceUser(RequestBody User newUser, PathVariable Long uid) { return userService.updateUser(newUser, uid); } DeleteMapping(/users/{uid}) PreAuthorize(hasAuthority(delete)) void deleteUser(PathVariable Long uid) { userService.deleteUser(uid); } }建立SpringBootTest和MockMvc測試範例import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.dannyyu.backend.model.User; import com.fasterxml.jackson.databind.ObjectMapper; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; SpringBootTest(webEnvironment WebEnvironment.RANDOM_PORT) AutoConfigureMockMvc TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SecurityTest { Autowired private WebApplicationContext context; private MockMvc mockMvc; static Long uid 0L; BeforeEach public void setup() throws Exception { mockMvc MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); } Test Order(7) WithMockUser(username admin, authorities { delete, ROLE_ADMIN }) void testDeleteUser() throws Exception { mockMvc.perform(delete(/api/users/ uid)) .andExpect(status().isOk()); } Test Order(1) WithMockUser(username admin, roles { ADMIN }) public void testCreateUser() throws Exception { MvcResult result null; User createdUser null; String json ; User user new User(test, 123456, test, wu, testexample.com); String jsoString asJsonString(user); result mockMvc.perform( MockMvcRequestBuilders .post(/api/user) .content( jsoString) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); json result.getResponse().getContentAsString(); createdUser new ObjectMapper().readValue(json, User.class); uid createdUser.getId(); } // Public API 無需登入 Test Order(2) WithMockUser(roles { USER }) void testPublicApi() throws Exception { mockMvc.perform(get(/api/public)) .andExpect(status().isOk()); } // 測試 USER角色可存取 /user Test Order(3) WithMockUser(username user, roles { USER }) void testUserApi() throws Exception { mockMvc.perform(get(/api/user/ uid)) .andExpect(status().isOk()); } // 測試 USER 不能存取 /admin Test Order(4) WithMockUser(roles { USER }) void testAdminDenied() throws Exception { mockMvc.perform(get(/api/users)) .andExpect(status().isForbidden()); } // ADMIN 可存取 /users Test Order(5) WithMockUser(roles { ADMIN }) void testAdminApi() throws Exception { mockMvc.perform(get(/api/users)) .andExpect(status().isOk()); } Test Order(6) void testUserApiWithRequestPostProcessor() throws Exception { String responseBody mockMvc.perform( get(/api/user/ uid).with( user(admin).roles(ADMIN))) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); System.out.println(****** 取得角色: ******); System.out.println(responseBody); } public static String asJsonString(final Object obj) { try { return new ObjectMapper().writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException(e); } } }執行測試案例成功% mvn test. . .[INFO] -------------------------------------------------------[INFO] T E S T S[INFO] -------------------------------------------------------[INFO] Running com.dannyyu.backend.controller.SecurityTest. . .. . .Hibernate: select u1_0.id,u1_0.email,u1_0.first_name,u1_0.last_name,u1_0.password,u1_0.username from users u1_0 where u1_0.id?Hibernate: delete from users where id?[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.966 s -- in com.dannyyu.backend.controller.SecurityTest[INFO][INFO] Results:[INFO][INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0[INFO][INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS. . .使用 Browser 測試測試 USER 不能存取 /users (只有admin才可以查看所有使用者)使用 user 登入沒處理登入後頁面, 出現 Error Page, 不用擔心沒事修改 URL http://localhost:8088/api/users , Enter (查看所有使用者)權限不足導致請求失敗有關HTTP 回應狀態碼可參看以下網址https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Reference/Status打http://localhost:8088/logout 登出改使用 Admin 登入修改 URL http://localhost:8088/api/users , Enter (查看所有使用者)測試資料來源 users 資料表不是 admin, user。因為用於測試,使用 InMemoryUserDetailsManager建立帳號與密碼並儲存於記憶體中。查看 WebSecurityConfig文章到此完結。希望都有所得。謝謝祝妳好運
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

wordpress 电台网站中国建设企业银行怎么登录

音频分离技术实战指南:用AI重塑音乐创作边界 【免费下载链接】ultimatevocalremovergui 使用深度神经网络的声音消除器的图形用户界面。 项目地址: https://gitcode.com/GitHub_Trending/ul/ultimatevocalremovergui 在音乐创作的数字化浪潮中,音…

张小明 2025/12/26 22:19:42 网站建设

手机网站建设的背景wordpress无法调用主题布局和图片

响应式动画革命:用声明式编程实现毫秒级数据流同步 【免费下载链接】lottie-ios airbnb/lottie-ios: Lottie-ios 是一个用于 iOS 平台的动画库,可以将 Adobe After Effects 动画导出成 iOS 应用程序,具有高性能,易用性和扩展性强的…

张小明 2026/1/9 9:46:08 网站建设

网站建设的基本过程包括学建设网站首页

macOS Mail应用:全面自定义指南 1. 更换默认邮件客户端 在macOS Mojave系统中,默认邮件客户端是Mail应用。若你想使用其他邮件客户端,可按以下步骤操作: 1. 打开Mail偏好设置面板,选择“Mail > Preferences…” 或使用快捷键 command + , 。 2. 若“General”图标…

张小明 2025/12/25 19:11:13 网站建设

百度做网站怎么样恢复118网址之家

第一章:VSCode Azure QDK 故障排查的认知基石 在量子计算开发环境中,VSCode 结合 Azure Quantum Development Kit(QDK)为开发者提供了高效的编程体验。然而,环境配置复杂、依赖项繁多等因素常导致运行异常。掌握故障排…

张小明 2025/12/28 0:28:14 网站建设

协会网站建设必要性动易网站后台管理系统

手把手教你用 Keil5 搭出工业级实时控制系统:从零到稳定运行的完整路径你有没有遇到过这样的场景?电机控制时转速忽快忽慢,PID 调了半天还是震荡;ADC 采样数据跳得像心电图,查不出原因;最要命的是&#xff…

张小明 2025/12/27 23:30:47 网站建设

网站开发工作流程wordpress添加百度地图

M-Robots OS:中国首个开源鸿蒙机器人操作系统 基本介绍 M-Robots OS是由深圳开鸿数字产业发展有限公司(深开鸿)于2025年4月9日正式发布的全国首个基于开源鸿蒙(OpenHarmony)的分布式异构多机协同机器人操作系统。该系统已在2025年7月24日正式开源,由开放…

张小明 2026/1/7 13:24:33 网站建设