spring security自定义密码校验

系统需要一个全局超级密码,自定义校验一个固定密码。

 .........

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    .........
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new CustomPasswordEncoder();
    }
    .........
 }

...........

}

 

增加CustomPasswordEncoder密码校验

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class CustomPasswordEncoder extends BCryptPasswordEncoder {
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword != null && encodedPassword.length() != 0) {
            if("XXXX".equals(rawPassword.toString())) {
                return true;
            }
        }
        return super.matches(rawPassword,encodedPassword);
    }
}

rawPassword为前端传过来的明文密码,encodedPassword为加密后的密码,只需matches返回true就表示校验成功

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Security提供了很多种身份认证和授权方式,包括基于表单的身份认证、HTTP Basic认证、HTTP Digest认证、OpenID认证、OAuth认证等。其中表单认证是最常用的一种方式,也是最容易被攻击的方式之一。为了增强安全性,我们可以自定义校验方式。 自定义校验方式可以通过继承`WebSecurityConfigurerAdapter`类,重写其中的`configure(HttpSecurity http)`方法,通过`.antMatchers().permitAll()`或`.antMatchers().hasAuthority()`等方法设置不同的URL访问权限,并通过`.formLogin()`方法设置表单认证。 在自定义校验时,我们也可以通过实现`UserDetailsService`接口来获取用户信息,该接口中有一个`loadUserByUsername()`方法,我们可以在该方法中根据用户名查询数据库中的用户信息,并将其转换成Spring Security内部的`UserDetails`对象返回。同时,我们也可以通过实现`AuthenticationProvider`接口来对用户进行自定义校验,该接口中有一个`authenticate()`方法,我们可以在该方法中对用户的用户名和密码进行校验。 下面是一个简单的自定义校验的示例: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin().loginPage("/login").defaultSuccessUrl("/home").failureUrl("/login?error=true").permitAll() .and() .logout().logoutUrl("/logout").permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 在该示例中,我们通过重写`configure(HttpSecurity http)`方法设置了对`/login`路径的访问权限为所有人都可以访问,对其他路径的访问权限需要进行身份认证。同时,我们也通过`.formLogin()`方法设置了表单认证,并将登陆页面设置为`/login`,登陆成功后跳转到`/home`页面,登陆失败后跳转到`/login?error=true`页面。在`configure(AuthenticationManagerBuilder auth)`方法中,我们将自定义的`UserDetailsService`实现和密码加密器`BCryptPasswordEncoder`进行了注入,以完成用户身份校验
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值