栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

Spring Security入门(自定义配置)

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Security入门(自定义配置)

1 引入依赖

	org.springframework.boot
	spring-boot-starter-security

2 配置
@Configuration
public class BrowserSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
 http.formLogin()  // 表单验证
     .and()
     .authorizeRequests()
     .anyRequest()
     .authenticated(); // 认证拦截所有请求
    }
}

3 自定义用户认证逻辑
  • 1.自定义用户信息获取逻辑

实现UserDetailService接口

public class DefaultUserDetailService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
 log.info("登录用户:{}",username);
 User user = getUser(username);
 return user;
    }

    private User getUser(String username) {
	    // 用户获取逻辑,通常情况下从数据库获取
      
    }
}
  • 2.自定义用户密码认证逻辑
    配置默认的加密算法实现,也可以自己实现PasswordEncoder接口实现自己的加密逻辑,需要注册,此加密逻辑需要和用户注册逻辑保持一致
    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder(){
 log.info("load default password encoder by BCrypt");
 return new BCryptPasswordEncoder();
    }
    1. 自定义登录页面
    • 3.1 自定义登录页
      在resources目录下创建static目录,并在static目录下创建default-login.html页面



    
    
    
    
    
    登录

    
    
    
    






这个是从bootstrap官网copy过来的简单登录页。配置form表单的提交地址为:/authentication/form,并分别配置两个input表单项的name为’username’和’password’。

  • 3.2 添加配置信息
@Configuration
public class BrowserSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
 http.formLogin()  // 表单验证
  .loginPage("/default-login.html")
  .loginProcessingUrl("/authentication/form") // 配置表单提交请求,此请求会被UsernamePasswordAuthenticationFilter 拦截处理
  .and()
  .authorizeRequests()
  .antMatchers("/default-login.html").permitAll() 
  .anyRequest()
  .authenticated()  // 认证拦截所有请求
  .and()
  .csrf().disable(); // 关闭跨站请求拦截
    }
}
    1. 自定义登录成功配置
      SpringSecurity默认登录成功后回跳转到之前访问的路径(页面),自定义登录成功之后的逻辑需要如下配置
    • 4.1 编写一个类实现AuthenticationSuccessHandler接口
@Slf4j
@Component
public class DefaultAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
 log.info("登录成功");
 response.setContentType("application/json;charset=UTF-8");
 // 登录成功以JSON格式返回数据信息
 response.getWriter().write(objectMapper.writevalueAsString(authentication));
    }
}
  • 4.2 配置Handler,告知SpringSecurity以自定义的Handler处理登录成功逻辑
@Configuration
public class BrowserSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties properties;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
 http.formLogin()  // 表单验证
  .loginPage("/authentication/require")
  .loginProcessingUrl("/authentication/form") // 配置表单提交请求,此请求会被UsernamePasswordAuthenticationFilter 拦截处理
  .successHandler(authenticationSuccessHandler)  // 登录成功配置
  .and()
  .authorizeRequests()
  .antMatchers("/authentication/require",properties.getBrowser().getLoginPage()).permitAll() 
  .anyRequest()
  .authenticated()  // 认证拦截所有请求
  .and()
  .csrf().disable(); // 关闭跨站请求拦截
    }
}
    1. 自定义登录失败配置
      登录失败配置流程与登录成功配置一致,继承AuthenticationFailureHandler接口实现自己相应的登录失败逻辑即可
@Slf4j
@Component
public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
 log.info("登录失败");
 response.setContentType("application/json;charset=UTF-8");
 // 登录成功以JSON格式返回数据信息
 response.getWriter().write(objectMapper.writevalueAsString(exception.getMessage()));
    }
}

添加配置

    @Override
    protected void configure(HttpSecurity http) throws Exception {
 http.formLogin()  // 表单验证
  .loginPage("/authentication/require")
  .loginProcessingUrl("/authentication/form") // 配置表单提交请求,此请求会被UsernamePasswordAuthenticationFilter 拦截处理
  .successHandler(authenticationSuccessHandler)  // 登录成功配置
  .failureHandler(authenticationFailureHandler)  // 登录失败配置
  .and()
  .authorizeRequests()
  .antMatchers("/authentication/require",properties.getBrowser().getLoginPage()).permitAll() // 放行登录页
  .anyRequest()
  .authenticated()  // 认证拦截所有请求
  .and()
  .csrf().disable(); // 关闭跨站请求拦截
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235154.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号