项目场景:
在若依项目中需要做一个在线沟通的聊天功能,所以在若依的脚手架中集成了websocket。
问题描述
在若依中集成websocket后进行通信,但是在开启websocket的时候会报错“websocket connection to 'ws://localhost' failed:”。找了很多解决方法都无法解决,包括:修改vue.config.js中的配置,修改跨域的配置问题。
let socketurl = "ws://localhost:8080/imserver/" + username;
if (socket != null) {
socket.close();
socket = null;
}
// 开启一个websocket服务
socket = new websocket(socketurl);
原因分析:
使用若依的基本都会对他的源码有所了解,若依对访问后端接口的限制是很多的,除了一些特殊访问,所有请求都需要鉴权访问,如下代码摘自若依前后端分离“ruoyi-framework/src/main/java/com/ruoyi/framework/config/securityconfig.java”
/**
* anyrequest | 匹配所有请求路径
* access | springel表达式结果为true时可以访问
* anonymous | 匿名可以访问
* denyall | 用户不能访问
* fullyauthenticated | 用户完全认证可以访问(非remember-me下自动登录)
* hasanyauthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
* hasanyrole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
* hasauthority | 如果有参数,参数表示权限,则其权限可以访问
* hasipaddress | 如果有参数,参数表示ip地址,如果用户ip和参数匹配,则可以访问
* hasrole | 如果有参数,参数表示角色,则其角色可以访问
* permitall | 用户可以任意访问
* rememberme | 允许通过remember-me登录的用户访问
* authenticated | 用户登录后可访问
*/
@override
protected void configure(httpsecurity httpsecurity) throws exception
{
// 注解标记允许匿名访问的url
expressionurlauthorizationconfigurer<httpsecurity>.expressionintercepturlregistry registry = httpsecurity.authorizerequests();
permitallurl.geturls().foreach(url -> registry.antmatchers(url).permitall());
httpsecurity
// csrf禁用,因为不使用session
.csrf().disable()
// 禁用http响应标头
.headers().cachecontrol().disable().and()
// 认证失败处理类
.exceptionhandling().authenticationentrypoint(unauthorizedhandler).and()
// 基于token,所以不需要session
.sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.stateless).and()
// 过滤请求
.authorizerequests()
// 对于登录login 注册register 验证码captchaimage 允许匿名访问
.antmatchers("/login", "/register", "/captchaimage").permitall()
// 静态资源,可匿名访问
.antmatchers(httpmethod.get, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitall()
.antmatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitall()
// 除上面外的所有请求全部需要鉴权认证
.anyrequest().authenticated()
.and()
.headers().frameoptions().disable();
// 添加logout filter
httpsecurity.logout().logouturl("/logout").logoutsuccesshandler(logoutsuccesshandler);
// 添加jwt filter
httpsecurity.addfilterbefore(authenticationtokenfilter, usernamepasswordauthenticationfilter.class);
// 添加cors filter
httpsecurity.addfilterbefore(corsfilter, jwtauthenticationtokenfilter.class);
httpsecurity.addfilterbefore(corsfilter, logoutfilter.class);
}
解决方案:
可以根据自己的需要进行配置,比如项目是自己练习使用,可以将“
.anyrequest().authenticated()
”直接注释掉,就可以将所有鉴权认证步骤忽略,而上面的问题就迎刃而解了,或者将静态资源写入antmatchers内,也可以解决该问题。
发表评论