1987WEB视界-分享互联网热门产品和行业

您现在的位置是:首页 > WEB开发 > 正文

WEB开发

若依前后端分离版:增加新的登录接口,用于小程序或者APP获取token,并使用若依的验证方法

1987web2024-03-25WEB开发286
若依前后端分离版:增加新的登录接口,用于小程序或者APP获取token,并使用若依的验证方法LoginController

若依前后端分离版:增加新的登录接口,用于小程序或者APP获取token,并使用若依的验证方法
LoginController

具体代码/*** app 登录*/@AnonymousAccess@PostMapping("login")publicAjaxResultlogin(@RequestBodyLoginBodyloginBody){AjaxResultajax=AjaxResult.success();// 生成令牌Stringtoken=loginService.login(loginBody.getUsername(),loginBody.getPassword());ajax.put(Constants.TOKEN,token);returnajax;}

登录校验 ——AppLoginService类

具体代码

@ResourceprivateAppAuthenticationProviderauthenticationManager;/*** 登录验证** @param username 用户名* @param password 密码* @return 结果*/publicStringlogin(Stringusername,Stringpassword){// 用户验证Authenticationauthentication;try{// 该方法会去调用UserDetailsServiceImpl.loadUserByUsernameauthentication=authenticationManager.authenticate(newUsernamePasswordAuthenticationToken(username,password));}catch(Exceptione){if(einstanceofBadCredentialsException){AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,Constants.LOGIN_FAIL,MessageUtils.message("user.password.not.match")));thrownewUserPasswordNotMatchException();}else{AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,Constants.LOGIN_FAIL,e.getMessage()));thrownewServiceException(e.getMessage());}}AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,Constants.LOGIN_SUCCESS,MessageUtils.message("user.login.success")));LoginUserloginUser=(LoginUser)authentication.getPrincipal();recordLoginInfo(loginUser.getUserId());// 生成tokenreturntokenService.createToken(loginUser);}AppAuthenticationProvider

具体代码

@ComponentpublicclassAppAuthenticationProviderimplementsAuthenticationProvider{privatestaticfinalLoggerlog=LoggerFactory.getLogger(UserDetailsServiceImpl.class);@AutowiredprivateAppUserDetailsServiceImpluserDetailsService;@SneakyThrows@OverridepublicAuthenticationauthenticate(Authenticationauthentication)throwsAuthenticationException{StringuserName=authentication.getName();// 这个获取表单输入中返回的用户名;Objectpassword=authentication.getCredentials();//这个获取表单输入中返回的密码;// 这里构建来判断用户是否存在和密码是否正确UserDetailsuserInfo=userDetailsService.loadUserByUsername(userName);// 这里调用我们的自己写的获取用户的方法;if(!SecurityUtils.matchesPassword(password.toString(),userInfo.getPassword())){log.info("用户不存在/密码错误,{}",userName);thrownewServiceException("用户不存在/密码错误");}Collection