@Configuration public class SecurityConfig {// 创建 BCryptPasswordEncoder 注入容器,密码加密 @Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}// 登录时调用一次AuthenticationManager.authenticate 执行一次校验// authenticate @Beanpublic AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {return config.getAuthenticationManager();}// 登录请求放行配置// SecurityFilterChain 一个表示安全过滤器链的对象 @Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception{// 关闭csrf机制http.csrf(csrf -> csrf.disable());/*** 配置请求拦截方式,* requestMatchers 表示某个请求不需要进行身份校验* authorizeHttpRequests 配置请求的授权规则,.anyRequest().authenticated() 表示任何请求都需要经过身份验证* permitAll 随意访问*/http.authorizeHttpRequests(auth -> auth.requestMatchers("/user/login").permitAll().anyRequest().authenticated());return http.build();} }
service
@Service public class LoginServiceImpl implements LoginService {@Autowiredprivate AuthenticationManager authenticationManager;@Overridepublic String login(SysUserinfo sysUserinfo) {//用户认证// 1. 封装 authentication 对象UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUserinfo.getUsername(),sysUserinfo.getPassword());// 2. 进行校验Authentication authentication = authenticationManager.authenticate(authenticationToken);//认证没有通过if (Objects.isNull(authentication)){throw new RuntimeException("登录失败");}//认证通过,获取放入的用户信息LoginUser loginUser = (LoginUser) authentication.getPrincipal();// 生成JWT,使用fastjson方法,把对象转为字符串String jsonString = JSON.toJSONString(loginUser);// 调用jwt工具类,生成jwt令牌String jwt = JwtUtil.createJWT(jsonString, null);return jwt;} }
controller
@RestController @RequestMapping("/user") public class LoginController {@Autowiredprivate LoginService loginService;@PostMapping("/login")public ResultVO login(@RequestBody SysUserinfo sysUserinfo) {String jwt = loginService.login(sysUserinfo);if (StringUtils.hasLength(jwt)){// ResultVO 自定义响应类return ResultVO.success(jwt);}return ResultVO.fail("err");}}
测试
使用postman,点击body,选用json格式,输入用户名密码