Spring Security 身份验证处理抛异常 重复执行?

Spring Security
loadUserByUsername(String username)方法抛出异常后重新执行了,且username为空

有点不解,为什么会多次执行

具体的代码如下

自定义的登录接口 Controller如下

@RestController

public class UserLoginController {

@Autowired

UserLoginService userLoginService;

@RequestMapping(method = RequestMethod.POST, value = "/doLogin")

public ResponseEntity userLogin(@Validated @RequestBody User user) {

Result result = userLoginService.userLogin(user);

return ResponseEntity.ok(result);

}

}

实现类业务逻辑如下:

    @Autowired

AuthenticationManager authenticationManager;

@Autowired

RedisUtil redisUtil;

@Override

public Result userLogin(User user) {

UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken

(user.getUsername(), user.getPassword());

Authentication authenticate = authenticationManager.authenticate(authenticationToken);

if (ObjectUtils.isEmpty(authenticate)) {

throw new RuntimeException("账号密码错误,请检查账号密码");

}

LoginUser user1 = (LoginUser) authenticate.getPrincipal();

String uid = user1.getUser().getUid().toString();

String token = JwtUtil.createJWT(uid);

redisUtil.set("login:" + uid, user1);

Map map = new HashMap();

map.put("token", token);

return ResultResponse.getSuccessandMessage(map, "登录成功");

}

}

UserDetailService具体逻辑代码如下 这里加了个变量num来打印执行的次数

  private static int num = 0;

@Override

public UserDetails loadUserByUsername(String username) {

System.out.println(++num);

User user;

String regex = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";

//邮箱登录逻辑

if (username.matches(regex)) {

Email email = emailService.getByEmail(username);

if (ObjectUtils.isEmpty(email)) {

System.out.println("邮箱不存在抛出异常——");

throw new ValidateCodeException("邮箱不存在");

} else {

if (email.getCheck() != 1) {

throw new ValidateCodeException("邮箱未启用");

}

user = userService.findByUId(email.getUid());

}

} else {

user = userService.getUserByname(username);

}

if (ObjectUtils.isEmpty(user)) {

System.out.println("账号不存在 抛出异常");

throw new RuntimeException("用户不存在");

}

return new LoginUser(user);

}

具体配置如下

@Override

protected void configure(HttpSecurity http) throws Exception {

//关闭csrf防护

http.csrf().disable();

//开启表单验证

http.formLogin().failureHandler(myAuthenticationFailedHandler).and()

.authorizeRequests().antMatchers("/doLogin").permitAll().

anyRequest().authenticated();

}

当用户不存在时抛出异常时,发现重复调用loadUserByUsername方法


回答:

会执行两次有意思,有demo没,搞个demo出来看看

以上是 Spring Security 身份验证处理抛异常 重复执行? 的全部内容, 来源链接: utcz.com/p/944897.html

回到顶部