iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring Security 密码验证动态加盐的验证处理方法
  • 416
分享到

Spring Security 密码验证动态加盐的验证处理方法

2024-04-02 19:04:59 416人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

本文个人博客地址:https://www.leafage.top/posts/detail/21697I2R 最近几天在改造项目,需要将gateway整合security在一起进行认

本文个人博客地址:https://www.leafage.top/posts/detail/21697I2R

最近几天在改造项目,需要将gateway整合security在一起进行认证和鉴权,之前gateway和auth是两个服务,auth是shiro写的一个,一个filter和一个配置,内容很简单,生成token,验证token,没有其他的安全检查,然后让对项目进行重构。

先是要整合gateway和shiro,然而因为gateway是WEBflux,而shiro-spring是webmvc,所以没搞成功,如果有做过并成功的,请告诉我如何进行整合,非常感谢。

那整合security呢,因为spring cloud gateway基于webflux,所以网上很多教程是用不了的,webflux的配置会有一些变化,具体看如下代码示例:


import io.leafage.gateway.api.HypervisorApi;
import io.leafage.gateway.handler.ServerFailureHandler;
import io.leafage.gateway.handler.ServerSuccesshandler;
import io.leafage.gateway.service.JdbcReactiveUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.Http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPassWordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.authentication.loGout.HttpStatusReturningServerLogoutSuccessHandler;
import org.springframework.security.web.server.csrf.CookieServerCsrfTokenRepository;


@EnableWebFluxSecurity
public class ServerSecurityConfiguration {

    // 用于获取远程数据
    private final HypervisorApi hypervisorApi;

    public ServerSecurityConfiguration(HypervisorApi hypervisorApi) {
        this.hypervisorApi = hypervisorApi;
    }

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

    
    @Bean
    public ReactiveUserDetailsService userDetailsService() {
        // 自定义的ReactiveUserDetails 实现
        return new JdbcReactiveUserDetailsService(hypervisorApi);
    }

    
    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.fORMLogin(f -> f.authenticationSuccessHandler(authenticationSuccessHandler())
                .authenticationFailureHandler(authenticationFailureHandler()))
                .logout(l -> l.logoutSuccessHandler(new HttpStatusReturningServerLogoutSuccessHandler()))
                .csrf(c -> c.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
                .authorizeExchange(a -> a.pathMatchers(HttpMethod.OPTIONS).permitAll()
                        .anyExchange().authenticated())
                .exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)));
        return http.build();
    }

    
    private ServerAuthenticationSuccessHandler authenticationSuccessHandler() {
        return new ServerSuccessHandler();
    }

    
    private ServerAuthenticationFailureHandler authenticationFailureHandler() {
        return new ServerFailureHandler();
    }

}

上面的示例代码,是我开源项目中的一段,一般的配置就如上面写的,就可以使用了,但是由于我们之前的项目中的是shiro,然后有一个自定义的加密解密的逻辑。

首先说明一下情况,之前那一套加密(前端MD5,不加盐,然后数据库存储的是加盐后的数据和对应的盐(每个账号一个),要登录比较之前对密码要获取动态的盐,然后加盐进行MD5,再进行对比,但是在配置的时候是没法获取某一用户的盐值)

所以上面的一版配置是没法通过验证的,必须在验证之前,给请求的密码混合该账号对应的盐进行二次加密后在对比,但是这里就有问题了:

  1. security 框架提供的几个加密\解密工具没有MD5的方式;
  2. security 配置加密\解密方式的时候,无法填入动态的账号的加密盐;

对于第一个问题还好处理,解决方式是:自定义加密\解密方式,然后注入到配置类中,示例如下:


import cn.hutool.crypto.SecureUtil;
import com.ichinae.imis.gateway.utils.SaltUtil;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.security.MessageDigest;


public class MD5PasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence charSequence) {
        String salt = SaltUtil.generateSalt();
        return SecureUtil.md5(SecureUtil.md5(charSequence.toString()) + salt);
    }

    @Override
    public boolean matches(CharSequence charSequence, String encodedPassword) {
        byte[] expectedBytes = bytesUtf8(charSequence.toString());
        byte[] actualBytes = bytesUtf8(charSequence.toString());
        return MessageDigest.isEqual(expectedBytes, actualBytes);
    }

    private static byte[] bytesUtf8(String s) {
        // need to check if Utf8.encode() runs in constant time (probably not).
        // This may leak length of string.
        return (s != null) ? Utf8.encode(s) : null;
    }

}

第二个问题的解决办法,找了很多资料,也没有找到,后来查看security的源码发现,可以在UserDetailsService接口的findByUsername()方法中,在返回UserDetails实现的时候,使用默认实现User的UserBuilder内部类来解决这个问题,因为UserBuilder类中有一个属性,passwordEncoder属性,它是Fucntion<String, String>类型的,默认实现是 password -> password,即对密码不做任何处理,先看下它的源码:

1623227092.png

再看下解决问题之前的findByUsername()方法:


@Service
public class UserDetailsServiceImpl implements ReactiveUserDetailsService {

    @Resource
    private RemoteService remoteService;

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        return remoteService.getUser(username).map(userBO -> User.builder()
                .username(username)
                .password(userBO.getPassword())
                .authorities(grantedAuthorities(userBO.getAuthorities()))
                .build());
    }

    private Set<GrantedAuthority> grantedAuthorities(Set<String> authorities) {
        return authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
    }

}

那找到了问题的解决方法,就来改代码了,如下所示:

新增一个代码处理方法


private Function<String, String> passwordEncoder(String salt) {
    return rawPassword -> SecureUtil.md5(rawPassword + salt);
}

然后添加builder链


@Service
public class UserDetailsServiceImpl implements ReactiveUserDetailsService {

    @Resource
    private RemoteService remoteService;

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        return remoteService.getUser(username).map(userBO -> User.builder()
                .passwordEncoder(passwordEncoder(userBO.getSalt())) //在这里设置动态的盐
                .username(username)
                .password(userBO.getPassword())
                .authorities(grantedAuthorities(userBO.getAuthorities()))
                .build());
    }

    private Set<GrantedAuthority> grantedAuthorities(Set<String> authorities) {
        return authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
    }

    private Function<String, String> passwordEncoder(String salt) {
        return rawPassword -> SecureUtil.md5(rawPassword + salt);
    }
}

然后跑一下代码,请求登录接口,就登陆成功了。

1623227505(1).png

以上就是Spring Security 密码验证动态加盐的验证处理的详细内容,更多关于Spring Security密码验证的资料请关注编程网其它相关文章!

--结束END--

本文标题: Spring Security 密码验证动态加盐的验证处理方法

本文链接: https://www.lsjlt.com/news/128047.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作