日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring boot 整合security

發布時間:2025/1/21 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot 整合security 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

1、基于內存認證

2、基于數據庫認證


1、基于內存認證

1)、配置pom文件

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId> </dependency>

?

2)、自定義WebSecurityConfigurerAdapter?

@Configuration public class WebImSecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance();}//配置基于內存認證@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password("123").roles("ADMIN","USER").and().withUser("zhao").password("123").roles("USER");}//配置HttpSecurity@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')").antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')").anyRequest().authenticated().and().formLogin().loginProcessingUrl("/login").usernameParameter("name").passwordParameter("passwd").successHandler(new AuthenticationSuccessHandler() {//登錄成功@Overridepublic void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {Object principal = authentication.getPrincipal();resp.setContentType("application/json;charset=utf-8");PrintWriter out = resp.getWriter();resp.setStatus(200);Map<String,Object> map = new HashMap<>();map.put("status",200);map.put("msg",principal);ObjectMapper om = new ObjectMapper();out.write(om.writeValueAsString(map));out.flush();out.close();}}).failureHandler(new AuthenticationFailureHandler() {//登錄失敗@Overridepublic void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");PrintWriter out = resp.getWriter();resp.setStatus(401);Map<String,Object> map = new HashMap<>();map.put("status",401);if(e instanceof LockedException) {map.put("msg","賬戶被鎖定,登錄失敗!");}else if (e instanceof BadCredentialsException) {map.put("msg","賬戶密碼輸入錯誤,登錄失敗!");}else if (e instanceof BadCredentialsException) {map.put("msg","賬戶密碼輸入錯誤,登錄失敗!");}else if (e instanceof DisabledException) {map.put("msg","賬戶被禁用,登錄失敗!");}else if (e instanceof AccountExpiredException) {map.put("msg","賬戶已過期,登錄失敗!");}else if (e instanceof CredentialsExpiredException) {map.put("msg","密碼已過期,登錄失敗!");}else {map.put("msg","登錄失敗");}ObjectMapper om = new ObjectMapper();out.write(om.writeValueAsString(map));out.flush();out.close();}}).and().logout().logoutUrl("/logout").clearAuthentication(true).invalidateHttpSession(true).addLogoutHandler(new LogoutHandler() {//退出@Overridepublic void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {}}).logoutSuccessHandler(new LogoutSuccessHandler() {//退出成功@Overridepublic void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {httpServletResponse.sendRedirect("/login_page");}}).permitAll().and().csrf().disable();} }

?3)、密碼加密

@Bean public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder(); }

?4)、方法安全使用?@EnableGlobalMethodSecurity

prePostEnabled = true 會解鎖@PreAuthorize 和@PostAuthorize兩個注解

以上是基于內存認證的spring security,下節我們繼續講spring security 怎么基于數據庫認證!?

總結

以上是生活随笔為你收集整理的spring boot 整合security的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。