前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[Express]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Python
...g Regular Expressions in Python: Advanced Techniques and Real-world Use Cases》(掌握Python中的正则表达式:高级技巧与实际应用场景)引起了广泛关注。该文不仅深入剖析了Python正则表达式的复杂模式匹配、条件语句和环视等高级特性,还结合当下大数据处理、网络爬虫及数据分析等领域的需求,提供了丰富的实战案例。 例如,文中详述了如何利用正则表达式高效解析JSON和XML数据结构,这对于提升数据分析效率至关重要。此外,作者还分享了在抓取网页内容时,如何精准提取特定标签内的信息,展示了正则表达式在Web scraping任务中的关键作用。同时,文章讨论了正则表达式在文本清洗过程中过滤特殊字符、标准化日期格式以及识别电子邮件、URL等常见字符串模式的实践方法。 对于希望更深入理解并有效应用Python正则表达式的开发者来说,这篇深度解读与实战指导相结合的文章无疑是极具时效性和针对性的延伸阅读材料,它将帮助读者应对更为复杂的文本处理挑战,提高开发效率,并助力实现项目目标。
2023-01-25 14:35:48
282
键盘勇士
Python
...g Regular Expressions》一书,该书以其丰富的示例和深入浅出的解析,被广大开发者誉为正则表达式领域的经典之作。通过研读此类资料,您不仅能深化对Python中正则表达式的掌握,还能将其应用于更多跨语言、跨平台的场景,从而提升自身在文本挖掘、数据分析等领域的专业技能。
2023-08-02 16:27:28
304
代码侠
NodeJS
...ipt const express = require('express'); const app = express(); // 使用自定义错误处理中间件 app.use(errorHandler); // 其他中间件和路由... app.listen(3000, () => { console.log('Server started on port 3000'); }); 在这个例子中,我们首先导入了Express库,并创建了一个新的Express应用。然后,我们使用app.use()方法将我们的错误处理中间件添加到应用中。最后,我们启动了服务器。 五、总结 在Node.js中,中间件是处理错误的强大工具。你知道吗,我们可以通过设计一个定制化的错误处理小工具,来更灵活、精准地把控程序出错时的应对方式。这样一来,无论遇到啥样的错误状况,咱们的应用程序都能够稳稳当当地给出正确的反馈,妥妥地解决问题。当然啦,这只是错误处理小小的一部分而已,真实的错误处理可能需要更费心思的步骤,比如记下错误日记啊,给相关人员发送错误消息提醒什么的。不管咋说,要成为一个真正牛掰的Node.js开发者,领悟和掌握错误处理的核心原理可是必不可少的关键一步。
2023-12-03 08:58:21
90
繁华落尽-t
NodeJS
...graphql和express-graphql。我们可以使用npm来安装这两个包: css npm install graphql express-graphql 然后,我们可以创建一个简单的Express应用,来处理GraphQL查询。以下是一个基本的示例: javascript const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const app = express(); app.use('/graphql', graphqlHTTP({ schema: require('./schema.js'), graphiql: true, })); app.listen(3000, () => { console.log('Server is running on port 3000'); }); 在这个示例中,我们创建了一个新的Express应用,并定义了一个路由/graphql,该路由将使用graphqlHTTP中间件来处理GraphQL查询。咱们还需要搞个名叫schema.js的文件,这个文件里头装着我们整个GraphQL模式的“秘籍”。此外,我们还启用了GraphiQL UI,这是一个交互式GraphQL查询工具。 让我们看看这个schema.js文件的内容: typescript const { gql } = require('graphql'); const typeDefs = gql type Query { users: [User] user(id: ID!): User } type User { id: ID! name: String! email: String! } ; module.exports = typeDefs; 在这个文件中,我们定义了两种类型的查询:users和user。users查询将返回所有的用户,而user查询则返回特定的用户。我们还定义了两种类型的实体:User。User实体具有id、name和email三个字段。 现在,我们可以在浏览器中打开http://localhost:3000/graphql,并尝试执行一些查询。例如,我们可以使用以下查询来获取所有用户的列表: json { users { id name email } } 如果我们想要获取特定用户的信息,我们可以使用以下查询: json { user(id:"1") { id name email } } 以上就是如何使用NodeJS进行数据查询的方法。用上GraphQL,咱们就能更溜地获取和管理数据啦,而且更能给用户带来超赞的体验!如果你还没有尝试过GraphQL,我强烈建议你去试一试!
2023-06-06 09:02:21
55
红尘漫步-t
NodeJS
...许多高质量开源项目如Express.js、React等都遵循这一原则,确保了组件的可复用性和维护性。 此外,对于大型项目,合理的模块划分和依赖管理是至关重要的,工具如Lerna可以帮助管理和优化具有多个相互依赖包的Monorepo项目结构,从而减少require错误发生的概率,并提高团队协作效率。 同时,为了预防和解决模块加载中的常见问题,开发者可以学习并应用模块绑定、模块缓存以及动态导入等高级特性,这些不仅能优化性能,还能增强代码的健壮性。综上所述,与时俱进地掌握NodeJS模块系统的最新动态与最佳实践,将助力我们编写出更加稳定、高效的JavaScript应用程序。
2023-12-17 19:06:53
58
梦幻星空-t
VUE
...此外,一些开源库如express-jwt和jsonwebtoken,为开发者提供了便捷的工具来处理JWT相关的操作,从而减少因不当实现而导致的安全风险。 另外,随着微服务架构的普及,跨域资源共享(CORS)成为另一个需要关注的领域。确保正确配置CORS策略对于防止未授权访问至关重要。例如,最近Netflix公开分享了其在构建大规模微服务架构时如何处理CORS的最佳实践,其中包括详细的配置指南和常见陷阱的避免方法。 最后,持续集成/持续部署(CI/CD)流水线中的自动化安全检查也变得越来越重要。通过将安全扫描工具集成到CI/CD流程中,可以及早发现并修复潜在的安全漏洞。例如,GitHub Actions和GitLab CI等平台提供了丰富的插件和模板,帮助开发者轻松实现这一目标。 总之,通过采用最新的安全技术和最佳实践,我们可以显著提升Vue项目以及其他Web应用的安全性,从而为用户提供更加可靠的服务。
2025-01-23 15:55:50
29
灵动之光
NodeJS
...速度和服务器性能。 express-graphql , 这是一个Node.js中间件,用于将GraphQL服务集成到基于Express框架构建的应用程序中。在文章示例代码中,express-graphql库被用来创建一个简单的GraphQL HTTP服务器,使得客户端可以通过HTTP协议向服务器发起GraphQL查询请求,并接收结构化的JSON响应结果。 JWT(JSON Web Tokens) , 虽然在文章中JWT仅作为权限控制的一种潜在解决方案被简要提到,但它在现代Web应用的安全认证方面扮演着重要角色。JWT是一种开放标准(RFC 7519),用于安全地在各方之间传输声明。在GraphQL API中结合JWT,可以在resolver执行前验证请求的权限,确保只有经过身份验证和授权的用户才能访问特定数据。
2024-02-08 11:34:34
65
落叶归根
PHP
...el(基于PHP)和Express.js(基于Node.js)正在尝试弥合两者之间的界限,通过整合各种工具和服务,使得开发者能够更便捷地实现PHP与Node.js的混合部署与通信。此外,随着微服务架构和Serverless计算模型的普及,PHP和Node.js可以分别应用于更适合的服务组件中,形成互补优势,共同构建高性能、可扩展的分布式系统。 综上所述,在实际项目开发中,了解并结合PHP和Node.js的最新发展动态,将有助于开发者更加灵活高效地利用两种技术的优势,应对不断变化的市场需求和技术挑战。而持续关注相关的技术社区、博客文章及行业报告,也是提升Web开发技能,紧跟时代步伐的重要途径。
2024-01-21 08:08:12
62
昨夜星辰昨夜风_t
NodeJS
...起,因此名声在外。而Express呢,就像是在这个强大运行环境上搭建的一座便利桥梁,它提供了一整套超实用的Web应用框架工具箱,让你开发API时既高效又省心,维护起来更是轻松加愉快!本文将围绕如何使用Express进行安全的API开发展开,让我们一起踏上这场数据传输的优雅之旅。 二、了解Express 1. Express简介 Express 是一个轻量级、灵活的Node.js web应用框架,它简化了HTTP请求与响应的处理流程,并为我们提供了丰富的中间件(Middleware)来扩展其功能。比如,我们可以借助express.static()这个小工具,来帮我们处理和分发静态文件。又或者,我们可以使出body-parser这个神通广大的中间件,它能轻松解析请求体里藏着的JSON数据或者URL编码过的那些信息。 javascript const express = require('express'); const app = express(); // 静态文件目录 app.use(express.static('public')); // 解析JSON请求体 app.use(bodyParser.json()); 2. 安装和配置基本路由 在开始API开发之前,我们需要安装Express和其他必要的依赖库。通过npm(Node Package Manager),我们可以轻松完成这个任务: bash $ npm install express body-parser cors helmet 然后,在应用程序初始化阶段,我们要引入这些模块并设置相应的中间件: javascript const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const helmet = require('helmet'); const app = express(); // 设置CORS策略 app.use(cors()); // 使用Helmet增强安全性 app.use(helmet()); // JSON解析器 app.use(bodyParser.json()); // 指定API资源路径 app.use('/api', apiRouter); // 假设apiRouter是定义了多个API路由的模块 // 启动服务器 const port = 3000; app.listen(port, () => { console.log(Server is running on http://localhost:${port}); }); 三、实现基本的安全措施 1. Content Security Policy (CSP) 使用Helmet中间件,我们能够轻松地启用CSP以限制加载源,防止跨站脚本攻击(XSS)等恶意行为。在配置中添加自定义CSP策略: javascript app.use(helmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'unsafe-inline'"], styleSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", 'data:', "https:"], fontSrc: ["'self'", "https:"], connect-src: ["'self'", "https:"] } })); 2. CORS策略 我们之前已经设置了允许跨域访问,但为了确保安全,可以根据需求调整允许的源: javascript app.use(cors({ origin: ['http://example.com', 'https://other-site.com'], // 允许来自这两个域名的跨域访问 credentials: true, // 如果需要发送cookies,请开启此选项 exposedHeaders: ['X-Custom-Header'] // 可以暴露特定的自定义头部给客户端 })); 3. 防止CSRF攻击 在处理POST、PUT等涉及用户数据变更的操作时,可以考虑集成csurf中间件以验证跨站点请求伪造(CSRF)令牌: bash $ npm install csurf javascript const csurf = require('csurf'); // 配置CSRF保护 const csrf = csurf(); app.use(csurf({ cookie: true })); // 将CSRF令牌存储到cookie中 // 处理登录API POST请求 app.post('/login', csrf(), (req, res) => { const { email, password, _csrfToken } = req.body; // 注意获取CSRF token if (validateCredentials(email, password)) { // 登录成功 } else { res.status(401).json({ error: 'Invalid credentials' }); } }); 四、总结与展望 在使用Express进行API开发时,确保安全性至关重要。通过合理的CSP、CORS策略、CSRF防护以及利用其他如JWT(Json Web Tokens)的身份验证方法,我们的API不仅能更好地服务于前端应用,还能有效地抵御各类常见的网络攻击,确保数据传输的安全性。 当然,随着业务的发展和技术的进步,我们会面临更多安全挑战和新的解决方案。Node.js和它身后的生态系统,最厉害的地方就是够灵活、够扩展。这就意味着,无论我们面对多复杂的场景,总能像哆啦A梦找百宝箱一样,轻松找到适合的工具和方法来应对。所以,对咱们这些API开发者来说,要想把Web服务做得既安全又牛逼,就得不断学习、紧跟技术潮流,时刻关注行业的新鲜动态。这样一来,咱就能打造出更棒、更靠谱的Web服务啦!
2024-02-13 10:50:50
79
烟雨江南-t
NodeJS
...用的框架和工具。就像Express.js、Koa.js这些服务端框架,还有Gulp.js、Webpack.js这些自动化构建工具,真是应有尽有。它们的存在,就是为了让我们能够更轻松、更快速地搭建起自己的应用程序,简直像是给开发者们插上了翅膀一样,特别给力! 在本篇文章中,我们将探讨如何使用 Node.js 进行云服务开发。首先,咱们得先摸清楚 Node.js 在云服务这个领域里头是怎么被用起来的,接下来再给大家伙儿逐一介绍一下时下热门的云服务提供商,还会附带上他们在 Node.js 开发这块的一些实用教程,让大家能更好地掌握上手。 一、Node.js 在云服务中的应用场景 1. 实时通信应用 Node.js 的事件驱动和非阻塞 I/O 模型使其非常适合实时通信应用。比如,我们完全可以借助 Socket.IO 这个神器,搭建出像实时聊天室、在线一起编辑文档这些超级实用的应用程序。就像是你和朋友们能即时聊天的小天地,或者大家一起同时修改同一份文档的神奇工具,这些都是 Socket.IO 能帮我们实现的好玩又强大的功能。 2. 后端服务 由于 Node.js 具有高并发性和异步编程的能力,因此它可以作为后端服务的核心引擎。比如,咱们可以拿 Express.js 这个框架来搭建一个飞快的 RESTful API,要不就用 Koa.js 来整一个更轻巧灵活的服务器,随你喜欢。 3. 数据库中间件 Node.js 可以作为数据库中间件,与数据库交互并实现数据的读取、存储和更新等功能。比如,我们可以拿起 Mongoose ORM 这个工具箱,它能帮我们牵线搭桥连上 MongoDB 数据库。然后,我们就能够借助它提供的查询语句,像玩魔术一样对数据进行各种操作,插入、删除、修改,随心所欲。 二、常用的云服务提供商及其 Node.js 开发教程 1. AWS AWS 提供了一系列的云服务,包括计算、存储、数据库、安全等等。在 AWS 上,我们可以使用 Lambda 函数来实现无服务器架构,使用 EC2 或 ECS 来部署 Node.js 应用程序。此外,AWS 还提供了丰富的 SDK 和 CLI 工具,方便我们在本地开发和调试应用程序。 2. Google Cloud Platform (GCP) GCP 提供了类似的云服务,包括 Compute Engine、App Engine、Cloud Functions、Cloud SQL 等等。在 GCP(Google Cloud Platform)这个平台上,咱们完全可以利用 Node.js 这门技术来开发应用程序,然后把它们稳稳地部署到 App Engine 上。这样一来,咱们就能更轻松、更方便地管理自家的应用程序,同时还能对它进行全方位的监控,确保一切运行得妥妥当当的。就像是在自家后院种菜一样,从播种(开发)到上架(部署),再到日常照料(管理和监控),全都在掌控之中。 3. Azure Azure 是微软提供的云服务平台,支持多种编程语言和技术栈。在 Azure 上,我们可以使用 Function App 来部署 Node.js 函数,并使用 App Service 来部署完整的 Node.js 应用程序。另外,Azure还准备了一整套超级实用的DevOps工具和服务,这对我们来说可真是个大宝贝,能够帮我们在管理和发布应用程序时更加得心应手,轻松高效。 接下来,我们将详细介绍如何使用 Node.js 在 AWS Lambda 上构建无服务器应用程序。 三、在 AWS Lambda 上使用 Node.js 构建无服务器应用程序 AWS Lambda 是一种无服务器计算服务,可以让开发者无需关心服务器的操作系统、虚拟机配置等问题,只需要专注于编写和上传代码即可。在Lambda这个平台上,咱们能够用Node.js来编写函数,就像变魔术一样把函数和触发器手牵手连起来,这样一来,就能轻松实现自动执行的酷炫效果啦! 以下是使用 Node.js 在 AWS Lambda 上构建无服务器应用程序的基本步骤: Step 1: 创建 AWS 帐户并登录 AWS 控制台 Step 2: 安装 AWS CLI 工具 Step 3: 创建 Lambda 函数 Step 4: 编写 Lambda 函数 Step 5: 配置 Lambda 函数触发器 Step 6: 测试 Lambda 函数 Step 7: 将 Lambda 函数部署到生产环境
2024-01-24 17:58:24
144
青春印记-t
NodeJS
...大的生态系统(比如 Express、Socket.IO 等),简直就是为实时应用量身定制的工具。所以,今天我们就用 Node.js + WebSocket 来做一个简单的实时监控面板,顺便分享一下我的一些心得。 --- 2. 第一步 搭建基础环境 首先,我们需要准备开发环境。Node.js 的安装非常简单,去官网下载对应版本就行。安装完后,用 node -v 和 npm -v 验证是否成功。如果这两个命令都能正常输出版本号,那就说明环境配置好了。 接下来,我们创建项目文件夹,并初始化 npm: bash mkdir real-time-monitor cd real-time-monitor npm init -y 然后安装必要的依赖包。这里我们用到两个核心库:Express 和 ws(WebSocket 库)。Express 是用来搭建 HTTP 服务的,ws 则专门用于 WebSocket 通信。 bash npm install express ws 接下来,我们写一个最基础的 HTTP 服务,确保环境能正常工作: javascript // server.js const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(Server is running on port ${PORT}); }); 保存文件后运行 node server.js,然后在浏览器输入 http://localhost:3000,应该能看到 “Hello World!”。到这里,我们的基本框架已经搭好了,是不是感觉还挺容易的? --- 3. 第二步 引入 WebSocket 现在我们有了一个 HTTP 服务,接下来该让 WebSocket 上场了。WebSocket 的好处就是能在浏览器和服务器之间直接搭起一条“高速公路”,不用老是像发短信那样频繁地丢 HTTP 请求过去,省时又高效!为了方便,我们可以直接用 ws 库来实现。 修改 server.js 文件,添加 WebSocket 相关代码: javascript // server.js const express = require('express'); const WebSocket = require('ws'); const app = express(); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('A client connected!'); // 接收来自客户端的消息 ws.on('message', (message) => { console.log(Received message => ${message}); ws.send(You said: ${message}); }); // 当客户端断开时触发 ws.on('close', () => { console.log('Client disconnected.'); }); }); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(HTTP Server is running on port ${PORT}); }); 这段代码做了几件事: 1. 创建了一个 WebSocket 服务器,监听端口 8080。 2. 当客户端连接时,打印日志并等待消息。 3. 收到消息后,会回传给客户端。 4. 如果客户端断开连接,也会记录日志。 为了让浏览器能连接到 WebSocket 服务器,我们还需要一个简单的 HTML 页面作为客户端入口: html Real-Time Monitor WebSocket Test Send Message 这段 HTML 代码包含了一个简单的聊天界面,用户可以在输入框中输入内容并通过 WebSocket 发送到服务器,同时也能接收到服务器返回的信息。跑完 node server.js 之后,别忘了打开浏览器,去 http://localhost:3000 看一眼,看看它是不是能正常转起来。 --- 4. 第三步 扩展功能——实时监控数据 现在我们的 WebSocket 已经可以正常工作了,但还不能算是一个真正的监控面板。为了让它更实用一点,咱们不妨假装弄点监控数据玩玩,像CPU用得多不多、内存占了百分之多少之类的。 首先,我们需要一个生成随机监控数据的函数: javascript function generateRandomMetrics() { return { cpuUsage: Math.random() 100, memoryUsage: Math.random() 100, diskUsage: Math.random() 100 }; } 然后,在 WebSocket 连接中定时向客户端推送这些数据: javascript wss.on('connection', (ws) => { console.log('A client connected!'); setInterval(() => { const metrics = generateRandomMetrics(); ws.send(JSON.stringify(metrics)); }, 1000); // 每秒发送一次 ws.on('close', () => { console.log('Client disconnected.'); }); }); 客户端需要解析接收到的数据,并动态更新页面上的信息。我们可以稍微改造一下 HTML 和 JavaScript: html CPU Usage: Memory Usage: Disk Usage: javascript socket.onmessage = (event) => { const metrics = JSON.parse(event.data); document.getElementById('cpuProgress').value = metrics.cpuUsage; document.getElementById('memoryProgress').value = metrics.memoryUsage; document.getElementById('diskProgress').value = metrics.diskUsage; const messagesDiv = document.getElementById('messages'); messagesDiv.innerHTML += Metrics updated. ; }; 这样,每秒钟都会从服务器获取一次监控数据,并在页面上以进度条的形式展示出来。是不是很酷? --- 5. 结尾 总结与展望 通过这篇文章,我们从零开始搭建了一个基于 Node.js 和 WebSocket 的实时监控面板。别看它现在功能挺朴素的,但这东西一出手就让人觉得,WebSocket 在实时互动这块儿真的大有可为啊!嘿,听我说!以后啊,你完全可以接着把这个项目捯饬得更酷一些。比如说,弄点新鲜玩意儿当监控指标,让用户用起来更爽,或者直接把它整到真正的生产环境里去,让它发挥大作用! 其实开发的过程就像拼图一样,有时候你会遇到困难,但只要一点点尝试和调整,总会找到答案。希望这篇文章能给你带来灵感,也欢迎你在评论区分享你的想法和经验! 最后,如果你觉得这篇文章对你有帮助,记得点个赞哦!😄 --- 完
2025-05-06 16:24:48
71
清风徐来
转载文章
...mation is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
Python
...Generator Expressions)对列表进行复杂操作,如过滤、映射和压缩数据,从而提升代码可读性和运行效率。文章还介绍了functools模块中的reduce函数,用于对列表元素执行累积操作,如求乘积、求序列中最长连续子序列等。 另外,在实际编程实践中,掌握列表的排序、切片、连接、复制等基本操作同样至关重要。例如,使用sorted()函数或列表的sort()方法对列表进行排序;利用切片技术实现列表的部分提取或替换;通过extend()和+运算符完成列表合并等。这些操作不仅能丰富你对Python列表的理解,更能在日常开发任务中助你事半功倍。 总的来说,深入学习和熟练运用Python列表的各种特性与功能,不仅有助于数据分析和处理,更能提升代码编写质量,使程序更加简洁、高效。同时,关注Python社区的最新动态和最佳实践,将能持续拓展你的编程技能边界,紧跟时代发展步伐。
2023-10-05 18:16:18
359
算法侠
转载文章
...on ? true_expression : false_expression(在Lua中的写法是 a and b or c),它会根据给定的条件判断执行两种不同的结果。如果条件为真,则返回true_expression的结果;如果条件为假,则返回false_expression的结果。在本文的上下文中,Lua使用其特有的逻辑运算符实现了类似三目运算符的功能。 短路求值 , 短路求值是编程语言中逻辑表达式计算的一种策略,当逻辑表达式的最终结果可以通过评估部分表达式就能确定时,程序将不再继续评估剩余的部分。在Lua中,and 和 or 运算符都遵循短路求值原则,对于 a and b or c 的情况,如果 a 为假(即 falsy 值如 nil、false 等),则不会继续计算 b 的值,直接返回 a;如果 a 为真,则返回 b 的值。本文提及的特殊写法 (a and b or c ) 1 正是利用了这一特性来避免 b 为 nil 导致错误返回的情况。 Nil值 , 在Lua编程语言中,nil是一个特殊的值,表示“无”或“不存在”。变量未被赋值、函数没有返回值或者尝试访问表中不存在的键时,都会得到nil。在条件表达式和逻辑运算中,nil被视为假(false)。文章中讨论的问题是,在标准三目运算符形式下,若b为nil,会导致意外地返回c的值,因此提出了一个处理nil值的安全方法,即通过临时创建包含预期值的表来避免此问题的发生。
2023-12-29 14:47:09
241
转载
JSON
...js后端环境中,诸如Express框架支持直接将JSON传递给路由处理器,并内建了中间件来解析JSON请求体。同时,使用诸如axios或fetch这类现代HTTP客户端库,可以更加优雅地发起异步请求并处理返回的JSON数据。 近期,ECMAScript标准也在JSON支持上进行了优化,如引入JSON.stringify()的第三个参数用于定制化序列化过程,以及JSON.parse()可选的reviver函数对反序列化结果进行深度处理。这些新特性的运用能够帮助开发者更精细地控制JSON数据在程序中的流转和表现形式。 总的来说,理解并熟练掌握JSON数据处理已经成为现代全栈开发者的必备技能,持续关注相关技术和最佳实践的发展,能更好地适应快速变化的Web开发环境,提升开发效率和代码质量。
2023-07-24 23:16:09
441
逻辑鬼才
VUE
...层如Node.js的Express框架或GraphQL来处理前后端数据交互,以实现更为安全、可控的数据流管理。例如,通过RESTful API设计,Vue前端可以发起HTTP请求获取MySQL后端处理过的数据,避免直接数据库查询带来的潜在安全风险。 此外,为了更好地优化Vue应用与MySQL数据库的协作效率,社区涌现出诸多优秀实践与工具,如TypeORM、Sequelize等ORM解决方案,使得开发者能够以面向对象的方式来操作MySQL数据库,大大简化了数据库操作代码,并增强了类型安全性。 综上所述,掌握Vue.js与MySQL的实际应用不仅限于基础的连接与查询,还需关注最新技术动态,合理运用中间层架构以及先进的开发工具,才能更好地满足现代Web应用开发的需求。同时,深入理解并遵循最佳实践对于提升系统整体性能和安全性同样至关重要。
2023-11-04 09:39:55
77
数据库专家
NodeJS
...cript var express = require('express'); var cors = require('cors'); var app = express(); app.use(cors()); app.get('/api/data', function(req, res) { res.json({ message: 'Hello World!' }); }); app.listen(3000, function() { console.log('Example app listening on port 3000!'); }); 在这个例子中,我们首先引入了Express和Cors模块,然后创建了一个新的Express应用程序,并使用cors()方法设置了允许所有源访问的应用程序中间件。 四、总结 跨域问题是我们在进行网页或应用开发时经常会遇到的问题。通过使用Node.js中间件,我们可以很容易地解决这个问题。在这篇文章里,我们手把手教你如何用cors这个小工具,轻松几步设置好响应头,让任何源都能无障碍访问你的资源~虽然这种方法安全性可能没那么高,但是在某些特定情况下,它可能是最省事儿、最一针见血的解决方案了。 当然,这只是一个基本的示例。在实际做项目的时候,你可能遇到需要制定更高级的跨域方案,比如说,得让特定的一些来源能够访问,或者干脆只放行那些从HTTPS请求过来的连接啥的。这些都可以通过调整cors库的配置来实现。如果你正在面临跨域问题,我强烈建议你尝试使用cors库来解决。我相信,只要正确使用,它一定能帮你解决问题。
2023-06-11 14:13:21
96
飞鸟与鱼-t
Datax
...ame type: expression expression: 'substr(column_name, 1, 1)' 提取配置 extraction_config: type: query sql: SELECT FROM source_a_log WHERE time > now() - INTERVAL 1 DAY - name: Extract log data from source B task-type: sink description: Extracts log data from source B and writes it to ODPS. config: 数据源配置 source_type: mysql source_host: 192.168.1.2 source_port: 3306 source_username: root source_password: 123456 source_database: logs source_table: source_b_log 目标表配置 destination_type: odps destination_project: my-project destination_database: logs destination_table: odps_log 转换配置 transform_config: - field: column_name type: expression expression: 'substr(column_name, 1, 1)' 提取配置 extraction_config: type: query sql: SELECT FROM source_b_log WHERE time > now() - INTERVAL 1 DAY 四、结论 通过以上介绍,我相信你已经对如何使用DataX进行日志数据采集同步至ODPS有了一个大致的理解。在实际应用中,你可能还需要根据自己的需求进行更多的定制化开发。但无论如何,DataX都会是你的好帮手。
2023-09-12 20:53:09
514
彩虹之上-t
AngularJS
...Node.js + Express为例: javascript const express = require('express'); const app = express(); // 允许来自任何域名的跨域请求 app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', ''); res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); if (req.method === 'OPTIONS') { res.send(200); } else { next(); } }); // 这里是你的路由配置... 4. 客户端注意事项 虽然前端不能设置跨域响应头,但在发起带自定义请求头的跨域请求时,仍需在$httpProvider.defaults.headers中声明这些请求头,以便让服务器知道客户端希望携带哪些头部信息: javascript angular.module('myApp').config(['$httpProvider', function ($httpProvider) { $httpProvider.defaults.headers.common['X-Custom-Header'] = 'some-value'; }]); // 在$http请求中使用 $http({ method: 'POST', url: 'https://api.example.com/data', headers: {'Content-Type': 'application/json'}, data: { / ... / } }); 总结起来,虽然我们不能通过 $httpProvider.defaults.headers 来直接解决跨域问题,但它仍然是我们定制请求头部信息不可或缺的工具。要真正搞定跨域问题,关键得先摸清楚跨域策略的来龙去脉,然后在服务器那边儿把配置给整对了才行。在我们做前端开发这事儿的时候,千万要记牢这个小秘诀,这样一来,当咱们的AngularJS应用碰到跨域问题这块绊脚石时,就能轻松应对、游刃有余啦!
2023-09-21 21:16:40
397
草原牧歌
AngularJS
...五入显示等。通过 expression | filter 这样的语句,AngularJS可以自动执行绑定和过滤操作,确保数据显示符合预期格式。
2024-03-09 11:18:03
476
柳暗花明又一村
Docker
...包含Node.js和Express框架的应用程序的Docker镜像: bash FROM node:12-alpine WORKDIR /app COPY package.json ./ RUN npm install COPY . . EXPOSE 3000 CMD [ "npm", "start" ] 这个Dockerfile定义了一个基于Node.js 12.0.0-alpine镜像的镜像,然后安装了项目所需的所有依赖项,并设置了端口映射为3000。最后,我们可以通过运行以下命令来构建这个Docker镜像: go docker build -t my-node-app . 这将生成一个名为my-node-app的Docker镜像,我们可以使用以下命令将其运行起来: css docker run -p 3000:3000 --name my-running-app my-node-app 现在,你可以通过访问http://localhost:3000来查看你的应用程序是否正常工作。 2. Docker的优点 Docker的主要优点包括: - 隔离:Docker容器是在宿主机上的进程,它们具有自己的网络、文件系统和资源限制,因此可以避免不同应用程序之间的冲突。 - 可移植性:由于Docker镜像是轻量级的,它们可以在任何支持Docker的平台上运行,无论该平台是在开发人员的本地计算机上还是在云服务器上。 - 快速部署:通过使用预构建的Docker镜像,可以快速地部署应用程序,而不需要担心底层基础设施的差异。 3. Docker的使用场景 Docker适用于许多不同的场景,包括但不限于: - 开发:Docker可以帮助开发人员在同一台机器上运行多个实例,每个实例都具有其特定的配置和依赖项。另外,Docker这小家伙还能在持续集成和持续部署(CI/CD)的流程里大显身手呢! - 测试:Docker可以模拟不同的操作系统和网络环境,以便进行兼容性和性能测试。 - 运行时:Docker可以用于在生产环境中运行应用程序,因为它的隔离特性可以确保应用程序不会影响其他应用程序。 - 基础设施即服务(IaaS):Docker可以与云平台(如AWS、Google Cloud、Azure等)集成,从而提供一种高度可扩展和灵活的基础架构解决方案。 4. Docker的最佳实践 虽然Docker提供了很多便利,但也有一些最佳实践需要遵循,以确保您的Docker容器始终处于最佳状态。这些最佳实践包括: - 使用轻量级的操作系统:选择轻量级的Docker镜像作为基础镜像,以减少镜像的大小和启动时间。 - 最小化运行时依赖项:只在容器内安装应用程序所需的必要组件,以防止潜在的安全漏洞。 - 使用端口映射:在Docker容器外部公开端口号,以便客户端可以连接到容器内的应用程序。 - 使用守护进程:如果应用程序需要持久运行,那么应该将其包装在一个守护进程中,这样即使容器关闭,应用程序仍然可以继续运行。 - 使用卷:如果应用程序需要持久存储数据,那么应该将其挂载到一个Docker卷中,而不是在容器内部存储数据。
2023-02-17 17:09:52
515
追梦人-t
SeaTunnel
...] - type: expression script: "field3 = field1 + field2" 这段配置表示仅选择field1和field2字段,并进行一个简单的字段运算,生成新的field3。 2.3 数据写入目标系统 处理后的数据可以被发送到任意目标系统,比如另一个Kafka主题或HDFS: yaml sink: type: kafka09 bootstrapServers: "localhost:9092" topic: "output-topic" 或者 yaml sink: type: hdfs path: "hdfs://namenode:8020/output/path" 3. 实现 ExactlyOnce 语义 ExactlyOnce 语义是指在分布式系统中,每条消息只被精确地处理一次,即使在故障恢复后也是如此。在SeaTunnel这个工具里头,我们能够实现这个目标,靠的是把Flink或者其他那些支持“ExactlyOnce”这种严谨语义的计算引擎,与具有事务处理功能的数据源和目标巧妙地搭配起来。就像是玩拼图一样,把这些组件严丝合缝地对接起来,确保数据的精准无误传输。 例如,在与Apache Flink整合时,SeaTunnel可以利用Flink的Checkpoint机制来保证状态一致性及ExactlyOnce语义。同时,SeaTunnel还有个很厉害的功能,就是针对那些支持事务处理的数据源,比如更新到Kafka 0.11及以上版本的,还有目标端如Kafka、能进行事务写入的HDFS,它都能联手计算引擎,确保从头到尾,数据“零丢失零重复”的精准传输,真正做到端到端的ExactlyOnce保证。就像一个超级快递员,确保你的每一份重要数据都能安全无误地送达目的地。 在配置中,开启Flink Checkpoint功能,确保在处理过程中遇到故障时可以从检查点恢复并继续处理,避免数据丢失或重复: yaml engine: type: flink checkpoint: interval: 60s mode: exactly_once 总结来说,借助SeaTunnel灵活强大的流式数据处理能力,结合支持ExactlyOnce语义的计算引擎和其他组件,我们完全可以在实际业务场景中实现高可靠、无重复的数据处理流程。在这一路的“探险”中,我们可不只是见识到了SeaTunnel那实实在在的实用性以及它强大的威力,更是亲身感受到了它给开发者们带来的那种省心省力、安心靠谱的舒爽体验。而随着技术和需求的不断演进,SeaTunnel也将在未来持续优化和完善,为广大用户提供更优质的服务。
2023-05-22 10:28:27
113
夜色朦胧
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
rm -rf dir/*
- 删除目录下所有文件(慎用)。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"