前端技术
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
[数据源整合技巧 介绍如何将不同来源的数据...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Kylin
... 用Kylin解决数据集成与管理问题 在大数据时代,数据就像石油一样珍贵。不过呢,要想让这些数据真正派上用场,我们就得搞定数据整合和管理,让它变得又快又好。嘿,今天想跟大家聊聊Apache Kylin,这是一款超棒的开源分布式分析工具,它能帮我们轻松搞定数据整合和管理的问题。 1. Kylin是什么? 首先,让我们来了解一下Kylin是什么。Kylin这东西啊,是建在Hadoop上面的一个数据仓库工具,你可以用SQL来跟它对话,而且它在处理超大规模的数据时,查询速度能快到像闪电一样,几乎就在一眨眼的工夫。Kylin最初是由eBay开发的,后来成为了Apache软件基金会的顶级项目之一。对那些每天得跟海量数据打交道,还得迅速分析的企业来说,Kylin简直就是个神器。 2. 数据集成挑战 在开始之前,我们需要认识到数据集成与管理面临的挑战。我们在搭建数据仓库的时候,经常会碰到各种棘手的问题,比如数据来源五花八门、数据量大到吓人,还有数据质量也是参差不齐,真是让人头大。而Kylin正是为了解决这些问题而生。 2.1 多样化数据源 想象一下,你的公司可能拥有来自不同部门、不同系统的数据,比如销售数据、用户行为数据、库存数据等。如何把这些数据统一起来,形成一个完整的数据视图,是数据集成的第一步。 代码示例: python 假设我们有一个简单的ETL流程,将数据从多个源导入Kylin from pykylin import KylinClient client = KylinClient(host='localhost', port=7070) project_name = 'sales_project' 创建一个新的项目 client.create_project(project_name) 将数据从Sales系统导入Kylin sales_data = client.import_data('sales_source', project_name) 同样的方式处理用户行为数据 user_behavior_data = client.import_data('user_behavior_source', project_name) 在这个例子中,我们简化了实际操作中的复杂度,但是可以看到,通过Kylin提供的API,我们可以轻松地将来自不同源的数据导入到Kylin中,为后续的数据分析打下基础。 3. 数据管理策略 有了数据之后,接下来就是如何有效地管理和利用这些数据了。Kylin提供了多种数据管理策略,包括但不限于数据模型的设计、维度的选择以及Cube的构建。 3.1 数据模型设计 一个好的数据模型设计能够极大地提升查询效率。Kylin 这个工具挺酷的,可以让用户自己定义多维数据模型。这样一来,我们就能够根据实际的业务需求,随心所欲地搭建数据立方体了。 代码示例: python 定义一个数据模型 model = { "name": "sales_model", "dimensions": [ {"name": "date"}, {"name": "product_id"}, {"name": "region"} ], "measures": [ {"name": "total_sales", "function": "SUM"} ] } 使用Kylin API创建数据模型 client.create_model(model, project_name) 在这个例子中,我们定义了一个包含日期、产品ID和区域三个维度以及总销售额这一指标的数据模型。通过这种方式,我们可以针对不同的业务场景构建适合的数据模型。 3.2 Cube构建 Cube是Kylin的核心概念之一。它是一种预计算的数据结构,用于加速查询速度。Kylin 这个工具挺酷的,能让用户自己决定怎么搭建 Cube。比如说,你可以挑选哪些维度要放进 Cube 里,还可以设置数据怎么汇总。 代码示例: python 构建一个包含所有维度的Cube cube_config = { "name": "all_dimensions_cube", "model_name": "sales_model", "dimensions": ["date", "product_id", "region"], "measures": ["total_sales"] } 使用Kylin API创建Cube client.create_cube(cube_config) 在这个例子中,我们构建了一个包含了所有维度的Cube。这样做虽然会增加存储空间的需求,但能够显著提高查询效率。 4. 总结 通过上述介绍,我们可以看到Kylin在解决数据集成与管理问题上所展现的强大能力。无论是面对多样化的数据源还是复杂的业务需求,Kylin都能提供有效的解决方案。当然,Kylin并非万能,它也有自己的局限性和适用场景。所以啊,在实际操作中,我们要根据实际情况灵活地选择和调整策略,这样才能真正把Kylin的作用发挥出来。 最后,我想说的是,技术的发展永远是双刃剑,它既带来了前所未有的机遇,也伴随着挑战。咱们做技术的啊,得有一颗好奇的心,老是去学新东西,新技能。遇到难题也不要怕,得敢上手,找办法解决。只有这样,我们才能在这个快速变化的时代中立于不败之地。
2024-12-12 16:22:02
88
追梦人
Hadoop
随着大数据这股浪潮席卷而来,各行各业对数据处理的需求可以说是爆炸式增长。而Hadoop这个家伙,作为当前炙手可热的大数据处理框架之一,已经成功打入各个行业的核心地带,被大家伙儿广泛应用着。在实际处理数据的时候,咱们常常得干一些额外的活儿,比如给数据“洗洗澡”,变个身,再把它们装进系统里边去。这会儿,ETL工具就派上大用场啦!这次,咱就拿Hadoop和ETL工具的亲密合作当个例子,来说说Apache NiFi和Apache Beam这两个在数据圈里炙手可热的ETL小能手。我不仅会给你详细介绍它们的功能特点,还会通过实实在在的代码实例,手把手带你瞧瞧怎么让它们跟Hadoop成功牵手,一起愉快地干活儿。 一、Apache NiFi简介 Apache NiFi是一个基于Java的流数据处理器,它可以接收、路由、处理和传输数据。这个东西最棒的地方在于,你可以毫不费力地搭建和管控那些超级复杂的实时数据流管道,并且它还很贴心地支持各种各样的数据来源和目的地,相当给力!由于它具有高度可配置性和灵活性,因此可以用于各种数据处理场景。 二、Hadoop与Apache NiFi集成 为了使Hadoop与Apache NiFi进行集成,我们需要安装Apache NiFi并将其添加到Hadoop集群中。具体步骤如下: 1. 安装Apache NiFi 我们可以从Apache NiFi的官方网站下载最新的稳定版本,并按照官方提供的指导手册进行安装。在安装这个东西的时候,我们得先调整几个基础配置,就好比NiFi的端口号码啦,还有它怎么进行身份验证这些小细节。 2. 将Apache NiFi添加到Hadoop集群中 为了让Apache NiFi能够访问Hadoop集群中的数据,我们需要配置NiFi的环境变量。首先,我们需要确定Hadoop集群的位置,然后在NiFi的环境中添加以下参数: javascript export HADOOP_CONF_DIR=/path/to/hadoop/conf export HADOOP_HOME=/path/to/hadoop 3. 配置NiFi数据源 接下来,我们需要配置NiFi的数据源,使其能够连接到Hadoop集群中的HDFS文件系统。在NiFi的用户界面里,我们可以亲自操刀,动手新建一个数据源,而且,你可以酷炫地选择“HDFS”作为这个新数据源的小马甲,也就是它的类型啦!然后,我们需要输入HDFS的地址、用户名、密码等信息。 4. 创建数据处理流程 最后,我们可以创建一个新的数据处理流程,使Apache NiFi能够读取HDFS中的数据,并对其进行处理和转发。我们可以在NiFi的UI界面中创建新的流程节点,并将它们连接起来。例如,我们可以使用“GetFile”节点来读取HDFS中的数据,使用“TransformJSON”节点来处理数据,使用“PutFile”节点来将处理后的数据保存到其他位置。 三、Apache Beam简介 Apache Beam是一个开源的统一编程模型,它可以用于构建批处理和实时数据处理应用程序。这个东西的好处在于,你可以在各种不同的数据平台上跑同一套代码,这样一来,开发者们就能把更多的精力放在数据处理的核心逻辑上,而不是纠结于那些底层的繁琐细节啦。 四、Hadoop与Apache Beam集成 为了使Hadoop与Apache Beam进行集成,我们需要使用Apache Beam SDK,并将其添加到Hadoop集群中。具体步骤如下: 1. 安装Apache Beam SDK 我们可以从Apache Beam的官方网站下载最新的稳定版本,并按照官方提供的指导手册进行安装。在安装这玩意儿的时候,我们得先调好几个基础配置,就好比Beam的通讯端口、验证登录的方式这些小细节。 2. 将Apache Beam SDK添加到Hadoop集群中 为了让Apache Beam能够访问Hadoop集群中的数据,我们需要配置Beam的环境变量。首先,我们需要确定Hadoop集群的位置,然后在Beam的环境中添加以下参数: javascript export HADOOP_CONF_DIR=/path/to/hadoop/conf export HADOOP_HOME=/path/to/hadoop 3. 编写数据处理代码 接下来,我们可以编写数据处理代码,并使用Apache Beam SDK来运行它。以下是使用Apache Beam SDK处理HDFS中的数据的一个简单示例: java public class HadoopWordCount { public static void main(String[] args) throws Exception { Pipeline p = Pipeline.create(); String input = "gs://dataflow-samples/shakespeare/kinglear.txt"; TextIO.Read read = TextIO.read().from(input); PCollection words = p | read; PCollection> wordCounts = words.apply( MapElements.into(TypeDescriptors.KVs(TypeDescriptors.strings(), TypeDescriptors.longs())) .via((String element) -> KV.of(element, 1)) ); wordCounts.apply(Write.to("gs://my-bucket/output")); p.run(); } } 在这个示例中,我们首先创建了一个名为“p”的Pipeline对象,并指定要处理的数据源。然后,我们使用“TextIO.Read”方法从数据源中读取数据,并将其转换为PCollection类型。接下来,我们要用一个叫“KV.of”的小技巧,把每一条数据都变个身,变成一个个键值对。这个键呢,就是咱们平常说的单词,而对应的值呢,就是一个简简单单的1。就像是给每个单词贴上了一个标记“已出现,记1次”。最后,我们将处理后的数据保存到Google Cloud Storage中的指定位置。 五、结论 总的来说,Hadoop与Apache NiFi和Apache Beam的集成都是非常容易的。只需要按照上述步骤进行操作,并编写相应的数据处理代码即可。而且,你知道吗,Apache NiFi和Apache Beam都超级贴心地提供了灵活度爆棚的API接口,这就意味着我们完全可以按照自己的小心思,随心所欲定制咱们的数据处理流程,就像DIY一样自由自在!相信过不了多久,Hadoop和ETL工具的牵手合作将会在大数据处理圈儿掀起一股强劲风潮,成为大伙儿公认的关键趋势。
2023-06-17 13:12:22
581
繁华落尽-t
Mongo
...误啊,常常会在我们把数据塞进数据库的时候冒出来。就好比你本来打算把苹果放水果篮子里,结果不小心塞了个梨,那肯定就出岔子啦。说的就是这个理儿,就是当咱们提供的数据类型和数据库希望的对不上号,这错误就蹦跶出来了。今天我们就来详细地讨论一下这个问题。 什么是字段类型? 首先,让我们来看看什么是字段类型。在数据库这个大家族里,每一种数据都有它独特的身份标签,也就是类型。这些类型就像咱们生活中的各种工具,帮助我们在和数据打交道的时候,更好地理解它们的“脾气”和“秉性”,更顺手地对它们进行各种操作,让工作变得轻松又高效。例如,在MongoDB中,我们可以定义字段为字符串类型、数字类型、日期类型等。 字符串和数字字段类型不匹配的问题 现在,我们来看看如何解决字符串和数字字段类型不匹配的问题。这是一个非常常见的问题,尤其是在我们从外部源(如API)获取数据时。有时候啊,这些数据可能没被我们给正确转换类型,就像把方块塞进圆洞里一样,结果在往MongoDB数据库里插的时候,就蹦出了个“类型对不上”的错误提示。 让我们来看一个具体的例子: javascript var db = require('mongodb').connect('mongodb://localhost:27017/test'); db.collection('test').insertOne({ "name": "John", "age": "30" }, function(err, result) { if (err) throw err; console.log(result); }); 在这个例子中,我们试图将一个字符串"30"插入到一个字段"age"中,但是"age"被定义为数字类型。当我们运行这段代码时,我们会收到一个错误,提示我们字段类型不匹配。 要解决这个问题,我们可以使用Number()函数将字符串转换为数字: javascript var db = require('mongodb').connect('mongodb://localhost:27017/test'); db.collection('test').insertOne({ "name": "John", "age": Number("30") }, function(err, result) { if (err) throw err; console.log(result); }); 这样,我们就成功地将字符串"30"转换为了数字,并且成功地将其插入到了数据库中。 总结 总的来说,字段类型不匹配是一个很常见的问题,特别是在我们处理来自不同来源的数据时。你知道吗,只要我们学会并熟练运用正确的类型转换技巧,就能轻松搞定这个问题,确保咱们的数据能够顺顺利利地“搬”进MongoDB数据库里。这样一来,就再也不用担心数据插入时的小插曲啦!
2023-12-16 08:42:04
184
幽谷听泉-t
Superset
Superset与Apache Kafka实时流数据集成:探索与实践 1. 引言 在大数据时代,实时数据分析已经成为企业决策的重要支撑。Superset,这款由Airbnb大神们慷慨开源的数据可视化和BI工具,可厉害了!它凭借无比强大的数据挖掘探索力,以及那让人拍案叫绝的灵活仪表板定制功能,早就赢得了大家伙儿的一致喜爱和热捧啊!而Apache Kafka作为高吞吐量、分布式的消息系统,被广泛应用于实时流数据处理场景中。将这两者有机结合,无疑能够为企业的实时业务分析带来巨大价值。本文将以“Superset与Apache Kafka实时流数据集成”为主题,通过实例代码深入探讨这一技术实践过程。 2. Superset简介与优势 Superset是一款强大且易于使用的开源数据可视化平台,它允许用户通过拖拽的方式创建丰富的图表和仪表板,并能直接查询多种数据库进行数据分析。其灵活性和易用性使得非技术人员也能轻松实现复杂的数据可视化需求。 3. Apache Kafka及其在实时流数据中的角色 Apache Kafka作为一个分布式的流处理平台,擅长于高效地发布和订阅大量实时消息流。它的最大亮点就是,能够在多个生产者和消费者之间稳稳当当地传输海量数据,尤其适合用来搭建那些实时更新、数据流动如飞的应用程序和数据传输管道,就像是个超级快递员,在各个角色间高效地传递信息。 4. Superset与Kafka集成 技术实现路径 (1) 数据摄取: 首先,我们需要配置Superset连接到Kafka数据源。这通常需要咱们用类似“kafka-python”这样的工具箱,从Kafka的主题里边捞出数据来,然后把这些数据塞到Superset能支持的数据仓库里,比如PostgreSQL或者MySQL这些数据库。例如: python from kafka import KafkaConsumer import psycopg2 创建Kafka消费者 consumer = KafkaConsumer('your-topic', bootstrap_servers=['localhost:9092']) 连接数据库 conn = psycopg2.connect(database="your_db", user="your_user", password="your_password", host="localhost") cur = conn.cursor() for message in consumer: 解析并处理Kafka消息 data = process_message(message.value) 将数据写入数据库 cur.execute("INSERT INTO your_table VALUES (%s)", (data,)) conn.commit() (2) Superset数据源配置: 在成功将Kafka数据导入到数据库后,需要在Superset中添加对应的数据库连接。打开Superset的管理面板,就像装修房子一样,咱们得设定一个新的SQLAlchemy链接地址,让它指向你的数据库。想象一下,这就是给Superset指路,让它能够顺利找到并探索你刚刚灌入的那些Kafka数据宝藏。 (3) 创建可视化图表: 最后,你可以在Superset中创建新的 charts 或仪表板,利用SQL Lab查询刚刚配置好的数据库,从而实现对Kafka实时流数据的可视化展现。 5. 实践思考与探讨 将Superset与Apache Kafka集成的过程并非一蹴而就,而是需要根据具体业务场景灵活设计数据流转和处理流程。咱们不光得琢磨怎么把Kafka那家伙产生的实时数据,嗖嗖地塞进关系型数据库里头,同时还得留意,在不破坏数据“新鲜度”的大前提下,确保这些数据的完整性和一致性,可马虎不得啊!另外,在使用Superset的时候,咱们可得好好利用它那牛哄哄的数据透视和过滤功能,这样一来,甭管业务分析需求怎么变,都能妥妥地满足它们。 总结来说,Superset与Apache Kafka的结合,如同给实时数据流插上了一双翅膀,让数据的价值得以迅速转化为洞见,驱动企业快速决策。在这个过程中,我们将不断探索和优化,以期在实践中发掘更多可能。
2023-10-19 21:29:53
301
青山绿水
Datax
...本环境配置后,对于大数据处理和迁移领域的最新动态及深入应用,以下是一些推荐的延伸阅读内容: 1. 阿里云实时数据集成服务MaxCompute DataWorks:作为DataX的“同门兄弟”,阿里云推出的MaxCompute DataWorks提供了更为全面的数据开发、治理、服务和安全能力。近期,DataWorks升级了其数据同步模块,支持更丰富的数据源接入,实现了分钟级数据入湖,并增强了实时数据处理性能,为用户带来了全新的数据整合体验。 2. DataX在金融业数据迁移中的实战案例分析:某知名金融机构最近分享了利用DataX进行跨系统、跨数据中心大规模数据迁移的成功经验,深入剖析了如何结合DataX特性优化迁移策略以确保数据一致性与迁移效率,为业界提供了宝贵的操作指南。 3. 开源社区对DataX生态发展的讨论:随着开源技术的快速发展,国内外开发者们围绕DataX在GitHub等平台展开了热烈讨论,不仅对DataX的功能扩展提出了新的设想,还针对不同场景下的问题给出了针对性解决方案。例如,有开发者正在研究如何将DataX与Kafka、Flink等流处理框架更好地融合,实现准实时的数据迁移与处理。 4. 基于DataX的企业级数据治理最佳实践:在企业数字化转型的过程中,DataX在数据治理体系中扮演着重要角色。一篇由业内专家撰写的深度解读文章,探讨了如何通过定制化DataX任务以及与其他数据治理工具如Apache Atlas、Hue等配合,构建起符合企业需求的数据生命周期管理方案。 5. DataX新版本特性解析及未来展望:DataX项目团队持续更新产品功能,新发布的版本中包含了诸多改进与新特性,如增强对云数据库的支持、优化分布式作业调度算法等。关注这些新特性的解读文章,有助于用户紧跟技术潮流,充分利用DataX提升数据处理效能,降低运维成本。
2024-02-07 11:23:10
361
心灵驿站-t
Hadoop
...oop的HBase:如何与NoSQL数据库进行数据交互? 引言 在大数据的世界里,数据量的爆炸式增长使得数据管理成为了一项挑战。Hadoop,作为分布式计算的先驱,提供了处理大规模数据的能力。哎呀,你知道的,HBase在Hadoop这个大家庭里可是个大明星呢!它就像个超级仓库,能把海量的数据整齐地放好,不管是半结构化的数据,还是那些乱七八糟的非结构化数据,HBase都能搞定。你想想,当你需要快速查询或者修改这些数据的时候,HBase就像是你的私人管家,既快又精准,简直是太方便了!所以,无论是大数据分析、实时数据分析还是构建大规模的数据库系统,HBase都是你不可多得的好帮手!本文将深入探讨HBase如何与NoSQL数据库进行数据交互,以及这种交互在实际应用场景中的价值。 HBase概述 HBase是一种基于列存储的NoSQL数据库,它构建在Hadoop的HDFS之上,利用MapReduce进行数据处理。哎呀,HBase这东西啊,它就是借鉴了Google的Bigtable的思路,就是为了打造一个既能跑得快,又稳当,还能无限长大的数据仓库。简单来说,就是想给咱的数据找个既好用又耐用的家,让数据处理起来更顺畅,不卡壳,还能随着业务增长不断扩容,就跟咱们搬新房子一样,越住越大,越住越舒服!其数据模型支持多维查询,适合处理大量数据并提供快速访问。 与NoSQL数据库的集成 HBase的出现,让开发者能够利用Hadoop的强大计算能力同时享受NoSQL数据库的灵活性。哎呀,你知道的啦,在咱们的实际操作里,HBase这玩意儿可是个好帮手,能和各种各样的NoSQL数据库玩得转,不管是数据共享、搬家还是联合作战查情报,它都能搞定!就像是咱们团队里的多面手,哪里需要就往哪一站,灵活得很呢!以下是几种常见的集成方式: 1. 外部数据源集成 通过简单的API调用,HBase可以读取或写入其他NoSQL数据库的数据,如MongoDB、Cassandra等。这通常涉及数据复制或同步流程,确保数据的一致性和完整性。 2. 数据融合 在大数据分析项目中,HBase可以与其他Hadoop生态系统内的组件(如MapReduce、Spark)结合,处理从各种来源收集的数据,包括但不限于NoSQL数据库。通过这种方式,可以构建更复杂的数据模型和分析流程。 3. 实时数据处理 借助HBase的实时查询能力,可以集成到流处理系统中,如Apache Kafka和Apache Flink,实现数据的实时分析和决策支持。 示例代码实现 下面我们将通过一个简单的示例,展示如何使用HBase与MongoDB进行数据交互。这里假设我们已经安装了HBase和MongoDB,并且它们在本地运行。 步骤一:连接HBase java import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; public class HBaseConnection { public static void main(String[] args) { String hbaseUrl = "localhost:9090"; try { Connection connection = ConnectionFactory.createConnection(HBaseConfiguration.create(), hbaseUrl); System.out.println("Connected to HBase"); } catch (Exception e) { System.err.println("Error connecting to HBase: " + e.getMessage()); } } } 步骤二:连接MongoDB java import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; public class MongoDBConnection { public static void main(String[] args) { String mongoDbUrl = "mongodb://localhost:27017"; try { MongoClient client = new MongoClient(mongoDbUrl); MongoDatabase database = client.getDatabase("myDatabase"); System.out.println("Connected to MongoDB"); } catch (Exception e) { System.err.println("Error connecting to MongoDB: " + e.getMessage()); } } } 步骤三:数据交换 为了简单起见,我们假设我们有一个简单的HBase表和一个MongoDB集合,我们将从HBase读取数据并将其写入MongoDB。 java import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.UpdateOneModel; public class DataExchange { public static void main(String[] args) { // 连接HBase String hbaseUrl = "localhost:9090"; try { Connection hbaseConnection = ConnectionFactory.createConnection(HBaseConfiguration.create(), hbaseUrl); Table hbaseTable = hbaseConnection.getTable(TableName.valueOf("users")); // 连接MongoDB String mongoDbUrl = "mongodb://localhost:27017"; MongoClient mongoClient = new MongoClient(mongoDbUrl); MongoDatabase db = mongoClient.getDatabase("myDatabase"); MongoCollection collection = db.getCollection("users"); // 从HBase读取数据 Put put = new Put(Bytes.toBytes("123")); hbaseTable.put(put); // 将HBase数据写入MongoDB Document doc = new Document("_id", "123").append("name", "John Doe"); UpdateOneModel updateModel = new UpdateOneModel<>(Filters.eq("_id", "123"), new Document("$set", doc), new UpdateOptions().upsert(true)); collection.updateOne(updateModel); System.out.println("Data exchange completed."); } catch (Exception e) { System.err.println("Error during data exchange: " + e.getMessage()); } } } 请注意,上述代码仅为示例,实际应用中可能需要根据具体环境和需求进行调整。 结论 Hadoop的HBase与NoSQL数据库的集成不仅拓展了数据处理的边界,还极大地提升了数据分析的效率和灵活性。通过灵活的数据交换策略,企业能够充分利用现有数据资源,构建更加智能和响应式的业务系统。无论是数据融合、实时分析还是复杂查询,HBase的集成能力都为企业提供了强大的数据处理工具包。嘿,你知道吗?科技这玩意儿真是越来越神奇了!随着每一步发展,咱们就像在探险一样,发现越来越多的新玩法,新点子。就像是在拼图游戏里,一块块新的碎片让我们能更好地理解这个大数据时代,让它变得更加丰富多彩。我们不仅能看到过去,还能预测未来,这感觉简直酷毙了!所以,别忘了,每一次技术的进步,都是我们在向前跑,探索未知世界的一个大步。
2024-08-10 15:45:14
35
柳暗花明又一村
转载文章
...程详细、完整、深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程能成为掌握ASP.NET Identity技术的一份完整而有价值的资料。读者若是能够按照文章的描述,一边阅读、一边实践、一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐。 15 Advanced ASP.NET Identity 15 ASP.NET Identity高级技术 In this chapter, I finish my description of ASP.NET Identity by showing you some of the advanced features it offers. I demonstrate how you can extend the database schema by defining custom properties on the user class and how to use database migrations to apply those properties without deleting the data in the ASP.NET Identity database. I also explain how ASP.NET Identity supports the concept of claims and demonstrates how they can be used to flexibly authorize access to action methods. I finish the chapter—and the book—by showing you how ASP.NET Identity makes it easy to authenticate users through third parties. I demonstrate authentication with Google accounts, but ASP.NET Identity has built-in support for Microsoft, Facebook, and Twitter accounts as well. Table 15-1 summarizes this chapter. 本章将完成对ASP.NET Identity的描述,向你展示它所提供的一些高级特性。我将演示,你可以扩展ASP.NET Identity的数据库架构,其办法是在用户类上定义一些自定义属性。也会演示如何使用数据库迁移,这样可以运用自定义属性,而不必删除ASP.NET Identity数据库中的数据。还会解释ASP.NET Identity如何支持声明(Claims)概念,并演示如何将它们灵活地用来对动作方法进行授权访问。最后向你展示ASP.NET Identity很容易通过第三方部件来认证用户,以此结束本章以及本书。将要演示的是使用Google账号认证,但ASP.NET Identity对于Microsoft、Facebook以及Twitter账号,都有内建的支持。表15-1是本章概要。 Table 15-1. Chapter Summary 表15-1. 本章概要 Problem 问题 Solution 解决方案 Listing 清单号 Store additional information about users. 存储用户的附加信息 Define custom user properties. 定义自定义用户属性 1–3, 8–11 Update the database schema without deleting user data. 更新数据库架构而不删除用户数据 Perform a database migration. 执行数据库迁移 4–7 Perform fine-grained authorization. 执行细粒度授权 Use claims. 使用声明(Claims) 12–14 Add claims about a user. 添加用户的声明(Claims) Use the ClaimsIdentity.AddClaims method. 使用ClaimsIdentity.AddClaims方法 15–19 Authorize access based on claim values. 基于声明(Claims)值授权访问 Create a custom authorization filter attribute. 创建一个自定义的授权过滤器注解属性 20–21 Authenticate through a third party. 通过第三方认证 Install the NuGet package for the authentication provider, redirect requests to that provider, and specify a callback URL that creates the user account. 安装认证提供器的NuGet包,将请求重定向到该提供器,并指定一个创建用户账号的回调URL。 22–25 15.1 Preparing the Example Project 15.1 准备示例项目 In this chapter, I am going to continue working on the Users project I created in Chapter 13 and enhanced in Chapter 14. No changes to the application are required, but start the application and make sure that there are users in the database. Figure 15-1 shows the state of my database, which contains the users Admin, Alice, Bob, and Joe from the previous chapter. To check the users, start the application and request the /Admin/Index URL and authenticate as the Admin user. 本章打算继续使用第13章创建并在第14章增强的Users项目。对应用程序无需做什么改变,但需要启动应用程序,并确保数据库中有一些用户。图15-1显示了数据库的状态,它含有上一章的用户Admin、Alice、Bob以及Joe。为了检查用户,请启动应用程序,请求/Admin/Index URL,并以Admin用户进行认证。 Figure 15-1. The initial users in the Identity database 图15-1. Identity数据库中的最初用户 I also need some roles for this chapter. I used the RoleAdmin controller to create roles called Users and Employees and assigned the users to those roles, as described in Table 15-2. 本章还需要一些角色。我用RoleAdmin控制器创建了角色Users和Employees,并为这些角色指定了一些用户,如表15-2所示。 Table 15-2. The Types of Web Forms Code Nuggets 表15-2. 角色及成员(作者将此表的标题写错了——译者注) Role 角色 Members 成员 Users Alice, Joe Employees Alice, Bob Figure 15-2 shows the required role configuration displayed by the RoleAdmin controller. 图15-2显示了由RoleAdmin控制器所显示出来的必要的角色配置。 Figure 15-2. Configuring the roles required for this chapter 图15-2. 配置本章所需的角色 15.2 Adding Custom User Properties 15.2 添加自定义用户属性 When I created the AppUser class to represent users in Chapter 13, I noted that the base class defined a basic set of properties to describe the user, such as e-mail address and telephone number. Most applications need to store more information about users, including persistent application preferences and details such as addresses—in short, any data that is useful to running the application and that should last between sessions. In ASP.NET Membership, this was handled through the user profile system, but ASP.NET Identity takes a different approach. 我在第13章创建AppUser类来表示用户时曾做过说明,基类定义了一组描述用户的基本属性,如E-mail地址、电话号码等。大多数应用程序还需要存储用户的更多信息,包括持久化应用程序爱好以及地址等细节——简言之,需要存储对运行应用程序有用并且在各次会话之间应当保持的任何数据。在ASP.NET Membership中,这是通过用户资料(User Profile)系统来处理的,但ASP.NET Identity采取了一种不同的办法。 Because the ASP.NET Identity system uses Entity Framework to store its data by default, defining additional user information is just a matter of adding properties to the user class and letting the Code First feature create the database schema required to store them. Table 15-3 puts custom user properties in context. 因为ASP.NET Identity默认是使用Entity Framework来存储其数据的,定义附加的用户信息只不过是给用户类添加属性的事情,然后让Code First特性去创建需要存储它们的数据库架构即可。表15-3描述了自定义用户属性的情形。 Table 15-3. Putting Cusotm User Properties in Context 表15-3. 自定义用户属性的情形 Question 问题 Answer 回答 What is it? 什么是自定义用户属性? Custom user properties allow you to store additional information about your users, including their preferences and settings. 自定义用户属性让你能够存储附加的用户信息,包括他们的爱好和设置。 Why should I care? 为何要关心它? A persistent store of settings means that the user doesn’t have to provide the same information each time they log in to the application. 设置的持久化存储意味着,用户不必每次登录到应用程序时都提供同样的信息。 How is it used by the MVC framework? 在MVC框架中如何使用它? This feature isn’t used directly by the MVC framework, but it is available for use in action methods. 此特性不是由MVC框架直接使用的,但它在动作方法中使用是有效的。 15.2.1 Defining Custom Properties 15.2.1 定义自定义属性 Listing 15-1 shows how I added a simple property to the AppUser class to represent the city in which the user lives. 清单15-1演示了如何给AppUser类添加一个简单的属性,用以表示用户生活的城市。 Listing 15-1. Adding a Property in the AppUser.cs File 清单15-1. 在AppUser.cs文件中添加属性 using System;using Microsoft.AspNet.Identity.EntityFramework;namespace Users.Models { public enum Cities {LONDON, PARIS, CHICAGO}public class AppUser : IdentityUser {public Cities City { get; set; } }} I have defined an enumeration called Cities that defines values for some large cities and added a property called City to the AppUser class. To allow the user to view and edit their City property, I added actions to the Home controller, as shown in Listing 15-2. 这里定义了一个枚举,名称为Cities,它定义了一些大城市的值,另外给AppUser类添加了一个名称为City的属性。为了让用户能够查看和编辑City属性,给Home控制器添加了几个动作方法,如清单15-2所示。 Listing 15-2. Adding Support for Custom User Properties in the HomeController.cs File 清单15-2. 在HomeController.cs文件中添加对自定义属性的支持 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models;namespace Users.Controllers {public class HomeController : Controller {[Authorize]public ActionResult Index() {return View(GetData("Index"));}[Authorize(Roles = "Users")]public ActionResult OtherAction() {return View("Index", GetData("OtherAction"));}private Dictionary<string, object> GetData(string actionName) {Dictionary<string, object> dict= new Dictionary<string, object>();dict.Add("Action", actionName);dict.Add("User", HttpContext.User.Identity.Name);dict.Add("Authenticated", HttpContext.User.Identity.IsAuthenticated);dict.Add("Auth Type", HttpContext.User.Identity.AuthenticationType);dict.Add("In Users Role", HttpContext.User.IsInRole("Users"));return dict;} [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;await UserManager.UpdateAsync(user);return View(user);}private AppUser CurrentUser {get {return UserManager.FindByName(HttpContext.User.Identity.Name);} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } I added a CurrentUser property that uses the AppUserManager class to retrieve an AppUser instance to represent the current user. I pass the AppUser object as the view model object in the GET version of the UserProps action method, and the POST method uses it to update the value of the new City property. Listing 15-3 shows the UserProps.cshtml view, which displays the City property value and contains a form to change it. 我添加了一个CurrentUser属性,它使用AppUserManager类接收了表示当前用户的AppUser实例。在GET版本的UserProps动作方法中,传递了这个AppUser对象作为视图模型。而在POST版的方法中用它更新了City属性的值。清单15-3显示了UserProps.cshtml视图,它显示了City属性的值,并包含一个修改它的表单。 Listing 15-3. The Contents of the UserProps.cshtml File in the Views/Home Folder 清单15-3. Views/Home文件夹中UserProps.cshtml文件的内容 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";}<div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr></table></div> @using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Caution Don’t start the application when you have created the view. In the sections that follow, I demonstrate how to preserve the contents of the database, and if you start the application now, the ASP.NET Identity users will be deleted. 警告:创建了视图之后不要启动应用程序。在以下小节中,将演示如何保留数据库的内容,如果现在启动应用程序,将会删除ASP.NET Identity的用户。 15.2.2 Preparing for Database Migration 15.2.2 准备数据库迁移 The default behavior for the Entity Framework Code First feature is to drop the tables in the database and re-create them whenever classes that drive the schema have changed. You saw this in Chapter 14 when I added support for roles: When the application was started, the database was reset, and the user accounts were lost. Entity Framework Code First特性的默认行为是,一旦修改了派生数据库架构的类,便会删除数据库中的数据表,并重新创建它们。在第14章可以看到这种情况,在我添加角色支持时:当重启应用程序后,数据库被重置,用户账号也丢失。 Don’t start the application yet, but if you were to do so, you would see a similar effect. Deleting data during development is usually not a problem, but doing so in a production setting is usually disastrous because it deletes all of the real user accounts and causes a panic while the backups are restored. In this section, I am going to demonstrate how to use the database migration feature, which updates a Code First schema in a less brutal manner and preserves the existing data it contains. 不要启动应用程序,但如果你这么做了,会看到类似的效果。在开发期间删除数据没什么问题,但如果在产品设置中这么做了,通常是灾难性的,因为它会删除所有真实的用户账号,而备份恢复是很痛苦的事。在本小节中,我打算演示如何使用数据库迁移特性,它能以比较温和的方式更新Code First的架构,并保留架构中的已有数据。 The first step is to issue the following command in the Visual Studio Package Manager Console: 第一个步骤是在Visual Studio的“Package Manager Console(包管理器控制台)”中发布以下命令: Enable-Migrations –EnableAutomaticMigrations This enables the database migration support and creates a Migrations folder in the Solution Explorer that contains a Configuration.cs class file, the contents of which are shown in Listing 15-4. 它启用了数据库的迁移支持,并在“Solution Explorer(解决方案资源管理器)”创建一个Migrations文件夹,其中含有一个Configuration.cs类文件,内容如清单15-4所示。 Listing 15-4. The Contents of the Configuration.cs File 清单15-4. Configuration.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration: DbMigrationsConfiguration<Users.Infrastructure.AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(Users.Infrastructure.AppIdentityDbContext context) {// This method will be called after migrating to the latest version.// 此方法将在迁移到最新版本时调用// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data. E.g.// 例如,你可以使用DbSet<T>.AddOrUpdate()辅助器方法来避免创建重复的种子数据//// context.People.AddOrUpdate(// p => p.FullName,// new Person { FullName = "Andrew Peters" },// new Person { FullName = "Brice Lambson" },// new Person { FullName = "Rowan Miller" }// );//} }} Tip You might be wondering why you are entering a database migration command into the console used to manage NuGet packages. The answer is that the Package Manager Console is really PowerShell, which is a general-purpose tool that is mislabeled by Visual Studio. You can use the console to issue a wide range of helpful commands. See http://go.microsoft.com/fwlink/?LinkID=108518 for details. 提示:你可能会觉得奇怪,为什么要在管理NuGet包的控制台中输入数据库迁移的命令?答案是“Package Manager Console(包管理控制台)”是真正的PowerShell,这是Visual studio冒用的一个通用工具。你可以使用此控制台发送大量的有用命令,详见http://go.microsoft.com/fwlink/?LinkID=108518。 The class will be used to migrate existing content in the database to the new schema, and the Seed method will be called to provide an opportunity to update the existing database records. In Listing 15-5, you can see how I have used the Seed method to set a default value for the new City property I added to the AppUser class. (I have also updated the class file to reflect my usual coding style.) 这个类将用于把数据库中的现有内容迁移到新的数据库架构,Seed方法的调用为更新现有数据库记录提供了机会。在清单15-5中可以看到,我如何用Seed方法为新的City属性设置默认值,City是添加到AppUser类中自定义属性。(为了体现我一贯的编码风格,我对这个类文件也进行了更新。) Listing 15-5. Managing Existing Content in the Configuration.cs File 清单15-5. 在Configuration.cs文件中管理已有内容 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models;namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);}foreach (AppUser dbUser in userMgr.Users) {dbUser.City = Cities.PARIS;}context.SaveChanges();} }} You will notice that much of the code that I added to the Seed method is taken from the IdentityDbInit class, which I used to seed the database with an administration user in Chapter 14. This is because the new Configuration class added to support database migrations will replace the seeding function of the IdentityDbInit class, which I’ll update shortly. Aside from ensuring that there is an admin user, the statements in the Seed method that are important are the ones that set the initial value for the City property I added to the AppUser class, as follows: 你可能会注意到,添加到Seed方法中的许多代码取自于IdentityDbInit类,在第14章中我用这个类将管理用户植入了数据库。这是因为这个新添加的、用以支持数据库迁移的Configuration类,将代替IdentityDbInit类的种植功能,我很快便会更新这个类。除了要确保有admin用户之外,在Seed方法中的重要语句是那些为AppUser类的City属性设置初值的语句,如下所示: ...foreach (AppUser dbUser in userMgr.Users) { dbUser.City = Cities.PARIS;}context.SaveChanges();... You don’t have to set a default value for new properties—I just wanted to demonstrate that the Seed method in the Configuration class can be used to update the existing user records in the database. 你不一定要为新属性设置默认值——这里只是想演示Configuration类中的Seed方法,可以用它更新数据库中的已有用户记录。 Caution Be careful when setting values for properties in the Seed method for real projects because the values will be applied every time you change the schema, overriding any values that the user has set since the last schema update was performed. I set the value of the City property just to demonstrate that it can be done. 警告:在用于真实项目的Seed方法中为属性设置值时要小心,因为你每一次修改架构时,都会运用这些值,这会将自执行上一次架构更新之后,用户设置的任何数据覆盖掉。这里设置City属性的值只是为了演示它能够这么做。 Changing the Database Context Class 修改数据库上下文类 The reason that I added the seeding code to the Configuration class is that I need to change the IdentityDbInit class. At present, the IdentityDbInit class is derived from the descriptively named DropCreateDatabaseIfModelChanges<AppIdentityDbContext> class, which, as you might imagine, drops the entire database when the Code First classes change. Listing 15-6 shows the changes I made to the IdentityDbInit class to prevent it from affecting the database. 在Configuration类中添加种植代码的原因是我需要修改IdentityDbInit类。此时,IdentityDbInit类派生于描述性命名的DropCreateDatabaseIfModelChanges<AppIdentityDbContext> 类,和你相像的一样,它会在Code First类改变时删除整个数据库。清单15-6显示了我对IdentityDbInit类所做的修改,以防止它影响数据库。 Listing 15-6. Preventing Database Schema Changes in the AppIdentityDbContext.cs File 清单15-6. 在AppIdentityDbContext.cs文件是阻止数据库架构变化 using System.Data.Entity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Models;using Microsoft.AspNet.Identity; namespace Users.Infrastructure {public class AppIdentityDbContext : IdentityDbContext<AppUser> {public AppIdentityDbContext() : base("IdentityDb") { }static AppIdentityDbContext() {Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());}public static AppIdentityDbContext Create() {return new AppIdentityDbContext();} } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> {} } I have removed the methods defined by the class and changed its base to NullDatabaseInitializer<AppIdentityDbContext> , which prevents the schema from being altered. 我删除了这个类中所定义的方法,并将它的基类改为NullDatabaseInitializer<AppIdentityDbContext> ,它可以防止架构修改。 15.2.3 Performing the Migration 15.2.3 执行迁移 All that remains is to generate and apply the migration. First, run the following command in the Package Manager Console: 剩下的事情只是生成并运用迁移了。首先,在“Package Manager Console(包管理器控制台)”中执行以下命令: Add-Migration CityProperty This creates a new migration called CityProperty (I like my migration names to reflect the changes I made). A class new file will be added to the Migrations folder, and its name reflects the time at which the command was run and the name of the migration. My file is called 201402262244036_CityProperty.cs, for example. The contents of this file contain the details of how Entity Framework will change the database during the migration, as shown in Listing 15-7. 这创建了一个名称为CityProperty的新迁移(我比较喜欢让迁移的名称反映出我所做的修改)。这会在文件夹中添加一个新的类文件,而且其命名会反映出该命令执行的时间以及迁移名称,例如,我的这个文件名称为201402262244036_CityProperty.cs。该文件的内容含有迁移期间Entity Framework修改数据库的细节,如清单15-7所示。 Listing 15-7. The Contents of the 201402262244036_CityProperty.cs File 清单15-7. 201402262244036_CityProperty.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity.Migrations; public partial class Init : DbMigration {public override void Up() {AddColumn("dbo.AspNetUsers", "City", c => c.Int(nullable: false));}public override void Down() {DropColumn("dbo.AspNetUsers", "City");} }} The Up method describes the changes that have to be made to the schema when the database is upgraded, which in this case means adding a City column to the AspNetUsers table, which is the one that is used to store user records in the ASP.NET Identity database. Up方法描述了在数据库升级时,需要对架构所做的修改,在这个例子中,意味着要在AspNetUsers数据表中添加City数据列,该数据表是ASP.NET Identity数据库用来存储用户记录的。 The final step is to perform the migration. Without starting the application, run the following command in the Package Manager Console: 最后一步是执行迁移。无需启动应用程序,只需在“Package Manager Console(包管理器控制台)”中运行以下命令即可: Update-Database –TargetMigration CityProperty The database schema will be modified, and the code in the Configuration.Seed method will be executed. The existing user accounts will have been preserved and enhanced with a City property (which I set to Paris in the Seed method). 这会修改数据库架构,并执行Configuration.Seed方法中的代码。已有用户账号会被保留,且增强了City属性(我在Seed方法中已将其设置为“Paris”)。 15.2.4 Testing the Migration 15.2.4 测试迁移 To test the effect of the migration, start the application, navigate to the /Home/UserProps URL, and authenticate as one of the Identity users (for example, as Alice with the password MySecret). Once authenticated, you will see the current value of the City property for the user and have the opportunity to change it, as shown in Figure 15-3. 为了测试迁移的效果,启动应用程序,导航到/Home/UserProps URL,并以Identity中的用户(例如Alice,口令MySecret)进行认证。一旦已被认证,便会看到该用户City属性的当前值,并可以对其进行修改,如图15-3所示。 Figure 15-3. Displaying and changing a custom user property 图15-3. 显示和个性自定义用户属性 15.2.5 Defining an Additional Property 15.2.5 定义附加属性 Now that database migrations are set up, I am going to define a further property just to demonstrate how subsequent changes are handled and to show a more useful (and less dangerous) example of using the Configuration.Seed method. Listing 15-8 shows how I added a Country property to the AppUser class. 现在,已经建立了数据库迁移,我打算再定义一个属性,这恰恰演示了如何处理持续不断的修改,也为了演示Configuration.Seed方法更有用(至少无害)的示例。清单15-8显示了我在AppUser类上添加了一个Country属性。 Listing 15-8. Adding Another Property in the AppUserModels.cs File 清单15-8. 在AppUserModels.cs文件中添加另一个属性 using System;using Microsoft.AspNet.Identity.EntityFramework; namespace Users.Models {public enum Cities {LONDON, PARIS, CHICAGO} public enum Countries {NONE, UK, FRANCE, USA}public class AppUser : IdentityUser {public Cities City { get; set; }public Countries Country { get; set; }public void SetCountryFromCity(Cities city) {switch (city) {case Cities.LONDON:Country = Countries.UK;break;case Cities.PARIS:Country = Countries.FRANCE;break;case Cities.CHICAGO:Country = Countries.USA;break;default:Country = Countries.NONE;break;} }} } I have added an enumeration to define the country names and a helper method that selects a country value based on the City property. Listing 15-9 shows the change I made to the Configuration class so that the Seed method sets the Country property based on the City, but only if the value of Country is NONE (which it will be for all users when the database is migrated because the Entity Framework sets enumeration columns to the first value). 我已经添加了一个枚举,它定义了国家名称。还添加了一个辅助器方法,它可以根据City属性选择一个国家。清单15-9显示了对Configuration类所做的修改,以使Seed方法根据City设置Country属性,但只当Country为NONE时才进行设置(在迁移数据库时,所有用户都是NONE,因为Entity Framework会将枚举列设置为枚举的第一个值)。 Listing 15-9. Modifying the Database Seed in the Configuration.cs File 清单15-9. 在Configuration.cs文件中修改数据库种子 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models; namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);} foreach (AppUser dbUser in userMgr.Users) {if (dbUser.Country == Countries.NONE) {dbUser.SetCountryFromCity(dbUser.City);} }context.SaveChanges();} }} This kind of seeding is more useful in a real project because it will set a value for the Country property only if one has not already been set—subsequent migrations won’t be affected, and user selections won’t be lost. 这种种植在实际项目中会更有用,因为它只会在Country属性未设置时,才会设置Country属性的值——后继的迁移不会受到影响,因此不会失去用户的选择。 1. Adding Application Support 1. 添加应用程序支持 There is no point defining additional user properties if they are not available in the application, so Listing 15-10 shows the change I made to the Views/Home/UserProps.cshtml file to display the value of the Country property. 应用程序中如果没有定义附加属性的地方,则附加属性就无法使用了,因此,清单15-10显示了我对Views/Home/UserProps.cshtml文件的修改,以显示Country属性的值。 Listing 15-10. Displaying an Additional Property in the UserProps.cshtml File 清单15-10. 在UserProps.cshtml文件中显示附加属性 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";} <div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr> <tr><th>Country</th><td>@Model.Country</td></tr></table></div>@using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Listing 15-11 shows the corresponding change I made to the Home controller to update the Country property when the City value changes. 为了在City值变化时能够更新Country属性,清单15-11显示了我对Home控制器所做的相应修改。 Listing 15-11. Setting Custom Properties in the HomeController.cs File 清单15-11. 在HomeController.cs文件中设置自定义属性 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models; namespace Users.Controllers {public class HomeController : Controller {// ...other action methods omitted for brevity...// ...出于简化,这里忽略了其他动作方法... [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;user.SetCountryFromCity(city);await UserManager.UpdateAsync(user);return View(user);}// ...properties omitted for brevity...// ...出于简化,这里忽略了一些属性...} } 2. Performing the Migration 2. 准备迁移 All that remains is to create and apply a new migration. Enter the following command into the Package Manager Console: 剩下的事情就是创建和运用新的迁移了。在“Package Manager Console(包管理器控制台)”中输入以下命令: Add-Migration CountryProperty This will generate another file in the Migrations folder that contains the instruction to add the Country column. To apply the migration, execute the following command: 这将在Migrations文件夹中生成另一个文件,它含有添加Country数据表列的指令。为了运用迁移,可执行以下命令: Update-Database –TargetMigration CountryProperty The migration will be performed, and the value of the Country property will be set based on the value of the existing City property for each user. You can check the new user property by starting the application and authenticating and navigating to the /Home/UserProps URL, as shown in Figure 15-4. 这将执行迁移,Country属性的值将根据每个用户当前的City属性进行设置。通过启动应用程序,认证并导航到/Home/UserProps URL,便可以查看新的用户属性,如图15-4所示。 Figure 15-4. Creating an additional user property 图15-4. 创建附加用户属性 Tip Although I am focused on the process of upgrading the database, you can also migrate back to a previous version by specifying an earlier migration. Use the –Force argument make changes that cause data loss, such as removing a column. 提示:虽然我们关注了升级数据库的过程,但你也可以回退到以前的版本,只需指定一个早期的迁移即可。使用-Force参数进行修改,会引起数据丢失,例如删除数据表列。 15.3 Working with Claims 15.3 使用声明(Claims) In older user-management systems, such as ASP.NET Membership, the application was assumed to be the authoritative source of all information about the user, essentially treating the application as a closed world and trusting the data that is contained within it. 在旧的用户管理系统中,例如ASP.NET Membership,应用程序被假设成是用户所有信息的权威来源,本质上将应用程序视为是一个封闭的世界,并且只信任其中所包含的数据。 This is such an ingrained approach to software development that it can be hard to recognize that’s what is happening, but you saw an example of the closed-world technique in Chapter 14 when I authenticated users against the credentials stored in the database and granted access based on the roles associated with those credentials. I did the same thing again in this chapter when I added properties to the user class. Every piece of information that I needed to manage user authentication and authorization came from within my application—and that is a perfectly satisfactory approach for many web applications, which is why I demonstrated these techniques in such depth. 这是软件开发的一种根深蒂固的方法,使人很难认识到这到底意味着什么,第14章你已看到了这种封闭世界技术的例子,根据存储在数据库中的凭据来认证用户,并根据与凭据关联在一起的角色来授权访问。本章前述在用户类上添加属性,也做了同样的事情。我管理用户认证与授权所需的每一个数据片段都来自于我的应用程序——而且这是许多Web应用程序都相当满意的一种方法,这也是我如此深入地演示这些技术的原因。 ASP.NET Identity also supports an alternative approach for dealing with users, which works well when the MVC framework application isn’t the sole source of information about users and which can be used to authorize users in more flexible and fluid ways than traditional roles allow. ASP.NET Identity还支持另一种处理用户的办法,当MVC框架的应用程序不是有关用户的唯一信息源时,这种办法会工作得很好,而且能够比传统的角色授权更为灵活且流畅的方式进行授权。 This alternative approach uses claims, and in this section I’ll describe how ASP.NET Identity supports claims-based authorization. Table 15-4 puts claims in context. 这种可选的办法使用了“Claims(声明)”,因此在本小节中,我将描述ASP.NET Identity如何支持“Claims-Based Authorization(基于声明的授权)”。表15-4描述了声明(Claims)的情形。 提示:“Claim”在英文字典中不完全是“声明”的意思,根据本文的描述,感觉把它说成“声明”也不一定合适,所以在之后的译文中基本都写成中英文并用的形式,即“声明(Claims)”。根据表15-4中的声明(Claims)的定义:声明(Claims)是关于用户的一些信息片段。一个用户的信息片段当然有很多,每一个信息片段就是一项声明(Claim),用户的所有信息片段合起来就是该用户的声明(Claims)。请读者注意该单词的单复数形式——译者注 Table 15-4. Putting Claims in Context 表15-4. 声明(Claims)的情形 Question 问题 Answer 答案 What is it? 什么是声明(Claims)? Claims are pieces of information about users that you can use to make authorization decisions. Claims can be obtained from external systems as well as from the local Identity database. 声明(Claims)是关于用户的一些信息片段,可以用它们做出授权决定。声明(Claims)可以从外部系统获取,也可以从本地的Identity数据库获取。 Why should I care? 为何要关心它? Claims can be used to flexibly authorize access to action methods. Unlike conventional roles, claims allow access to be driven by the information that describes the user. 声明(Claims)可以用来对动作方法进行灵活的授权访问。与传统的角色不同,声明(Claims)让访问能够由描述用户的信息进行驱动。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework, but it is integrated into the standard authorization features, such as the Authorize attribute. 这不是直接由MVC框架使用的特性,但它集成到了标准的授权特性之中,例如Authorize注解属性。 Tip you don’t have to use claims in your applications, and as Chapter 14 showed, ASP.NET Identity is perfectly happy providing an application with the authentication and authorization services without any need to understand claims at all. 提示:你在应用程序中不一定要使用声明(Claims),正如第14章所展示的那样,ASP.NET Identity能够为应用程序提供充分的认证与授权服务,而根本不需要理解声明(Claims)。 15.3.1 Understanding Claims 15.3.1 理解声明(Claims) A claim is a piece of information about the user, along with some information about where the information came from. The easiest way to unpack claims is through some practical demonstrations, without which any discussion becomes too abstract to be truly useful. To get started, I added a Claims controller to the example project, the definition of which you can see in Listing 15-12. 一项声明(Claim)是关于用户的一个信息片段(请注意这个英文单词的单复数形式——译者注),并伴有该片段出自何处的某种信息。揭开声明(Claims)含义最容易的方式是做一些实际演示,任何讨论都会过于抽象根本没有真正的用处。为此,我在示例项目中添加了一个Claims控制器,其定义如清单15-12所示。 Listing 15-12. The Contents of the ClaimsController.cs File 清单15-12. 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);} }} } Tip You may feel a little lost as I define the code for this example. Don’t worry about the details for the moment—just stick with it until you see the output from the action method and view that I define. More than anything else, that will help put claims into perspective. 提示:你或许会对我为此例定义的代码感到有点失望。此刻对此细节不必着急——只要稍事忍耐,当看到该动作方法和视图的输出便会明白。尤为重要的是,这有助于洞察声明(Claims)。 You can get the claims associated with a user in different ways. One approach is to use the Claims property defined by the user class, but in this example, I have used the HttpContext.User.Identity property to demonstrate the way that ASP.NET Identity is integrated with the rest of the ASP.NET platform. As I explained in Chapter 13, the HttpContext.User.Identity property returns an implementation of the IIdentity interface, which is a ClaimsIdentity object when working using ASP.NET Identity. The ClaimsIdentity class is defined in the System.Security.Claims namespace, and Table 15-5 shows the members it defines that are relevant to this chapter. 可以通过不同的方式获得与用户相关联的声明(Claims)。方法之一就是使用由用户类定义的Claims属性,但在这个例子中,我使用了HttpContext.User.Identity属性,目的是演示ASP.NET Identity与ASP.NET平台集成的方式(请注意这句话所表示的含义:用户类的Claims属性属于ASP.NET Identity,而HttpContext.User.Identity属性则属于ASP.NET平台。由此可见,ASP.NET Identity已经融合到了ASP.NET平台之中——译者注)。正如第13章所解释的那样,HttpContext.User.Identity属性返回IIdentity的接口实现,当使用ASP.NET Identity时,该实现是一个ClaimsIdentity对象。ClaimsIdentity类是在System.Security.Claims命名空间中定义的,表15-5显示了它所定义的与本章有关的成员。 Table 15-5. The Members Defined by the ClaimsIdentity Class 表15-5. ClaimsIdentity类所定义的成员 Name 名称 Description 描述 Claims Returns an enumeration of Claim objects representing the claims for the user. 返回表示用户声明(Claims)的Claim对象枚举 AddClaim(claim) Adds a claim to the user identity. 给用户添加一个声明(Claim) AddClaims(claims) Adds an enumeration of Claim objects to the user identity. 给用户添加Claim对象的枚举。 HasClaim(predicate) Returns true if the user identity contains a claim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information 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
转载
Kibana
...言 你是否曾经想过,如何通过简单的方式来分析和理解复杂的数据?或者,你是否曾经遇到过需要生成大量报告,但又不知道如何下手的问题?别担心,今天我们将向你展示一个强大的工具——Kibana,它可以帮助我们轻松解决这些问题。 二、什么是Kibana? Kibana是一个基于浏览器的开源数据可视化工具,它是Elastic Stack的一部分。Elastic Stack是由Elastic公司开发的一套用于搜索、日志管理和分析的工具集合。Kibana主要用于创建交互式的图表、仪表盘以及探索和分析各种类型的数据。 三、使用Kibana创建自定义工作流程 我们可以使用Kibana的Canvas功能来创建自定义的工作流程。Canvas这个工具,就像是个超级画板,它能让我们把多个不同地方的数据源统统拽到一个画面里,然后像拼图一样把它们拼接起来,这样我们就能从一个更全面、更立体的角度去理解和掌握这些信息啦。 让我们看看如何在Canvas中创建一个工作流程: python from kibana import Kibana 创建一个Kibana实例 kibana = Kibana() 添加一个新的数据源 kibana.add_data_source('my_data_source', 'my_index') 创建一个新的视图 view = kibana.create_view('my_view', ['my_data_source']) 将视图添加到工作流程中 workflow = kibana.create_workflow('my_workflow') workflow.add_view(view) 保存工作流程 kibana.save_workflow(workflow) 在这个例子中,我们首先创建了一个Kibana实例,然后添加了一个新的数据源。接着,我们创建了一个新的视图,并将其添加到了我们的工作流程中。最后,我们将这个工作流程保存了下来。 四、生成自动化报告 一旦我们有了一个工作流程,我们就可以使用Kibana的Report功能来生成自动化报告。Report允许我们设置定时任务,以定期生成新的报告。 python from kibana import Kibana 创建一个Kibana实例 kibana = Kibana() 创建一个新的报告 report = kibana.create_report('my_report', 'my_workflow') 设置定时任务 report.set_cron_schedule(' ') 保存报告 kibana.save_report(report) 在这个例子中,我们首先创建了一个Kibana实例,然后创建了一个新的报告,并将其关联到了我们之前创建的工作流程。接着,我们设置了定时任务,以便每小时生成一次新的报告。最后,我们将这个报告保存了下来。 五、结论 总的来说,Kibana是一个非常强大而灵活的工具,它可以帮助我们轻松地处理和分析数据,生成自动化报告。用Kibana的Canvas功能,咱们就能随心所欲地定制自己的工作流程,确保一切都能按照咱们独特的需求来运行。就像是在画布上挥洒创意一样,让数据处理也能按照咱的心意来设计和展示,可方便了!同时,通过使用Report功能,我们可以设置定时任务,以方便地生成和分发自动化报告。 如果你还没有尝试过使用Kibana,我强烈建议你去试一试。我相信,一旦你开始使用它,你就不会想再离开它了。
2023-07-18 21:32:08
302
昨夜星辰昨夜风-t
Apache Pig
在当今的大数据分析领域,除了UNION和UNION ALL之外,还有很多其他重要的技术值得关注。最近,一项关于数据集成的研究引起了广泛关注。这项研究由国际数据工程协会发布,重点探讨了在处理大规模数据集时,如何高效地合并不同来源的数据,以实现更准确的分析结果。 例如,Facebook近期宣布了一项新的数据整合计划,旨在通过UNION和UNION ALL等操作,更好地管理其全球用户数据。Facebook的数据团队表示,通过优化这些操作,他们能够在数秒内完成原本需要几分钟才能完成的数据合并任务。这一改进不仅提升了数据处理速度,还显著降低了计算资源的消耗。 此外,Google BigQuery也在不断更新其数据处理功能,引入了更多高级的数据合并和清洗技术。BigQuery团队指出,通过结合使用UNION和UNION ALL,以及自定义函数,用户可以更灵活地处理复杂的数据集。这些改进使得大数据分析变得更加高效和便捷。 与此同时,亚马逊AWS也发布了关于其Redshift数据仓库的最新版本,其中新增了许多数据合并功能。这些新功能不仅支持UNION和UNION ALL,还提供了更多的数据清洗和预处理选项。这使得用户可以在同一个平台上完成从数据导入到分析的所有步骤,大大简化了工作流程。 这些案例表明,随着技术的不断发展,数据合并和处理技术也在不断进步。了解并掌握最新的数据处理工具和方法,对于从事大数据分析的专业人士来说至关重要。未来,我们可以期待更多创新的数据处理技术,这将使大数据分析变得更加高效和准确。
2025-01-12 16:03:41
81
昨夜星辰昨夜风
Logstash
...ic 公司开发的开源数据收集引擎,主要用于实时处理、过滤和转发来自不同来源的数据。在日志管理和监控领域中广泛应用,它可以收集包括系统日志、应用程序日志、数据库记录等各类数据源的日志信息,并通过一系列插件进行数据解析、转换和输出,最终将这些处理后的数据高效地发送到如Elasticsearch、Kafka、Solr等多种存储或分析系统中。 输出插件 , 在Logstash框架中,输出插件是负责将经过输入和中间阶段处理过的数据传输至目标系统的组件。输出插件具备特定的功能,比如可以将数据写入文件、数据库,或者发送到消息队列、搜索引擎等不同的目的地。由于每个插件设计和支持的目标各异,并非所有输出插件都兼容所有类型的输出目标,因此在实际应用时需要根据需求选择合适的输出插件以确保数据能正确送达指定位置。 HTTP 插件 , HTTP插件是Logstash众多输出插件之一,它允许用户将数据通过HTTP协议发送到任何支持HTTP接口的目标地址。在本文中,HTTP插件作为一个通用解决方案被提及,当用户无法找到直接支持所需输出目标的插件时,可以通过配置HTTP插件,定义URL、请求方法(如POST)以及请求体内容,从而实现将数据灵活推送到自定义API或其他HTTP服务的目的。
2023-11-18 22:01:19
303
笑傲江湖-t
Spark
在大数据这行里,Apache Spark可真是个大明星,就因为它那超凡的数据处理效率和无比强大的机器学习工具箱,引得大家伙儿都对它投来关注的目光。不过,在实际操作的时候,我们经常会遇到这样的情形:需要把各种来源的数据,比如SQL数据库里的数据,搬运到Spark这个平台里头,好让我们能够对这些数据进行更深入的加工和解读。这篇文章将带你了解如何将数据从SQL数据库导入到Spark中。 首先,我们需要了解一下什么是Spark。Spark是一款超级厉害的大数据处理工具,它快得飞起,又能应对各种复杂的任务场景。无论是批处理大批量的数据,还是进行实时的交互查询,甚至流式数据处理和复杂的图计算,它都能轻松搞定,可以说是大数据界的多面手。它通过内存计算的方式,大大提高了数据处理的速度。 那么,如何将数据从SQL数据库导入到Spark中呢?我们可以分为以下几个步骤: 一、创建Spark会话 在Spark中,我们通常会使用SparkSession来与Spark进行交互。首先,我们需要创建一个SparkSession实例: python from pyspark.sql import SparkSession spark = SparkSession.builder.appName('MyApp').getOrCreate() 二、读取SQL数据库中的数据 在Spark中,我们可以使用read.jdbc()函数来读取SQL数据库中的数据。这个函数需要提供一些参数,包括数据库URL、表名、用户名、密码等: python df = spark.read.format("jdbc").options( url="jdbc:mysql://localhost:3306/mydatabase", driver="com.mysql.jdbc.Driver", dbtable="mytable", user="root", password="password" ).load() 以上代码会读取名为"mydatabase"的MySQL数据库中的"mytable"表,并将其转换为DataFrame对象。 三、查看读取的数据 我们可以使用show()函数来查看读取的数据: python df.show() 四、对数据进行处理 读取并加载数据后,我们就可以对其进行处理了。例如,我们可以使用select()函数来选择特定的列: python df = df.select("column1", "column2") 我们也可以使用filter()函数来过滤数据: python df = df.filter(df.column1 > 10) 五、将处理后的数据保存到文件或数据库中 最后,我们可以使用write()函数将处理后的数据保存到文件或数据库中。例如,我们可以将数据保存到CSV文件中: python df.write.csv("output.csv") 或者将数据保存回原来的数据库: python df.write.jdbc(url="jdbc:mysql://localhost:3306/mydatabase", table="mytable", mode="overwrite") 以上就是将数据从SQL数据库导入到Spark中的全部流程。敲黑板,划重点啦!要知道,不同的数据库类型就像是不同口味的咖啡,它们可能需要各自的“咖啡伴侣”——也就是JDBC驱动程序。所以当你打算用read.jdbc()这个小工具去读取数据时,千万记得先检查一下,对应的驱动程序是否已经乖乖地安装好啦~ 总结一下,Spark提供了简单易用的API,让我们能够方便地将数据从各种数据源导入到Spark中进行处理和分析。无论是进行大规模数据处理还是复杂的数据挖掘任务,Spark都能提供强大的支持。希望这篇文章能对你有所帮助,让你更好地掌握Spark。
2023-12-24 19:04:25
162
风轻云淡-t
SeaTunnel
...L语法规则的演进与大数据时代下SQL技术的最新发展动态。近期,Apache Calcite项目发布了一项重大更新,增强了其SQL解析器和优化器的能力,为包括SeaTunnel在内的众多数据处理工具提供了更为强大和灵活的SQL支持。Calcite作为开源框架,致力于解决跨多个数据源和API的SQL兼容性和优化问题,这无疑将提升SeaTunnel用户编写复杂查询时的效率与准确性。 同时,业界对SQL标准的关注也在持续升温。最新的SQL:2016标准已扩展至涵盖更多高级特性,如窗口函数、递归查询等,这些新特性的逐步落地有望简化大数据处理中的复杂业务逻辑实现。因此,对于SeaTunnel的使用者而言,掌握SQL新特性的应用不仅能有效避免语法错误,更能助力其实现高效的数据集成与处理。 此外,随着云原生技术和Kubernetes容器编排系统的普及,SeaTunnel也正积极拥抱这一趋势,通过整合云环境下的SQL服务,例如Azure Synapse Analytics、Amazon Athena等,以无缝对接云上数据库资源,并确保在大规模分布式环境下SQL查询执行的一致性和稳定性。这意味着,在未来,SeaTunnel用户不仅需要关注SQL查询语法本身,更需了解如何借助云平台能力来优化SQL作业性能,从而更好地适应不断变化的大数据生态系统。
2023-05-06 13:31:12
144
翡翠梦境
Kylin
如何配置Kylin以支持跨集群的数据源查询? 在大数据领域,Apache Kylin作为一款开源的分布式分析引擎,因其强大的OLAP能力与超高的查询性能而备受瞩目。不过在实际操作的时候,我们可能会遇到一个头疼的问题,那就是得从不同集群的数据源里查询信息。这就涉及到怎样巧妙地设置Kylin,让它能够帮我们搞定这个难题。本文将通过详尽的步骤和实例代码,带您逐步了解并掌握如何配置Kylin来支持跨集群的数据源查询。 1. 理解Kylin跨集群数据源查询 在开始配置之前,首先理解Kylin处理跨集群数据源查询的基本原理至关重要。Kylin的心脏就是构建Cube,这个过程其实就是在玩一场源数据的“预计算游戏”,把各种维度的数据提前捣鼓好,然后把这些多维度、经过深度整合的聚合结果,妥妥地存放在HBase这个大仓库里。所以,当我们想要实现不同集群间的查询互通时,重点就在于怎样让Kylin能够顺利地触及到各个集群的数据源头,并且在此基础之上成功构建出Cube。这就像是给Kylin装上一双可以跨越数据海洋的翅膀,让它在不同的数据岛屿之间自由翱翔,搭建起高效查询的桥梁。 2. 配置跨集群数据源连接 2.1 配置远程数据源连接 首先,我们需要在Kylin的kylin.properties配置文件中指定远程数据源的相关信息。例如,假设我们的原始数据位于一个名为“ClusterA”的Hadoop集群: properties kylin.source.hdfs-working-dir=hdfs://ClusterA:8020/user/kylin/ kylin.storage.hbase.rest-url=http://ClusterA:60010/ 这里,我们设置了HDFS的工作目录以及HBase REST服务的URL地址,确保Kylin能访问到ClusterA上的数据。 2.2 配置数据源连接器(JDBC) 对于关系型数据库作为数据源的情况,还需要配置相应的JDBC连接信息。例如,若ClusterB上有一个MySQL数据库: properties kylin.source.jdbc.url=jdbc:mysql://ClusterB:3306/mydatabase?useSSL=false kylin.source.jdbc.user=myuser kylin.source.jdbc.pass=mypassword 3. 创建项目及模型并关联远程表 接下来,在Kylin的Web界面创建一个新的项目,并在该项目下定义数据模型。在选择数据表时,Kylin会根据之前配置的HDFS和JDBC连接信息自动发现远程集群中的表。 - 创建项目:在Kylin管理界面点击"Create Project",填写项目名称和描述等信息。 - 定义模型:在新建的项目下,点击"Model" -> "Create Model",添加从远程集群引用的表,并设计所需的维度和度量。 4. 构建Cube并对跨集群数据进行查询 完成模型定义后,即可构建Cube。Kylin会在后台执行MapReduce任务,读取远程集群的数据并进行预计算。构建完成后,您便可以针对这个Cube进行快速、高效的查询操作,即使这些数据分布在不同的集群上。 bash 在Kylin命令行工具中构建Cube ./bin/kylin.sh org.apache.kylin.tool.BuildCubeCommand --cube-name MyCube --project-name MyProject --build-type BUILD 至此,通过精心配置和一系列操作,您的Kylin环境已经成功支持了跨集群的数据源查询。在这一路走来,我们不断挠头琢磨、摸石头过河、动手实践,不仅硬生生攻克了技术上的难关,更是让Kylin在各种复杂环境下的强大适应力和灵活应变能力展露无遗。 总结起来,配置Kylin支持跨集群查询的关键在于正确设置数据源连接,并在模型设计阶段合理引用这些远程数据源。每一次操作都像是人类智慧的一次小小爆发,每查询成功的背后,都是我们对Kylin功能那股子钻研劲儿和精心打磨的成果。在这整个过程中,我们实实在在地感受到了Kylin这款大数据处理神器的厉害之处,它带来的便捷性和无限可能性,真是让我们大开眼界,赞不绝口啊!
2023-01-26 10:59:48
83
月下独酌
Logstash
...ogstash与现代数据管道:适应与进阶》 在数字化时代,数据是企业决策、创新和竞争优势的核心。数据管道作为数据收集、处理和分析的关键基础设施,其效率和效能直接影响到企业的运营和战略规划。Logstash作为数据管道中的关键组件,其在数据收集、解析、过滤和分发方面的强大功能,使其在众多行业和领域中广泛应用。随着数据量的激增和数据处理需求的日益复杂,Logstash也在不断进化,以适应现代数据管理的挑战。 当前趋势与挑战 1. 实时数据处理的需求增长 在物联网、云计算和边缘计算的推动下,实时数据处理已成为常态。Logstash通过集成Kafka、Pulsar等实时消息队列系统,增强了其实时数据处理能力,帮助企业能够即时响应市场变化,提升决策速度和质量。 2. 多元化数据源的整合 企业数据来源越来越多样化,包括传统数据库、API接口、社交媒体、日志文件等。Logstash凭借其灵活的输入和输出插件体系,能够轻松对接不同数据源,实现数据的一体化管理和分析。 3. 安全合规与隐私保护 随着GDPR、CCPA等全球数据保护法规的实施,企业对数据安全和隐私保护的要求愈发严格。Logstash通过加密传输、数据脱敏等安全措施,确保数据在传输和处理过程中的安全性,帮助企业遵守法规要求,保护用户隐私。 4. 自动化与智能化升级 为了提高数据处理效率和智能化水平,Logstash引入了自动化脚本和机器学习算法,能够自动执行复杂的数据清洗、异常检测和预测分析任务,减少人工干预,提升数据分析的精度和速度。 结论 Logstash作为数据管道的核心组件,正逐步适应并引领现代数据管理的趋势。通过增强实时处理能力、优化多源数据整合、加强安全合规保障以及引入自动化与智能化技术,Logstash为企业提供了更高效、更安全、更智能的数据处理解决方案。未来,随着数据科学和人工智能技术的不断发展,Logstash有望在数据管道领域发挥更加重要的作用,助力企业实现数据驱动的创新与增长。 --- 本文深入探讨了Logstash在现代数据管道中的角色与发展趋势,强调了实时处理、数据源整合、安全合规和智能化升级四个关键方向。通过分析当前行业趋势和挑战,展示了Logstash如何通过技术创新和优化,满足企业在大数据时代的需求,为数据驱动的战略决策提供强有力的支持。
2024-09-15 16:15:13
151
笑傲江湖
Spark
...架,它提供了对大规模数据集进行高效、快速处理的能力。Spark通过内存计算技术显著提升了大数据处理速度,并支持SQL查询、流处理、机器学习等多种计算模型,能够在一个统一的平台上处理批处理和实时数据。 DataFrame API , DataFrame是Apache Spark中一种重要的编程抽象,类似于关系型数据库中的表结构。DataFrame API允许用户以更为直观且高性能的方式操作结构化数据。相较于RDD(弹性分布式数据集),DataFrame提供了更多的优化机会,包括列式存储、执行计划优化以及与SQL引擎的无缝集成,使得数据处理过程更加高效和便捷。 Partitioner , 在Apache Spark中,Partitioner是一个用于决定如何将数据集划分为多个分区的策略。它在数据并行处理时起到关键作用,确保数据能够在集群节点间均衡分布,提高任务执行效率。当处理大量小文件时,可以通过自定义Partitioner来按照某种规则将小文件整合或分类,从而减少I/O开销,提升整体性能。 DataSource V2 , DataSource V2是Apache Spark 3.0版本引入的新接口,旨在提供更灵活、高效的读写数据源方式。它允许开发者实现更细粒度的数据分区和读取策略,尤其适用于处理大量小文件场景,可以降低磁盘I/O次数,提高数据读取速度,进而优化Spark的整体性能。 动态资源分配 , 动态资源分配是Apache Spark的一项资源管理特性,可根据当前作业负载动态调整各个Spark应用程序所占用的集群资源(如CPU核心数、内存大小等)。在处理大量小文件等复杂工作负载时,合理运用动态资源分配策略有助于提高系统资源利用率和作业执行效率。
2023-09-19 23:31:34
45
清风徐来-t
Logstash
...csearch:实时数据处理的黄金搭档 嘿,朋友们!今天我要带大家走进一个非常有趣的技术领域——Logstash与Elasticsearch的结合。这俩在大数据处理界可是响当当的角色,特别是在实时索引优化这块,简直绝了!想象一下,你正面对着一大堆日志数据,每天都得迅速搞定它们的分析和查找,这时候,Logstash加上Elasticsearch简直就是你的超级英雄搭档,简直不要太好用! 1.1 什么是Logstash? Logstash 是一个开源的数据收集引擎,它能够从多个来源采集数据,然后进行转换,最后输出到各种存储系统中。它的设计初衷就是用来处理日志和事件数据的,但其实它的能力远不止于此。这家伙挺能来事儿的,不仅能搞定各种输入插件——比如文件啊、网页数据啊、数据库啥的,还能用过滤插件整点儿花样,比如说正则表达式匹配或者修改字段之类的。最后,它还支持不少输出插件,比如往Elasticsearch或者Kafka里面扔数据,简直不要太方便!这种灵活性使得Logstash成为了处理复杂数据流的理想选择。 1.2 Elasticsearch:实时搜索与分析的利器 Elasticsearch 是一个基于Lucene构建的开源分布式搜索引擎,它提供了强大的全文搜索功能,同时也支持结构化搜索、数值搜索以及地理空间搜索等多种搜索类型。此外,Elasticsearch还拥有出色的实时分析能力,这得益于其独特的倒排索引机制。当你将数据导入Elasticsearch后,它会自动对数据进行索引,从而大大提高了查询速度。 2. 实时索引优化 让数据飞起来 现在我们已经了解了Logstash和Elasticsearch各自的特点,接下来就让我们看看如何通过它们来实现高效的实时索引优化吧! 2.1 数据采集与预处理 首先,我们需要利用Logstash从各种数据源采集数据。好嘞,咱们换个说法:比如说,我们要从服务器的日志里挖出点儿有用的东西,就像找宝藏一样,目标就是那些访问时间、用户ID和请求的网址这些信息。我们可以用Filebeat这个工具来读取日志文件,然后再用Grok这个插件来解析这些数据,让信息变得更清晰易懂。下面是一个具体的配置示例: yaml input { file { path => "/var/log/nginx/access.log" start_position => "beginning" } } filter { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } } 这段配置告诉Logstash,从/var/log/nginx/access.log这个路径下的日志文件开始读取,并使用Grok插件中的COMBINEDAPACHELOG模式来解析每一行日志内容。这样子一来,原始的文本信息就被拆成了一个个有组织的小块儿,给接下来的处理铺平了道路,简直不要太方便! 2.2 高效索引策略 一旦数据被Logstash处理完毕,下一步就是将其导入Elasticsearch。为了确保索引操作尽可能高效,我们可以采取一些策略: - 批量处理:减少网络往返次数,提高吞吐量。 - 动态映射:允许Elasticsearch根据文档内容自动创建字段类型,简化索引管理。 - 分片与副本:合理设置分片数量和副本数量,平衡查询性能与集群稳定性。 下面是一个简单的Logstash输出配置示例,演示了如何将处理后的数据批量发送给Elasticsearch: yaml output { elasticsearch { hosts => ["localhost:9200"] index => "nginx-access-%{+YYYY.MM.dd}" document_type => "_doc" user => "elastic" password => "changeme" manage_template => false template => "/path/to/template.json" template_name => "nginx-access" template_overwrite => true flush_size => 5000 idle_flush_time => 1 } } 在这段配置中,我们设置了批量大小为5000条记录,以及空闲时间阈值为1秒,这意味着当达到这两个条件之一时,Logstash就会将缓冲区内的数据一次性发送至Elasticsearch。此外,我还指定了自定义的索引模板,以便更好地控制字段映射规则。 3. 实战案例 打造高性能日志分析平台 好了,理论讲得差不多了,接下来让我们通过一个实际的例子来看看这一切是如何运作的吧! 假设你是一家电商网站的运维工程师,最近你们网站频繁出现访问异常的问题,客户投诉不断。为了找出问题根源,你需要对Nginx服务器的日志进行深入分析。幸运的是,你们已经部署了Logstash和Elasticsearch作为日志处理系统。 3.1 日志采集与预处理 首先,我们需要确保Logstash能够正确地从Nginx服务器上采集到所有相关的日志信息。根据上面说的设置,我们可以搞一个Logstash配置文件,用来从特定的日志文件里扒拉出重要的信息。嘿,为了让大家看日志的时候能更轻松明了,我们可以加点小技巧,比如说统计每个用户逛网站的频率,或者找出那些怪怪的访问模式啥的。这样一来,信息就一目了然啦! 3.2 索引优化与查询分析 接下来,我们将这些处理后的数据发送给Elasticsearch进行索引存储。有了合适的索引设置,就算同时来一大堆请求,我们的查询也能嗖嗖地快,不会拖泥带水的。比如说,在上面那个输出配置的例子里面,我们调高了批量处理的门槛,同时把空闲时间设得比较短,这样就能大大加快数据写入的速度啦! 一旦数据被成功索引,我们就可以利用Elasticsearch的强大查询功能来进行深度分析了。比如说,你可以写个DSL查询,找出最近一周内访问量最大的10个页面;或者,你还可以通过用户ID捞出某个用户的操作记录,看看能不能从中发现问题。 4. 结语 拥抱变化,不断探索 通过以上介绍,相信大家已经对如何使用Logstash与Elasticsearch实现高效的实时索引优化有了一个全面的认识。当然啦,技术这东西总是日新月异的,所以我们得保持一颗好奇的心,不停地学新技术,这样才能更好地迎接未来的各种挑战嘛! 希望这篇文章能对你有所帮助,如果你有任何疑问或建议,欢迎随时留言交流。让我们一起加油,共同成长!
2024-12-17 15:55:35
41
追梦人
Apache Atlas
随着大数据技术的发展,我们每天都在生成海量的数据。这些数据全方位地记录了咱们日常生活、工作奋斗、学习进步的点点滴滴,帮咱们挖出了不少有价值的信息宝藏,让咱们看得更深更透彻。不过呢,特别是在面对海量数据的时候,如何把它们处理得既快又准,这确实是我们现在急需解决的一道大难题啊! 本文将介绍一种名为Apache Atlas的技术,它能够有效地解决大规模图表数据性能问题,并提供了一种最佳的实践方法。 一、Apache Atlas简介 Apache Atlas是一款企业级的大数据图谱解决方案,它可以帮助我们更好地管理和理解复杂的大规模数据。把数据串联起来,就像编织一张信息图谱一样,这样一来,我们就能更像看故事书那样,一目了然地瞧见各个数据点之间千丝万缕的联系,进而对它们进行更加接地气、细致入微的分析探索。 二、大规模图表数据性能问题 在处理大规模图表数据时,我们经常会遇到一些性能问题,如查询速度慢、存储空间不足等。这些问题不仅拖慢了我们有效利用数据的节奏,甚至可能变成一道坎儿,拦住我们深入挖掘、获得更多有价值的数据洞见。 三、Apache Atlas解决问题的方法 那么,Apache Atlas是如何帮助我们解决这些问题的呢?主要有以下几点: 1. 使用高效的图数据库 Apache Atlas使用了TinkerPop作为其底层的图数据库,这是一个高性能、可扩展的图数据库框架。用上TinkerPop这个神器,Apache Atlas就像装上了涡轮增压器,嗖嗖地在大规模数据查询中飞驰,让咱们的数据访问性能瞬间飙升,变得超级给力! 2. 提供灵活的数据模型 Apache Atlas提供了一个灵活的数据模型,允许我们根据需要自定义图谱中的节点和边的属性。这样一来,我们就能在不扩容存储空间的前提下,灵活应对各种场景下的数据需求啦。 3. 支持多种数据源 Apache Atlas支持多种数据源,包括Hadoop、Hive、Spark等,这使得我们可以从多个角度理解和管理我们的数据。 四、Apache Atlas的实践应用 接下来,我们将通过一个实际的例子来展示Apache Atlas的应用。 假设我们需要对一组用户的行为数据进行分析。这些数据分布在多个不同的系统中,包括Hadoop HDFS、Hive和Spark SQL。我们想要构建一个图谱,表示用户和他们的行为之间的关系。 首先,我们需要创建一个图模型,定义用户和行为两个节点类型以及它们之间的关系。然后,我们使用Apache Atlas提供的API,将这些数据导入到图数据库中。最后,我们就可以通过查询图谱,得到我们想要的结果了。 这就是Apache Atlas的一个简单应用。用Apache Atlas,我们就能轻轻松松地管理并解析那些海量的图表数据,这样一来,工作效率嗖嗖地提升,简直不要太方便! 五、总结 总的来说,Apache Atlas是一个强大的工具,可以帮助我们有效地解决大规模图表数据性能问题。无论你是大数据的初学者,还是经验丰富的专业人士,都可以从中受益。嘿,真心希望这篇文章能帮到你!如果你有任何疑问、想法或者建议,千万别客气,随时欢迎来找我聊聊哈!
2023-06-03 23:27:41
472
彩虹之上-t
SeaTunnel
...实战 1. 引言 在数据集成和ETL的世界里,SeaTunnel(原名Waterdrop)作为一款强大的实时、批处理开源大数据工具,深受开发者喜爱。嘿,你知道吗?当你在捣鼓Parquet或者CSV这些不同格式的文件时,有时候真的会冒出一些让人措手不及的解析小插曲来呢!本文将深入探讨这类问题的成因,并通过丰富的代码实例演示如何在SeaTunnel中妥善解决这些问题。 2. Parquet/CSV文件解析常见问题及其原因 2.1 数据类型不匹配 Parquet和CSV两种格式对于数据类型的定义和处理方式有所不同。比如,你可能会遇到这么个情况,在CSV文件里,某个字段可能被不小心认作是文本串了,但是当你瞅到Parquet文件的时候,嘿,这个同样的字段却是个整数类型。这种类型不匹配可能导致解析错误。 python 假设在CSV文件中有如下数据 id,name "1", "John" 而在Parquet文件结构中,id字段是int类型 (id:int, name:string) 2.2 文件格式规范不一致 Parquet和CSV对空值、日期时间格式等有着各自的约定。如CSV中可能用“null”、“N/A”表示空值,而Parquet则以二进制标记。若未正确配置解析规则,就会出现错误。 3. 利用SeaTunnel解决文件格式解析错误 3.1 配置数据源与转换规则 在SeaTunnel中,我们可以精细地配置数据源和转换规则以适应各种场景。下面是一个示例,展示如何在读取CSV数据时指定字段类型: yaml source: type: csv path: 'path/to/csv' schema: - name: id type: integer - name: name type: string transform: - type: convert fields: - name: id type: int 对于Parquet文件,SeaTunnel会自动根据Parquet文件的元数据信息解析字段类型,无需额外配置。 3.2 自定义转换逻辑处理特殊格式 当遇到非标准格式的数据时,我们可以使用自定义转换插件来处理。例如,处理CSV中特殊的空值表示: yaml transform: - type: script lang: python script: | if record['name'] == 'N/A': record['name'] = None 4. 深度思考与讨论 处理Parquet和CSV文件解析错误的过程其实也是理解并尊重每种数据格式特性的过程。SeaTunnel以其灵活且强大的数据处理能力,帮助我们在面对这些挑战时游刃有余。但是同时呢,我们也要时刻保持清醒的头脑,像侦探一样敏锐地洞察可能出现的问题。针对这些问题,咱们得接地气儿,结合实际业务的具体需求,灵活定制出解决问题的方案来。 5. 结语 总之,SeaTunnel在应对Parquet/CSV文件格式解析错误上,凭借其强大的数据源适配能力和丰富的转换插件库,为我们提供了切实可行的解决方案。经过实战演练和持续打磨,我们能够更溜地玩转各种数据格式,确保数据整合和ETL过程一路绿灯,畅通无阻。所以,下次你再遇到类似的问题时,不妨试试看借助SeaTunnel这个好帮手,让数据处理这件事儿变得轻轻松松,更加贴近咱们日常的使用习惯,更有人情味儿。
2023-08-08 09:26:13
76
心灵驿站
Apache Atlas
元数据管理 , 元数据管理是对数据集、数据源或信息系统中结构化信息的描述性数据进行组织、存储、维护和检索的过程。在本文上下文中,Apache Atlas通过统一收集、整合和分析大数据生态系统的元数据,提供了一种企业级的解决方案,帮助用户更好地理解数据资产的来源、含义、关系以及变更历史等重要信息。 数据血缘追踪 , 数据血缘追踪是一种跟踪数据从源头到最终使用过程的技术方法,它揭示了数据在整个系统中的流转路径和处理过程。在实际应用中,Apache Atlas能够记录并展示数据在不同阶段的转换和流动情况,便于用户在面临数据问题时快速定位问题源头,评估影响范围,并据此制定相应的修复策略。 数据治理 , 数据治理是指企业为确保数据质量、安全性和合规性而建立的一系列政策、流程、标准和度量体系。借助Apache Atlas这类元数据管理工具,企业能够实现更精细的数据资产管理与控制,包括但不限于数据生命周期管理、数据权限管理、数据质量和一致性维护,从而提升整体数据价值,并满足日益严格的数据法规要求。
2023-05-17 13:04:02
438
昨夜星辰昨夜风
Logstash
...序与预期不符 在处理数据流时,Logstash 是一个强大的工具,它允许我们通过配置文件来定义数据处理流程。哎呀,你懂的,有时候在用那些管道干活的时候,会出现程序跑的顺序跟我们想象的不一样,挺烦人的。这事儿啊,可能是咱配置的时候马虎了,也可能是那个插件的优先级设置得不对头,或者是程序里的逻辑太复杂,让人摸不着头脑。总之,这种情况挺常见的,得好好找找原因,对症下药才行。本文将深入探讨这个问题,并提供解决策略。 一、理解Logstash管道 Logstash 的核心概念是管道,它由三个主要部分组成:输入(Input)、过滤器(Filter)和输出(Output)。输入负责从数据源读取数据,过滤器对数据进行清洗、转换等操作,而输出则将处理后的数据发送到目的地。 二、配置文件的重要性 配置文件是Logstash的核心,其中包含了所有输入、过滤器和输出的定义以及它们之间的连接方式。正确理解并编写配置文件是避免管道执行顺序问题的关键。 三、常见问题及解决策略 1. 配置顺序影响 - 问题:假设我们有一个包含多个过滤器的管道,每个过滤器都依赖于前一个过滤器的结果。如果配置顺序不当,可能会导致某些过滤器无法正确接收到数据。 - 解决策略: - 确保每个过滤器在配置文件中的位置能够反映其执行顺序。好嘞,咱们换个说法,听起来更接地气些。比如,想象一下,如果你想要吃人家煮的面,那得先等人家把面煮好啊,对吧?所以,如果A需要B的结果,那B就得提前准备好,要么和A同时开始,这样A才能用上B的结果,对不? - 使用 Logstash 的 logstash-filter 插件,可以设置过滤器的依赖关系,确保按正确的顺序执行。 2. 插件优先级 - 问题:当两个或多个插件执行相同操作时,优先级决定哪个插件会先执行。 - 解决策略: - 在 Logstash 配置文件中明确指定插件的顺序,优先级高的插件会先执行。 - 使用 logstash-filter 插件中的 if 条件语句,动态选择执行哪个过滤器。 3. 复杂的逻辑处理 - 问题:当管道内包含复杂的逻辑判断和条件执行时,可能会因为条件未被正确满足而导致执行顺序混乱。 - 解决策略: - 清晰地定义每个过滤器的逻辑,确保每个条件都经过仔细考虑和测试。 - 使用日志记录功能,跟踪数据流和过滤器执行情况,以便于调试和理解执行顺序。 四、示例代码 以下是一个简单的 Logstash 示例配置文件,展示了如何配置管道执行顺序: yaml input { beats { port => 5044 } } filter { if "event" in [ "error", "warning" ] { grok { match => { "message" => "%{GREEDYDATA:time} %{GREEDYDATA:facility} %{GREEDYDATA:level} %{GREEDYDATA:message}" } } } else { grok { match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{WORD:facility} %{NUMBER:level} %{GREEDYDATA:message}" } } } } output { stdout {} } 在这个示例中,我们根据事件类型的不同(错误或警告),使用不同的解析模式来处理日志信息。这种逻辑判断确保了数据处理的顺序性和针对性。 五、总结 解决 Logstash 管道执行顺序问题的关键在于仔细规划配置文件,确保逻辑清晰、顺序合理。哎呀,你知道吗?用那些插件里的高级功能,比如条件判断和管理依赖,就像有了魔法一样,能让我们精准掌控数据怎么走,哪儿该停,哪儿该转,超级方便!就像是给程序穿上了智能衣,它就能聪明地知道什么时候该做什么了,是不是感觉更鲜活、更有个性了呢?哎呀,你懂的,在实际操作中,咱们得经常去试错和微调设置,就像厨师做菜一样,边尝边改,才能找到那个最对味的秘方。这样做的好处可大了,能帮咱们揪出那些藏在角落里的小问题,还能让整个过程变得更加流畅,效率蹭蹭往上涨,你说是不是?
2024-09-26 15:39:34
70
冬日暖阳
Saiku
...表工具之后,我们发现数据可视化与分析领域正在不断取得新的突破。近日,Apache Superset——另一个开源的数据可视化平台,也因其灵活、可扩展的特性及丰富的图表类型获得了业界的关注。Superset支持实时数据分析和多维数据集探索,且同样具备友好的用户界面,让用户无需编码即可创建美观且信息量大的仪表板。 同时,随着大数据时代的到来,企业对于数据分析的需求日益增强,全球众多公司正致力于研发更为高效便捷的报表工具。例如,Tableau和Power BI等商业解决方案也在持续更新迭代,提供AI驱动的智能洞察,以及无缝集成各种云服务的能力,以帮助企业更好地利用数据进行决策。 此外,针对Saiku使用者可能关心的开源社区动态,近期Saiku开发者团队宣布了新版本的重大更新,其中包括对更多数据源的支持、性能优化以及用户体验的进一步提升。这些进展不仅印证了Saiku坚持创新的决心,也为广大用户带来了更加强大、易用的报表构建体验。 总的来说,在当前的大数据环境下,无论是开源工具如Saiku和Apache Superset,还是商业产品如Tableau和Power BI,都在不断推动报表和数据分析技术的发展,为企业数字化转型提供了有力支撑。而掌握并有效运用这些工具,无疑将助力企业和个人在信息时代中占据竞争优势。
2023-02-10 13:43:51
119
幽谷听泉-t
Superset
在深入理解如何在Superset中创建新的数据源之后,我们发现高效的数据接入和管理对于数据分析工作至关重要。事实上,随着大数据和云计算技术的飞速发展,数据源管理工具的选择与应用正成为各行业数字化转型中的热点话题。近期,Apache Superset社区持续活跃,不断推出新功能以满足用户更复杂多样的需求。 例如,最新版本的Superset已支持更多种类的数据源,包括但不限于Amazon Redshift、Google BigQuery、Snowflake等云数据库服务,这无疑拓宽了用户在混合云或多云环境下的数据集成能力。同时,Superset也在提升安全性方面有所作为,如通过增强SQL Lab的安全策略来保护敏感数据,并优化元数据库管理机制,使得大规模企业级部署更为稳健可靠。 此外,针对现代数据分析工作中实时性要求的提高,Superset也正在积极整合流处理平台,如Kafka、Flink等,以实现对实时数据流的可视化分析。这意味着,在不久的将来,用户可能可以直接在Superset中配置实时数据源,进一步丰富其在业务监控、风险预警等方面的应用场景。 综上所述,掌握Superset数据源管理的基础操作只是第一步,持续关注该领域的技术动态和发展趋势,将有助于我们更好地利用这一强大工具,挖掘数据背后的深层价值,赋能企业决策与创新。
2023-06-10 10:49:30
75
寂静森林
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
cut -d ',' -f 1,3 file.csv
- 根据逗号分隔符提取csv文件中第1列和第3列的内容。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"