spring-security遇到的问题

loadUserByUsername方法下用户信息成功查出来了,而且也返回出来了一个LoginUser,LoginUser实体也有,user封装进去了
。还有security版本为2.5.14

img


但是,下面代码貌似没有执行,没通过??,debug时authenticationManager中确实拿到了用户的值

img


@Slf4j
@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    /**
     * 登录
     *
     * @param user
     * @return ResponseResult.okResult(blogUserLoginVo)
     */
    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
//        if (Objects.isNull(authentication)) {
//            throw new RuntimeException("用户名或密码错误");
//        }

        // 认证成功,从Authentication获取LoginUser
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        log.info("loginUser:{}",loginUser);

        String userId = loginUser.getUser().getId().toString();
        // 生成token
        String jwt = JwtUtil.createJWT(userId);
        // 存入redis
        redisCache.setCacheObject(LOGIN_KEY + userId, loginUser);
        //把token响应给前端
//        HashMap<String, String> map = new HashMap<>();
//        map.put("token", jwt);
//        return new ResponseResult(CODE_200, "登陆成功", map);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt, userInfoVo);

        log.info("当前登录用户:{}",blogUserLoginVo);
        
        return ResponseResult.okResult(blogUserLoginVo);
    }
}

这是配置

package com.roydon.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/login").anonymous()
                // 除上面外的所有请求全部不需要认证即可访问
                .anyRequest().permitAll();

        http.logout().disable();
        //允许跨域
        http.cors();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}


img

问题已经解决,问题出在用 BCrypt 密码加密测试那一步,由于马虎直接new了加密处理器,没有使用bean里面注入的,导致数据库密码加密校验时对不上,security里没有过验证,所以没有报错,只给了个log提示密码加密方式有误,详情转向:


这个可以帮到你

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^