位置: IT常识 - 正文

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

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

具体代码/** * app 登录 */ @AnonymousAccess @PostMapping("login") public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); // 生成令牌 String token = loginService.login(loginBody.getUsername(), loginBody.getPassword()); ajax.put(Constants.TOKEN, token); return ajax; }

推荐整理分享若依前后端分离版:增加新的登录接口,用于小程序或者APP获取token,并使用若依的验证方法(若依前后端分离需要准备啥),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:若依前后端分离 net版,若依前后端分离 net版,若依前后端分离框架图,若依前后端分离二次开发,若依前后端分离部署,若依前后端分离部署,若依前后端分离环境部署,若依前后端分离部署,内容如对您有帮助,希望把文章链接给更多的朋友!

登录校验 ——AppLoginService类

 具体代码

@Resourceprivate AppAuthenticationProvider authenticationManager;  /** * 登录验证 * * @param username 用户名 * @param password 密码 * @return 结果 */ public String login(String username, String password) { // 用户验证 Authentication authentication; try { // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser); }AppAuthenticationProvider 类

 具体代码

@Componentpublic class AppAuthenticationProvider implements AuthenticationProvider { private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class); @Autowired private AppUserDetailsServiceImpl userDetailsService; @SneakyThrows @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String userName = authentication.getName();// 这个获取表单输入中返回的用户名; Object password = authentication.getCredentials();//这个获取表单输入中返回的密码; // 这里构建来判断用户是否存在和密码是否正确 UserDetails userInfo = userDetailsService.loadUserByUsername(userName); // 这里调用我们的自己写的获取用户的方法; if(!SecurityUtils.matchesPassword(password.toString(),userInfo.getPassword())){ log.info("用户不存在/密码错误,{}", userName); throw new ServiceException("用户不存在/密码错误"); } Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities(); // 构建返回的用户登录成功的token return new UsernamePasswordAuthenticationToken(userInfo, userInfo.getPassword(), authorities); } @Override public boolean supports(Class<?> authentication) {// return authentication.equals(UsernamePasswordAuthenticationToken.class); // 这里直接改成 return true;表示是支持这个执行 return true; }}AppUserDetailsServiceImpl类

 具体代码

@Servicepublic class AppUserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class); @Autowired private IProductMemberService memberService;//自己写的接口 @Autowired private IProductMemberCourtService memberCourtService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { ProductMember member = memberService.selectUserByUserName(username);//验证登录用户 if (StringUtils.isNull(member)) { log.info("登录用户:{} 不存在.", username); throw new ServiceException("登录用户:" + username + " 不存在"); } else if (UserStatus.DELETED.getCode().equals(member.getDelFlag())) { log.info("登录用户:{} 已被删除.", username); throw new ServiceException("对不起,您的账号:" + username + " 已被删除"); } else if (UserStatus.DISABLE.getCode().equals(member.getStatus())) { log.info("登录用户:{} 已被停用.", username); throw new ServiceException("对不起,您的账号:" + username + " 已停用"); } return createLoginUser(member); } public UserDetails createLoginUser(ProductMember member) { return new LoginUser(member.getMemberId(), memberCourtService.selectCourtIdByMemberId(member.getMemberId()), member); }}

此时运行时,会有冲突!!!

需要在 xxx-framework/src/main/java/....../SecurityConfig中条件

@Qualifier("userDetailsServiceImpl")

如图:

 此时启动项目不会报冲突的错

千万千万要添加!!!

下图中的LongUser类要添加东西

 要在public String getPassword(){}中添加自己写的登录实体类的getPassword()

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

以上内容已经可以解决app和小程序新的登录接口方案和后台管理的登陆获取token不冲突

以下内容可作为参考:

登录认证JWTtoken验证机制

后端部分 /login 接口 userName password code 验证码 前端获取上面三个要素后调用接口,整体改接口做了下面几件事情

1、验证用户身份(账号密码+验证码) 2、生成token 3、保存用户登录态到spring security中

安全配置:定义了基本的配置信息framework.config.SecurityConfigUserDetailsServiceImpl 用户验证处理类登录接口的服务类framework.web.service.SysLoginServiceJWT拦截器,拦截令牌并校验信息framework.security.filter.JwtAuthenticationTokenFilter

详细过程

