loadUserByUsername方法下用户信息成功查出来了,而且也返回出来了一个LoginUser,LoginUser实体也有,user封装进去了
。还有security版本为2.5.14
但是,下面代码貌似没有执行,没通过??,debug时authenticationManager中确实拿到了用户的值
@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();
}
}