首页 文章 精选 留言 我的

精选列表

搜索[javascript框架],共10000篇文章
优秀的个人博客,低调大师

前后端分离架构使用shiro框架进行登录的两种实现

方法一:重写FormAuthenticationFilter 原理: 假设在shiro.xml中配置了 /** = authc 而默认authc对应org.apache.shiro.web.filter.authc.FormAuthenticationFilter过滤器 则表示所有路径都被此过滤器拦截 当未登录请求被拦截,会调用FormAuthenticationFilter.onAccessDeny(): 如果请求的是loginUrl,则调用AuthenticatingFilter.executeLogin() 如果不是,则使request重定向到loginUrl,并return false; AuthenticatingFilter.executeLogin(): 调用subject.login(token) 如果登录成功,则调用onLoginSuccess() 失败则调用onLoginFailure() AuthenticatingFilter.onLoginSuccess(): return true; AuthenticatingFilter.onLoginFailure(): return false; subject.login(token): 最终会调用realm的doGetAuthenticationInfo 思路 重写默认的FormAuthenticationFilter, 在onAccessDeny()方法中: 如果请求的是loginUrl,则调用AuthenticatingFilter.executeLogin() 如果不是,则返回json,提示“未登录,无法访问该地址” @Override protectedbooleanonAccessDenied(ServletRequestrequest,ServletResponseresponse)throwsException{ if(this.isLoginRequest(request,response)){ if(this.isLoginSubmission(request,response)){ if(log.isTraceEnabled()){ log.trace("Loginsubmissiondetected.Attemptingtoexecutelogin."); } returnthis.executeLogin(request,response); }else{ if(log.isTraceEnabled()){ log.trace("Loginpageview."); } returntrue; } }else{ if(log.isTraceEnabled()){ log.trace("Attemptingtoaccessapathwhichrequiresauthentication.ForwardingtotheAuthenticationurl["+this.getLoginUrl()+"]"); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriterout=response.getWriter(); ServerResponseserverResponse=ServerResponse.createByErrorMessage("未登录,无法访问该地址"); Gsongson=GsonFactory.getGson(); Strings=gson.toJson(serverResponse); out.println(s); out.flush(); out.close(); returnfalse; } } 由于AuthenticatingFilter.executeLogin()会调用onLoginSuccess()和onLoginFailure()方法 所以我们重写两个方法,前者返回登录成功的json,并把当前用户放入session;后者返回登录失败的json @Override protectedbooleanonLoginSuccess(AuthenticationTokentoken,Subjectsubject,ServletRequestrequest,ServletResponseresponse)throwsException{ response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriterout=null; try{ out=response.getWriter(); }catch(IOExceptione1){ e1.printStackTrace(); } HttpSessionsession=((HttpServletRequest)request).getSession(); Useruser=userMapper.selectByUserName(token.getPrincipal().toString()); session.setAttribute(Const.CURRENT_USER,user); ServerResponseserverResponse=ServerResponse.createBySuccessMsg("登录成功"); Gsongson=GsonFactory.getGson(); Strings=gson.toJson(serverResponse); out.println(s); out.flush(); out.close(); returntrue; } @Override protectedbooleanonLoginFailure(AuthenticationTokentoken,AuthenticationExceptione,ServletRequestrequest,ServletResponseresponse){ response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriterout=null; try{ out=response.getWriter(); }catch(IOExceptione1){ e1.printStackTrace(); } ServerResponseserverResponse=ServerResponse.createByErrorMessage("登录失败"); Gsongson=GsonFactory.getGson(); Strings=gson.toJson(serverResponse); out.println(s); out.flush(); out.close(); returnfalse; } } 最后配置shiro.xml将authc对应的默认的FormAuthenticationFilter,替换成我们的MyAuthenticationFilter <beanid="shiroFilter"class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <propertyname="securityManager"ref="securityManager"/> <propertyname="loginUrl"value="/user/login.do"/> <propertyname="unauthorizedUrl"value="/user/unauthorized_err"/> <propertyname="filters"> <map> <entrykey="authc"value-ref="myAuthenticationFilter"/> </map> </property> <propertyname="filterChainDefinitions"> <value> /user/login_err.do=anon /user/unauthorized_err.do=anon /**=authc </value> </property> </bean> <beanid="myAuthenticationFilter"class="com.mmall.shiro.filter.MyAuthenticationFilter"/> 方法二:使用PassThruAuthenticationFilter代替FormAuthenticationFilter 原理: org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter源码: publicclassPassThruAuthenticationFilterextendsAuthenticationFilter{ publicPassThruAuthenticationFilter(){ } protectedbooleanonAccessDenied(ServletRequestrequest,ServletResponseresponse)throwsException{ if(this.isLoginRequest(request,response)){ returntrue; }else{ this.saveRequestAndRedirectToLogin(request,response); returnfalse; } } } 官方文档: An authentication filter that redirects the user to the login page when they are trying to access a protected resource. However, if the user is trying to access the login page, the filter lets the request pass through to the application code. The difference between this filter and the FormAuthenticationFilter is that on a login submission (by default an HTTP POST to the login URL), the FormAuthenticationFilter filter attempts to automatically authenticate the user by passing the username and password request parameter values to Subject.login(usernamePasswordToken) directly. Conversely, this controller always passes all requests to the loginUrl through, both GETs and POSTs. This is useful in cases where the developer wants to write their own login behavior, which should include a call to Subject.login(AuthenticationToken) at some point. For example, if the developer has their own custom MVC login controller or validator, this PassThruAuthenticationFilter may be appropriate. 我们继承PassThruAuthenticationFilter并重写onAccessDenied方法,和redirectToLogin方法 publicclassMyPassThruAuthenticationFilterextendsPassThruAuthenticationFilter{ privateStringloginErrUrl="/"; publicvoidsetLoginErrUrl(StringloginErrUrl){ this.loginErrUrl=loginErrUrl; } @Override protectedbooleanonAccessDenied(ServletRequestrequest,ServletResponseresponse)throwsException{ if(this.isLoginRequest(request,response)){ returntrue; }else{ this.saveRequestAndRedirectToLogin(request,response); returnfalse; } } //重写redirectToLogin方法是因为saveRequestAndRedirectToLogin方法会调用它,而原始的redirectToLogin方法会使得请求重定向到loginUrl @Override protectedvoidredirectToLogin(ServletRequestrequest,ServletResponseresponse)throwsIOException{ WebUtils.issueRedirect(request,response,loginErrUrl); } } 首先修改shiro.xml , 将authc默认对应的FormAuthenticationFilter修改为MyPassThruAuthenticationFilter <beanid="shiroFilter"class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <propertyname="securityManager"ref="securityManager"/> <propertyname="loginUrl"value="/user/login.do"/> <propertyname="unauthorizedUrl"value="/user/unauthorized_err"/> <propertyname="filters"> <map> <entrykey="authc"> <beanclass="com.mmall.shiro.filter.MyPassThruAuthenticationFilter"> <propertyname="loginErrUrl"value="/user/login_err.do"/><!--注意这里的loginErrUrl与上面的loginUrl的区别--> </bean> </entry> </map> </property> <propertyname="filterChainDefinitions"> <value> /=anon /user/login_err.do=anon /user/unauthorized_err.do=anon /user/logout.do=logout /**=authc </value> </property> </bean> 然后修改loginUrl对应的Contoller的方法,在其中要调用subject.login()完成shiro的认证 //UserController中:结合shiro,使用PassThruAuthenticationFilter的登录,需要调用subject.login()完成shiro的认证 @RequestMapping(value="login.do",method=RequestMethod.POST) @ResponseBody publicServerResponselogin(@RequestBodyUseruser,HttpSessionsession){ Subjectsubject=SecurityUtils.getSubject(); UsernamePasswordTokentoken=newUsernamePasswordToken(user.getUsername(),user.getPassword()); //ServerResponseserverResponse=iUserService.login(user.getUsername(),user.getPassword()); try{ /**subject.login(token)提交申请,验证能不能通过,也就是交给shiro。这里会回调reaml(或自定义的realm)里的一个方法 protectedAuthenticationInfodoGetAuthenticationInfo()*/ subject.login(token); }catch(AuthenticationExceptione){//验证身份失败 returnServerResponse.createByErrorMessage("登陆客户身份失败!"); } /**Shiro验证后,跳转到此处,这里判断验证是否通过*/ if(subject.isAuthenticated()){//验证身份通过 session.setAttribute(Const.CURRENT_USER,subject.getPrincipal()); returnServerResponse.createBySuccessMsg("登录成功"); }else{ returnServerResponse.createByErrorMessage("登陆客户身份失败!"); } } 而loginErrUrl对应的方法则返回Json提示未登录: @RequestMapping(value="login_err.do",method=RequestMethod.GET) @ResponseBody publicServerResponselogin_error(){ returnServerResponse.createByErrorMessage("用户未登录"); }

优秀的个人博客,低调大师

2.5配置的框架浅析「深入浅出ASP.NET Core系列」

希望给你3-5分钟的碎片化学习,可能是坐地铁、等公交,积少成多,水滴石穿,谢谢关注。 配置的使用流程 //第一步.初始化Builder var builder = new ConfigurationBuilder(); //第二步.将Source添加到Builder builder.AddJsonFile("student.json", false, true); //builder.AddInMemoryCollection(dict) //builder.AddXmlFile("/path/tmp.xml") //第三步.调用Build var configuration = builder.Build(); //第四步.使用 configurationRoot["key"] 第二步,在将Source添加到Builder的时候,内部做了哪些事情呢? 初始化对应的Source对象,比如Json文件配置源对象: JsonConfigurationSource sr=new JsonConfigurationSource() { Path = "settings.json", } 第三步,Build时候在内部,生成Provider对象,一个Source对应一个Provider,最后返回ConfigurationRoot,该Root包含所有的Provider。 foreach(var source in sources) { var provider = source.Build(); providers.add(provider); } return new ConfigurationRoot(providers); 第四步,在使用的时候,通过Provider去找到相应的key,返回key值。 foreach(var provider in providers.Reverse()) { string value; provider.TryGet(key,out value); return value; } 通过以上步骤,我们可以看到配置Source和配置Provider是关键的两个要点。 内部类关系图 如果所示,如果要自己定义配置,必须实现接口IConfigurationSource,并在内部实现一个对应的Provider,该Provider必须继承ConfigurationProvider抽象类,并在Provider读取配置,对配置进行维护、同步、热更新。具体如何定制,在后续进阶和高级进行讲解。 我是.NET架构师张飞洪,入行10年有余,人不堪其忧,吾不改其乐,谢谢您关注我的头条号。

优秀的个人博客,低调大师

使用Python-Flask框架开发Web网站系列课程(一)构建项目

版权声明:如需转载,请注明转载地址。 https://blog.csdn.net/oJohnny123/article/details/81907475 前言 使用IDE:PyCharm 操作系统: Mac Python版本:3.6 我的邮箱:51263921@qq.com 交流群: 372430835 请注意,既然要学习开发,那么要注意以下几个问题。 1、开发语言版本不一样,尤其是Python,会导致同一段代码压根跑不起来的情况。所以请保证版本一致。 2、操作系统不一样,自然也会有区分,但是Mac环境和Linux环境基本还是比较相近,贴合生产,所以使用Mac作为演示环境。但与Window的差别也不会很大。 3、简易使用一样的IDE工具,但是不强求。 4、本课代码的github地址在页面最底。 构建项目 一、创建虚拟环境venv 1、从前我很皮,不喜欢创建这东西,都是直接用系统环境的Python,后来项目一多,呵呵哒,这个项目用的Django1.9,那个项目又用Django2.0。得,乱套了。所以,请养成良好的习惯,使用venv大人。 2、通过PyCharm添加虚拟环境venv ,Windows在File->Settings,Mac在PyCharm->Preferences, 打开页面后,按下图配置。Add local Python Interpreter。最后 Apply -> OK。 二、安装flask 2.1 看下图,在Terminal控件里面执行 pip install flask==1.0.2 。 2.2 然后我们将这个阶段的依赖包记录下来,使用的命令为: pip freeze>requirement.txt 2.3 我们开始构建目录结构 我们需要一个目录放前端的代码(frontend),一个放后端代码(backend),一个放公共方法代码(utils),一个放配置文件(config)。 我们在根目录myproject里面右键New->Python Package,用这个创建包。按上面括号里面的名字建。 2.4 构建后端代码 2.4.1 添加config.py,在/myproject/config下。 这东西就是我们网站以后所有配置存放的地方啦,其中Config放的是各个环境都一致的配置,ProdConfig放的是生产环境的配置,SitConfig存放SIT环境配置,其他类比。 最后的一行,代表config = SitConfig() 当前获取的是SIT环境的配置。 全路径为:/myproject/config/config.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2017/11/8. """ import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class Config(object): """Base config class.""" # 版本 VERSION = 'beta 0.1' # 项目名称 PROJECTNAME = 'myproject' # 端口 PORT = 10101 SECRET_KEY = '1234567890!@#$%^&*()' class ProdConfig(Config): """Production config class.""" # 是否开启调试 DEBUG = False # 主机ip地址 HOST = '0.0.0.0' class SitConfig(Config): """Development config class.""" # Open the DEBUG # 是否开启调试 DEBUG = True # 主机ip地址 HOST = '127.0.0.1' class DevConfig(Config): pass # Default using Config settings, you can write if/else for different env config = SitConfig() 2.4.2 修改/myproject/backend/__init__.py 这个是未来整个后端的入口文件,具体内容如下: 全路径:/myproject/backend/__init__.py 具体代码如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午2:41. """ from flask import Flask from config.config import config def create_app(): #初始化项目实例 app = Flask(__name__) app.secret_key = app.config['SECRET_KEY'] #导入配置项 app.config.from_object(config) # 钩子 在请求执行之前 @app.before_request def before_request(): print('hi') return app 2.4.3 在根目录添加后端项目管理文件 manage.py 要先补一个模块 pip install Flask-Script==2.0.6 添加一个空的python脚本,manage.py 全路径:/myproject/manage.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午3:40. """ from flask_script import Manager, Server from backend import create_app app = create_app() app.debug = app.config["DEBUG"] # 获取根目录config.py的配置项 host = app.config["HOST"] port = app.config["PORT"] # Init manager object via app object manager = Manager(app) # Create a new commands: server # This command will be run the Flask development_env server manager.add_command("runserver", Server(host=host,port=port,threaded=True)) @manager.shell def make_shell_context(): """Create a python CLI. return: Default import object type: `Dict` """ # 确保有导入 Flask app object,否则启动的 CLI 上下文中仍然没有 app 对象 return dict(app=app) if __name__ == '__main__': manager.run() 2.4.4 添加视图文件,views.py 我们访问一个链接,要显示或者返回什么东西,就是在这里处理后返回给浏览器或者接口的。 全路径:/myproject/backend/views.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午3:51. """ from flask import Blueprint,jsonify #账户的蓝图 访问http://host:port/account 这个链接的子链接,都会跳到这里 account = Blueprint('/account', __name__) # 访问http://host:port/account/test 这个链接,就会跳到这里 @account.route('/test') #上面的链接,绑定的就是这个方法,我们给浏览器或者接口请求 一个json格式的返回 def test(): return jsonify({'code':0,'content':'hi flask'}) 2.4.5 添加路由文件,urls.py 全路径:/myproject/backend/urls.py 内容为: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午3:50. """ from backend.views import account # 蓝图注册 def register(app): app.register_blueprint(account, url_prefix='/account', strict_slashes=False) 2.4.6 最后一步,添加内容到入口文件__init__.py 我们添加了两行代码 from backend.urls import register register(app) 用来干啥的呢,是要把我们路由蓝图的对应关系注册到我们的 flask实例里面。和我们之前把配置文件注册到app.config里面是一个道理。 路径:/myproject/backend/__init__.py 内容如下: #!/usr/bin/python # -*- coding: UTF-8 -*- """ Created by liaoyangyang1 on 2018/8/21 下午2:41. """ from flask import Flask from config.config import config from backend.urls import register def create_app(): #初始化项目实例 app = Flask(__name__) app.secret_key = app.config['SECRET_KEY'] #导入配置项 app.config.from_object(config) # 注册路由 register(app) # 钩子 在请求执行之前 @app.before_request def before_request(): print('hi') return app 三、启动项目 3.1 点击根目录的manage.py,右键执行 执行方式如图1,然后我们会发现还是缺了参数,请看图2、图3,通过edit configurations,在弹出框中的 Parameters 里面输入runserver。Apply后OK。 现在再次点击根目录的manage.py,右键执行。 * Serving Flask app "backend" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:10101/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 110-176-230 现在,我们在浏览器输入 http://127.0.0.1:10101/account/test 图1: 图2 图3 四、GITHUB地址 https://github.com/lyy8510a/myproject/releases/tag/v1

优秀的个人博客,低调大师

直播系统开发,完整的系统框架架构,打造完美的直播系统

直播系统开发、直播平台开发中怎样做才能快速积攒人气流量、得到用户的青睐呢? 一、要做到明确自己的是行业市场定位,要明白自己直播平台的行业市场方向和针对的人群,才能够对直播系统开发进行系统化的梳理和一个大构架的概念。直播市场走到今天,靠颜值撑起一片天已经很难实现了,观众审美口味如此挑剔的今天这样的做法很慢在直播这个行业走下去,因此要找到自己熟知的有能力做好的的某一行业的某个特色,做精致。行业的不同,对于直播系统开发中的功能就有所不同,在主播和观众端的操作上也就有不同的需求。所以,明白自己的定位,才能够迈出开需求发最重要的第一步。 二、在运营过程中市场推广和宣传,要做到巧妙贴合。前期运营中最主要的就是宣传和推广要打开自己的平台知名度,让用户知道和记住,进而使用你的软件,而好的推广策略会让你事半功倍。之后。,就可以通过本身在直播APP或平台积攒的人气进行宣传和自身的宣传下,才能够达到最理想的效果,所以在运营这一块也要十分重视。 三、就是开发的核心问题直播APP功能,有了行业市场方向后。就可以使用或者开发相应的直播APP软件的功能,做到吸引用户长久发展,让直播间人气不断一直火爆下去,并且还要考虑到商业化的发展。直播系统开发早已发展成熟,搭建直播平台也逐渐成为一种趋势,各位如果对于搭建个人直播平台或是直播源码上有更好地看法和意见,或者您需要搭建直播平台,欢迎互动交流。

优秀的个人博客,低调大师

python+pytest单元测试框架之生成各种格式测试报告

前面讲到使用pytest执行单个、多个或指定的测试用例。接下来讲解下通过运行测试用例,怎么来生成不同格式的测试报告 首先,创建test_calss.py 测试用例文件,这里以测试该文件为例 #coding:utf-8 class TestClass(): def test_one(self): x = "this" assert "h" in x def test_two(self): x = "hello" assert x == "hi" def test_three(self): x = "world" assert x != "worl" 一、生成ResultLog文件 1.在CMD中切换到该测试用例路径下,执行指令:py.test test_class.py --resultlog=./log.txt (其中./log.txt为生成log的路径,也可写成py.test test_class.py --resultlog=E:/log.txt)。并早当前路径下生成log.txt文件,打开文件,内容如下 执行结果1 二、生成JunitXML文件 1.在CMD中切换到该测试用例路径下,执行指令:py.test test_class.py --junitxml=./log.xml (其中./log.xml为生成log的路径,也可写成py.test test_class.py --junitxml=E:/log.xml)。并在当前路径下生成log.xml文件,打开文件,内容如下 执行结果2 三、创建测试用例的URL 1.在CMD中切换到该测试用例路径下,执行指令:py.test test_class.py --pastehbin=all 会在最后一行生成一个网址 执行结果3-1 2.把网址(https://bpaste.net/show/5e60a2096e54)复制到浏览器打开可以看到测试用例执行的全部结果 执行结果3-2 3.指定显示测试结果为FAIL,输入指令:py.test test_class.py --pastebin=failed 执行结果3-3 四、生成HTML测试报告 1.要想生成html格式的测试报告,首先的下载安装pytest-html插件,执行如下指令:pip install pytest-html 如下图 安装pytest-html插件 2.在CMD中切换到该测试用例路径下,执行指令:py.test test_class.py --html=./report.html (其中./report.html为生成log的路径,也可写成py.test test_class.py --html=E:/report.html)。并在当前路径下生成report.html文件,打开文件,内容如下 执行结果4-1 3.双击打开生成的report.html文档,可以看到如下效果 执行结果4-2 其中,红色框框内的选项可以自行选择是否显示。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码