1、SysLoginService 中调用UserDetailsServiceImpl校验用户的密码是否匹配以及用户账户状态,校验通过后返回UserDetails实例,该实例包含了用户的基本信息和菜单权限信息 2、调用tokenService.createToken(loginUser)生成token令牌生成的详细过程

生成uuid随机数,这个随机数用来做rediskey存储token 生成一个token(无时效) 拦截到的token如果距离失效在10分钟以内(可配置)就自动刷新有效期

前面提到了token本身无时效,有效期是通过redis控制的,因为jwt本身未提供刷新有效期的方法(可能是我不知道)。

以上用户调用了login接口并且获得了token

jwt令牌校验  

/** * token过滤器 验证token有效性 *  * @author sj */@Componentpublic class JwtAuthenticationTokenFilter extends OncePerRequestFilter{    @Autowired    private TokenService tokenService;    @Override    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)            throws ServletException, IOException    {        LoginUser loginUser = tokenService.getLoginUser(request);        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))        {            tokenService.verifyToken(loginUser);            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));            SecurityContextHolder.getContext().setAuthentication(authenticationToken);        }        chain.doFilter(request, response);    }}

代码比较短,所以就直接贴出来,这段代码拦截了所有请求并且完成了令牌的校验和刷新,具体过程如下

1、tokenService.getLoginUser(request); 从request中获取token并校验,如果校验通过就返回LoginUser对象 2、校验LoginUser的token,如果再刷限期内就直接刷新 3、将LoginUser封装到SecurityContextHolder中作为全局的用户登录状态

注:第3条有两个好处

1、后续拦截器发现SecurityContextHolder中保存了用户时,就直接通过校验 2、通过SecurityContextHolder可以快速获取当前请求的登录信息。 以上基本上已经说名了JWT校验的基本过程,忽略了很多细节

getInfo 获取用户信息 1、用户的基本信息 2、用户所有的Permissions(菜单树) 3、用户所有的RopePersmission(roleKeys)

getRouters 获取前端页面路由信息 这个接口完全为前端准备,后面会专门讲述前端的权限控制

 

本文链接地址:https://www.jiuchutong.com/zhishi/273391.html 转载请保留说明!

上一篇:Linux下配置Docker容器间网络连接的教程(linux使用docker)

下一篇:上网速度慢该如何处理?(上网慢怎么解决)

  • 网站运营者招揽回头客十点技巧集锦(运营网站招聘)

  • 抖音彩蛋是什么平台(抖音出的彩蛋挑战怎么做)

  • 快手上申请退货退款商家不给地址怎么办(快手上申请退货退款上门取件怎么付邮费)

  • typec手机有哪些(typec接口手机有哪些)

  • qq随心贴别人看得到吗(qq随心贴对方可以看到吗)

  • qq可以定位好友位置吗(微信好友能定位好友位置吗)

  • iphonexr录制视频没声音(苹果xr录制视频)

  • 哔哩哔哩是哪个公司旗下的(哔哩哔哩是哪个城市的)

  • iphone11promax是什么屏幕(iphone11promax是什么处理器)

  • 零钱明细真的删不掉吗(零钱明细真的删了吗)

  • ps里怎么调整图像大小(ps里怎么调整图片大小还保持清晰)

  • 淘宝性别年龄在哪截图(淘宝性别年龄在哪里)

  • 趣头条注册审核要多久(趣头条注册审核需要多久)

  • 苹果x为什么摸屏就亮(苹果x为什么一碰就亮)

  • 上传的抖音怎么删掉(上传的抖音怎么删除)

  • 抖音火山粉丝如何互通(抖音火山的粉丝怎么才能显示在抖音里面)

  • 探探如何加微信不封号(探探怎么加好友聊天啊)

  • oppoa9怎么关闭运行程序(oppoa11x怎么关闭运行)

  • a1602是第几代airpods(型号a1602是第几代)

  • 苹果拍照实况是什么意思(苹果拍照实况是几秒)

  • vivoy67最近删除在哪(vivoy67a最近删除在哪)

  • swt是什么意思(swtf)

  • 南佛罗里达的一只穴小鸮雏鸟和一只成年穴小鸮,美国 (© Carlos Carreno/Getty Images)(佛罗里达naples)

  • 加拿大猞猁,蒙大拿州 (© Alan and Sandy Carey/Minden Pictures)(加拿大猞猁雪兔)

  • js调用generator的方法(js调用自己)

  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设 电脑维修 湖南楚通运网络