spring boot 整合security
生活随笔
收集整理的這篇文章主要介紹了
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring boot 整合redis实
- 下一篇: springboo整合security—