目录
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 { @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } //配置基于内存认证 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin") .password("123").roles("ADMIN","USER") .and() .withUser("zhao") .password("123").roles("USER"); } //配置HttpSecurity @Override protected 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() {//登录成功 @Override public 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() {//登录失败 @Override public 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() {//退出 @Override public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) { } }) .logoutSuccessHandler(new LogoutSuccessHandler() {//退出成功 @Override public 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 怎么基于数据库认证!