@Configuration public class SecurityConfig { // 创建 BCryptPasswordEncoder 注入容器,密码加密 @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // 登录时调用一次AuthenticationManager.authenticate 执行一次校验 // authenticate @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { return config.getAuthenticationManager(); } // 登录请求放行配置 // SecurityFilterChain 一个表示安全过滤器链的对象 @Bean public 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 { @Autowired private AuthenticationManager authenticationManager; @Override public 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 { @Autowired private 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格式,输入用户名密码
标签:return,请求,jwt,SpringSecurity,---,放行,sysUserinfo,login,public From: https://www.cnblogs.com/wangdch/p/18438036