前端技术
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
[ http服务拦截器用于身份验证的实例研...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
Beego
...WT允许你在不依赖于服务器端会话的情况下验证用户身份,非常适合微服务架构。 - 示例代码: go package main import ( "github.com/astaxie/beego" "github.com/dgrijalva/jwt-go" "net/http" "time" ) var jwtSecret = []byte("your_secret_key") type Claims struct { Username string json:"username" jwt.StandardClaims } func loginHandler(c beego.Context) { username := c.Input().Get("username") password := c.Input().Get("password") // 这里应该有验证用户名和密码的逻辑 token := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{ Username: username, StandardClaims: jwt.StandardClaims{ ExpiresAt: time.Now().Add(time.Hour 72).Unix(), }, }) tokenString, err := token.SignedString(jwtSecret) if err != nil { c.Ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError) return } c.Data[http.StatusOK] = []byte(tokenString) } func authMiddleware() beego.ControllerFunc { return func(c beego.Controller) { tokenString := c.Ctx.Request.Header.Get("Authorization") token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token jwt.Token) (interface{}, error) { return jwtSecret, nil }) if claims, ok := token.Claims.(Claims); ok && token.Valid { // 将用户信息存储在session或者全局变量中 c.SetSession("user", claims.Username) c.Next() } else { c.Ctx.ResponseWriter.WriteHeader(http.StatusUnauthorized) } } } 3. 中间件与拦截器 - 利用Beego的中间件机制,我们可以为特定路由添加权限检查逻辑,从而避免重复编写相同的权限校验代码。 - 示例代码: go func AuthRequiredMiddleware() beego.ControllerFunc { return func(c beego.Controller) { if !c.GetSession("user").(string) { c.Redirect("/login", 302) return } c.Next() } } func init() { beego.InsertFilter("/admin/", beego.BeforeRouter, AuthRequiredMiddleware) } 四、实际应用案例分析 让我们来看一个具体的例子,假设我们正在开发一款在线教育平台,需要对不同类型的用户(学生、教师、管理员)提供不同的访问权限。例如,只有管理员才能删除课程,而学生只能查看课程内容。 1. 定义用户类型 - 我们可以通过枚举类型来表示不同的用户角色。 - 示例代码: go type UserRole int const ( Student UserRole = iota Teacher Admin ) 2. 实现权限验证逻辑 - 在每个需要权限验证的操作之前,我们都需要先判断当前登录用户是否具有相应的权限。 - 示例代码: go func deleteCourse(c beego.Controller) { if userRole := c.GetSession("role"); userRole != Admin { c.Ctx.ResponseWriter.WriteHeader(http.StatusForbidden) return } // 执行删除操作... } 五、总结与展望 通过上述讨论,我们已经了解了如何在Beego框架下实现基本的用户权限管理系统。当然,实际应用中还需要考虑更多细节,比如异常处理、日志记录等。另外,随着业务越做越大,你可能得考虑引入一些更复杂的权限管理系统了,比如可以根据不同情况灵活调整的权限分配,或者可以精细到每个小细节的权限控制。这样能让你的系统管理起来更灵活,也更安全。 最后,我想说的是,无论采用哪种方法,最重要的是始终保持对安全性的高度警惕,并不断学习最新的安全知识和技术。希望这篇文章能对你有所帮助! --- 希望这样的风格和内容符合您的期待,如果有任何具体需求或想要进一步探讨的部分,请随时告诉我!
2024-10-31 16:13:08
166
初心未变
转载文章
...ider是一种特殊的服务类型,用于在应用启动阶段配置和提供服务。它是最基础的服务创建者,可以通过provider定义、配置并返回一个对象,该对象在运行时被注入到其他组件中使用。其中,Value、Constant、Service和Factory是基于Provider的四种不同实现方式,分别适用于存储静态值、不可更改的常量、单例服务以及可执行函数返回的服务实例。 Single Page Application (SPA) , Single Page Application是指一种Web应用程序开发模式,用户在一个网页加载后不再需要刷新整个页面即可与服务器进行交互获取数据更新界面内容。在AngularJS Routing and Templating一文中提到的SPA技术,允许开发者通过路由(Routing)功能实现在单一网页内按需加载不同的视图模板,从而构建出类似桌面应用般的流畅用户体验。 OAuth , OAuth是一个开放标准授权协议,允许第三方应用在用户的授权下访问其存储在另外一方服务提供商的数据,而无需暴露用户的账号密码。在\ How to Implement Safe Sign-In via OAuth\ 这篇文章中,OAuth作为安全登录机制被应用于AngularJS应用中,使得用户可以安全地通过社交账号或其他身份验证服务提供商进行登录认证。 $http Interceptor , 在AngularJS中,$http Interceptor是一个拦截器机制,它允许开发者在$http服务发送请求或接收响应时插入自定义处理逻辑。这意味着可以在所有HTTP请求/响应生命周期中添加全局的预处理操作,如添加请求头、统一错误处理、身份验证令牌管理等。通过$http Interceptor,开发者能够更高效地管理和控制应用程序中的网络通信行为。 JSON Web Tokens (JWT) , JSON Web Tokens是一种开放的标准(RFC 7519),用来在各方之间安全地传输信息。JWT通常用于身份验证,它是一个经过数字签名的JSON对象,包含用户的身份信息以及其他声明(claims)。在\ Simple AngularJS Authentication with JWT\ 文章中,JWT用于实现AngularJS应用的身份验证流程,当用户成功登录后,服务器会生成一个JWT并将其返回给客户端,客户端利用$http Interceptor将JWT添加至后续请求的Authorization头部,以便于服务器端验证用户身份并确保资源的安全访问。
2023-06-14 12:17:09
213
转载
SpringBoot
...。这时候我们可以使用拦截器(Interceptor)来进行处理。在 Spring MVC 这个大家伙里,拦截器可是个大忙人,它身影广泛地出现在各个角落。比如说吧,当我们要对用户权限进行验证时,或者要对系统性能进行实时监控时,都离不开这位“幕后英雄”——拦截器的鼎力相助。本文将详细介绍 SpringBoot 如何实现自定义的拦截器。 二、自定义拦截器的原理 首先我们需要了解一下什么是拦截器。在Spring MVC这个大家伙里,拦截器就像是个扮演关键角色的小家伙,它其实就是一个实实在在的类,不过这个类得乖乖实现HandlerInterceptor接口,这样才能上岗工作。当我们发送一个 HTTP 请求给 Spring MVC 处理时,拦截器会对这个请求进行拦截,并根据我们的业务逻辑决定是否继续执行下一个拦截器或者 Controller。 三、自定义拦截器的实现步骤 接下来我们将一步步介绍如何在 SpringBoot 中实现自定义的拦截器。 1. 创建自定义拦截器实现 HandlerInterceptor 接口 java public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 这里可以根据需要进行预处理操作 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 这里可以在处理完成后进行后处理操作 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 这里可以在处理完成且没有异常发生的情况下进行后续操作 } } 2. 需要一个配置类实现 WebMvcConfigurer 接口,并添加@Configuration注解 java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()); } } 3. 在配置类中重写 addInterceptors 方法,将自定义拦截器添加到拦截器链中 java @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/"); // 添加拦截器路径匹配规则 } 四、自定义拦截器的应用场景 下面我们来看几个常见的应用场景。 1. 权限验证 java public class AuthInterceptor implements HandlerInterceptor { private List allowedRoles = Arrays.asList("admin", "manager"); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String username = (String) SecurityContextHolder.getContext().getAuthentication().getName(); if (!allowedRoles.contains(username)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return false; } return true; } } 在这个例子中,我们在 preHandle 方法中获取了当前用户的用户名,然后检查他是否有权访问这个资源。如果没有,则返回 403 Forbidden 错误。 2. 记录请求日志 java public class LogInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long start = System.currentTimeMillis(); System.out.println("开始处理请求:" + request.getRequestURL() + ",参数:" + request.getParameterMap()); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { long end = System.currentTimeMillis(); System.out.println("结束处理请求:" + request.getRequestURL() + ",耗时:" + (end - start)); } } 在这个例子中,我们在 preHandle 和 afterCompletion 方法中分别记录了请求开始时间和结束时间,并打印了相关的信息。 3. 判断用户是否登录 java public class LoginInterceptor implements HandlerInterceptor { private User user; public LoginInterceptor(User user) { this.user = user; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (user != null) { return true; } else { response.sendRedirect("/login"); return false; } } } 在这个例子中,我们在 preHandle 方法中判断用户是否已经登录,如果没有,则跳转到登录页面。 总结 以上就是如何在 SpringBoot 中实现自定义的拦截器。拦截器是一个非常强大的功能,可以帮助我们解决很多复杂的问题。但是伙计们,你们得留意了,过度依赖拦截器这玩意儿,可能会让代码变得乱七八糟、一团乱麻,维护起来简直能让你头疼欲裂。所以呐,咱们一定要悠着点用,合理利用这个小工具才是正解。希望这篇文章对你有所帮助!
2023-02-28 11:49:38
153
星河万里-t
VUE
HTTP 401错误 , HTTP 401错误是一种HTTP状态码,表示客户端请求需要用户认证。当客户端向服务器发送请求时,如果服务器要求进行用户身份验证,但客户端未能提供有效的认证信息,服务器将返回401错误。这种错误通常出现在用户未登录或登录信息已过期的情况下,提示客户端需要进行身份验证才能访问特定资源。 axios , axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js环境。它可以在Vue项目中用来发起HTTP请求。axios提供了一些强大的功能,如拦截器,允许开发者在请求发送前或响应接收后对请求进行处理。拦截器使得开发者可以在全局范围内处理诸如错误处理、请求头设置等问题,而无需在每个请求中重复编写相同的代码。 路由 , 在Vue项目中,路由指的是管理应用内部页面导航的功能。通过使用Vue Router,开发者可以定义不同的视图组件以及它们之间的映射关系。路由还允许开发者传递参数,如查询参数和动态路由参数,以便在用户点击链接或通过编程方式导航到不同页面时,可以携带必要的信息。在本文中,路由被用来处理用户登录后返回到之前访问的页面的需求。
2025-01-23 15:55:50
29
灵动之光
转载文章
...转载内容。原文链接:https://mohen.blog.csdn.net/article/details/123495342。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 目录 劫持 detours 实现劫持 步骤: 1. 安装Detours 2. 编译Detours工程 3. 把静态库和头文件引入工程 4. 函数指针与函数的定义 5.拦截 劫持QQ 实现劫持system函数。 1. 设置项目生成dll 2. 源文件(注意:需要保存为.c文件,或者加上extern C,因为detours是使用C语言实现的,表示代码使用C的规则进行编译) 3. 生成"劫持1.dll"文件 4. 把dll注入到QQ.exe 5. 拦截QQ执行system函数 参考 劫持 劫持的原理就是把目标函数的指针的指向修改为自定义函数的地址。 函数是放在内存中的代码区,所以劫持与代码区密切相关。 实现劫持需要使用detours。 detours detours是微软亚洲研究院出口的信息安全产品,主要用于劫持。这个工具使用C语言实现,所以是跨平台的。 detours根据函数指针改变函数的行为,可以拦截任何函数,即使操作系统函数。 detours下载地址: 下载地址1: http://research.microsoft.com/en-us/downloads/d36340fb-4d3c-4ddd-bf5b-1db25d03713d/default.aspx 下载地址2: http://pan.baidu.com/s/1eQEijtS 实现劫持 开发环境说明:win7、vs2012 步骤: 1. 安装Detours 2. 编译Detours工程 在安装目录C:\Program Files\Microsoft Research\Detours Express 3.0\src目录下的是工程的源文件。 (1) 打开VS2012命令行工具,进入src目录。 (2) 使用nmake(linux下是make)命令编译生成静态库。 (3) 在lib.x86目录下的.lib文件是win32平台下的静态库文件 (4) 在include目录下的是Detours工程的头文件 3. 把静态库和头文件引入工程 // 引入detours头文件include "detours.h"// 引入detours.lib静态库pragma comment(lib,"detours.lib") 4. 函数指针与函数的定义 (1) 定义一个函数指针指向目标函数,这里目标函数是system 例如: detour在realse模式生效(因为VS在Debug模式下已经把程序中的函数劫持了) static int ( oldsystem)(const char _Command) = system;//定义一个函数指针指向目标函数 (2) 定义与目标函数原型相同的函数替代目标函数 例如: //3.定义新的函数替代目标函数,需要与目标函数的原型相同int newsystem(const char _Command){int result = MessageBoxA(0,"是否允许该程序调用system命令","提示",1);//printf("result = %d", result);if (result == 1){oldsystem(_Command); //调用旧的函数}else{MessageBoxA(0,"终止调用system命令","提示",0);}return 0;} 5.拦截 //开始拦截void Hook(){DetourRestoreAfterWith();//恢复原来状态(重置)DetourTransactionBegin();//拦截开始DetourUpdateThread(GetCurrentThread());//刷新当前线程(刷新生效)//这里可以连续多次调用DetourAttach,表明HOOK多个函数DetourAttach((void )&oldsystem, newsystem);//实现函数拦截DetourTransactionCommit();//拦截生效} //取消拦截void UnHook(){DetourTransactionBegin();//拦截开始DetourUpdateThread(GetCurrentThread());//刷新当前线程//这里可以连续多次调用DetourDetach,表明撤销多个函数HOOKDetourDetach((void )&oldsystem, newsystem); //撤销拦截函数DetourTransactionCommit();//拦截生效} 劫持QQ 实现劫持system函数。 1. 设置项目生成dll 2. 源文件(注意:需要保存为.c文件,或者加上extern C,因为detours是使用C语言实现的,表示代码使用C的规则进行编译) include include include // 引入detours头文件include "detours.h"//1.引入detours.lib静态库pragma comment(lib,"detours.lib")//2.定义函数指针static int ( oldsystem)(const char _Command) = system;//定义一个函数指针指向目标函数//3.定义新的函数替代目标函数,需要与目标函数的原型相同int newsystem(const char _Command){char cmd[100] = {0};int result = 0;sprintf_s(cmd,100, "是否允许该程序执行%s指令", _Command);result = MessageBoxA(0,cmd,"提示",1);//printf("result = %d", result);if (result == 1) // 允许调用{oldsystem(_Command); //调用旧的函数}else{// 不允许调用}return 0;}// 4.拦截//开始拦截_declspec(dllexport) void Hook() // _declspec(dllexport)表示外部可调用,需要加上该关键字其它进程才能成功调用该函数{DetourRestoreAfterWith();//恢复原来状态(重置)DetourTransactionBegin();//拦截开始DetourUpdateThread(GetCurrentThread());//刷新当前线程(刷新生效)//这里可以连续多次调用DetourAttach,表明HOOK多个函数DetourAttach((void )&oldsystem, newsystem);//实现函数拦截DetourTransactionCommit();//拦截生效}//取消拦截_declspec(dllexport) void UnHook(){DetourTransactionBegin();//拦截开始DetourUpdateThread(GetCurrentThread());//刷新当前线程//这里可以连续多次调用DetourDetach,表明撤销多个函数HOOKDetourDetach((void )&oldsystem, newsystem); //撤销拦截函数DetourTransactionCommit();//拦截生效}// 劫持别人的程序:通过DLL注入,并调用Hook函数实现劫持。// 劫持系统:通过DLL注入系统程序(如winlogon.exe)实现劫持系统函数。_declspec(dllexport) void main(){Hook(); // 拦截system("tasklist"); //弹出提示框UnHook(); // 解除拦截system("ipconfig"); //成功执行system("pause"); // 成功执行} 3. 生成"劫持1.dll"文件 4. 把dll注入到QQ.exe DLL注入工具下载: https://coding.net/u/linchaolong/p/DllInjector/git/raw/master/Xenos.exe (1) 打开dll注入工具,点击add,选择"劫持1.dll" (2) 在Process中选择QQ.exe,点击Inject进行注入。 (3) 点击菜单栏Tools,选择Eject modules显示当前QQ.exe进程中加载的所有模块,如果有"劫持1.dll"表示注入成功。 5. 拦截QQ执行system函数 (1) 点击Advanced,在Init routine中填写动态库(dll)中的函数的名称,如Hook,然后点击Inject进行调用。此时,我们已经把system函数劫持了。 (2) 点击Advanced,在Init routine中填写main,执行动态库中的main函数。 此时,弹出一个对话框,问是否允许执行tasklist指令,表示成功把system函数拦截下来了。 参考 DLL注入工具源码地址: https://coding.net/u/linchaolong/p/DllInjector/git 说明: 该工具来自以下两个项目 Xenos: https://github.com/DarthTon/Xenos.git Blackbone: https://github.com/DarthTon/Blackbone 本篇文章为转载内容。原文链接:https://mohen.blog.csdn.net/article/details/123495342。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-23 19:22:06
352
转载
转载文章
...转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 注:本文是【ASP.NET Identity系列教程】的第三篇。本系列教程详细、完整、深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程能成为掌握ASP.NET Identity技术的一份完整而有价值的资料。读者若是能够按照文章的描述,一边阅读、一边实践、一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐。 15 Advanced ASP.NET Identity 15 ASP.NET Identity高级技术 In this chapter, I finish my description of ASP.NET Identity by showing you some of the advanced features it offers. I demonstrate how you can extend the database schema by defining custom properties on the user class and how to use database migrations to apply those properties without deleting the data in the ASP.NET Identity database. I also explain how ASP.NET Identity supports the concept of claims and demonstrates how they can be used to flexibly authorize access to action methods. I finish the chapter—and the book—by showing you how ASP.NET Identity makes it easy to authenticate users through third parties. I demonstrate authentication with Google accounts, but ASP.NET Identity has built-in support for Microsoft, Facebook, and Twitter accounts as well. Table 15-1 summarizes this chapter. 本章将完成对ASP.NET Identity的描述,向你展示它所提供的一些高级特性。我将演示,你可以扩展ASP.NET Identity的数据库架构,其办法是在用户类上定义一些自定义属性。也会演示如何使用数据库迁移,这样可以运用自定义属性,而不必删除ASP.NET Identity数据库中的数据。还会解释ASP.NET Identity如何支持声明(Claims)概念,并演示如何将它们灵活地用来对动作方法进行授权访问。最后向你展示ASP.NET Identity很容易通过第三方部件来认证用户,以此结束本章以及本书。将要演示的是使用Google账号认证,但ASP.NET Identity对于Microsoft、Facebook以及Twitter账号,都有内建的支持。表15-1是本章概要。 Table 15-1. Chapter Summary 表15-1. 本章概要 Problem 问题 Solution 解决方案 Listing 清单号 Store additional information about users. 存储用户的附加信息 Define custom user properties. 定义自定义用户属性 1–3, 8–11 Update the database schema without deleting user data. 更新数据库架构而不删除用户数据 Perform a database migration. 执行数据库迁移 4–7 Perform fine-grained authorization. 执行细粒度授权 Use claims. 使用声明(Claims) 12–14 Add claims about a user. 添加用户的声明(Claims) Use the ClaimsIdentity.AddClaims method. 使用ClaimsIdentity.AddClaims方法 15–19 Authorize access based on claim values. 基于声明(Claims)值授权访问 Create a custom authorization filter attribute. 创建一个自定义的授权过滤器注解属性 20–21 Authenticate through a third party. 通过第三方认证 Install the NuGet package for the authentication provider, redirect requests to that provider, and specify a callback URL that creates the user account. 安装认证提供器的NuGet包,将请求重定向到该提供器,并指定一个创建用户账号的回调URL。 22–25 15.1 Preparing the Example Project 15.1 准备示例项目 In this chapter, I am going to continue working on the Users project I created in Chapter 13 and enhanced in Chapter 14. No changes to the application are required, but start the application and make sure that there are users in the database. Figure 15-1 shows the state of my database, which contains the users Admin, Alice, Bob, and Joe from the previous chapter. To check the users, start the application and request the /Admin/Index URL and authenticate as the Admin user. 本章打算继续使用第13章创建并在第14章增强的Users项目。对应用程序无需做什么改变,但需要启动应用程序,并确保数据库中有一些用户。图15-1显示了数据库的状态,它含有上一章的用户Admin、Alice、Bob以及Joe。为了检查用户,请启动应用程序,请求/Admin/Index URL,并以Admin用户进行认证。 Figure 15-1. The initial users in the Identity database 图15-1. Identity数据库中的最初用户 I also need some roles for this chapter. I used the RoleAdmin controller to create roles called Users and Employees and assigned the users to those roles, as described in Table 15-2. 本章还需要一些角色。我用RoleAdmin控制器创建了角色Users和Employees,并为这些角色指定了一些用户,如表15-2所示。 Table 15-2. The Types of Web Forms Code Nuggets 表15-2. 角色及成员(作者将此表的标题写错了——译者注) Role 角色 Members 成员 Users Alice, Joe Employees Alice, Bob Figure 15-2 shows the required role configuration displayed by the RoleAdmin controller. 图15-2显示了由RoleAdmin控制器所显示出来的必要的角色配置。 Figure 15-2. Configuring the roles required for this chapter 图15-2. 配置本章所需的角色 15.2 Adding Custom User Properties 15.2 添加自定义用户属性 When I created the AppUser class to represent users in Chapter 13, I noted that the base class defined a basic set of properties to describe the user, such as e-mail address and telephone number. Most applications need to store more information about users, including persistent application preferences and details such as addresses—in short, any data that is useful to running the application and that should last between sessions. In ASP.NET Membership, this was handled through the user profile system, but ASP.NET Identity takes a different approach. 我在第13章创建AppUser类来表示用户时曾做过说明,基类定义了一组描述用户的基本属性,如E-mail地址、电话号码等。大多数应用程序还需要存储用户的更多信息,包括持久化应用程序爱好以及地址等细节——简言之,需要存储对运行应用程序有用并且在各次会话之间应当保持的任何数据。在ASP.NET Membership中,这是通过用户资料(User Profile)系统来处理的,但ASP.NET Identity采取了一种不同的办法。 Because the ASP.NET Identity system uses Entity Framework to store its data by default, defining additional user information is just a matter of adding properties to the user class and letting the Code First feature create the database schema required to store them. Table 15-3 puts custom user properties in context. 因为ASP.NET Identity默认是使用Entity Framework来存储其数据的,定义附加的用户信息只不过是给用户类添加属性的事情,然后让Code First特性去创建需要存储它们的数据库架构即可。表15-3描述了自定义用户属性的情形。 Table 15-3. Putting Cusotm User Properties in Context 表15-3. 自定义用户属性的情形 Question 问题 Answer 回答 What is it? 什么是自定义用户属性? Custom user properties allow you to store additional information about your users, including their preferences and settings. 自定义用户属性让你能够存储附加的用户信息,包括他们的爱好和设置。 Why should I care? 为何要关心它? A persistent store of settings means that the user doesn’t have to provide the same information each time they log in to the application. 设置的持久化存储意味着,用户不必每次登录到应用程序时都提供同样的信息。 How is it used by the MVC framework? 在MVC框架中如何使用它? This feature isn’t used directly by the MVC framework, but it is available for use in action methods. 此特性不是由MVC框架直接使用的,但它在动作方法中使用是有效的。 15.2.1 Defining Custom Properties 15.2.1 定义自定义属性 Listing 15-1 shows how I added a simple property to the AppUser class to represent the city in which the user lives. 清单15-1演示了如何给AppUser类添加一个简单的属性,用以表示用户生活的城市。 Listing 15-1. Adding a Property in the AppUser.cs File 清单15-1. 在AppUser.cs文件中添加属性 using System;using Microsoft.AspNet.Identity.EntityFramework;namespace Users.Models { public enum Cities {LONDON, PARIS, CHICAGO}public class AppUser : IdentityUser {public Cities City { get; set; } }} I have defined an enumeration called Cities that defines values for some large cities and added a property called City to the AppUser class. To allow the user to view and edit their City property, I added actions to the Home controller, as shown in Listing 15-2. 这里定义了一个枚举,名称为Cities,它定义了一些大城市的值,另外给AppUser类添加了一个名称为City的属性。为了让用户能够查看和编辑City属性,给Home控制器添加了几个动作方法,如清单15-2所示。 Listing 15-2. Adding Support for Custom User Properties in the HomeController.cs File 清单15-2. 在HomeController.cs文件中添加对自定义属性的支持 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models;namespace Users.Controllers {public class HomeController : Controller {[Authorize]public ActionResult Index() {return View(GetData("Index"));}[Authorize(Roles = "Users")]public ActionResult OtherAction() {return View("Index", GetData("OtherAction"));}private Dictionary<string, object> GetData(string actionName) {Dictionary<string, object> dict= new Dictionary<string, object>();dict.Add("Action", actionName);dict.Add("User", HttpContext.User.Identity.Name);dict.Add("Authenticated", HttpContext.User.Identity.IsAuthenticated);dict.Add("Auth Type", HttpContext.User.Identity.AuthenticationType);dict.Add("In Users Role", HttpContext.User.IsInRole("Users"));return dict;} [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;await UserManager.UpdateAsync(user);return View(user);}private AppUser CurrentUser {get {return UserManager.FindByName(HttpContext.User.Identity.Name);} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } I added a CurrentUser property that uses the AppUserManager class to retrieve an AppUser instance to represent the current user. I pass the AppUser object as the view model object in the GET version of the UserProps action method, and the POST method uses it to update the value of the new City property. Listing 15-3 shows the UserProps.cshtml view, which displays the City property value and contains a form to change it. 我添加了一个CurrentUser属性,它使用AppUserManager类接收了表示当前用户的AppUser实例。在GET版本的UserProps动作方法中,传递了这个AppUser对象作为视图模型。而在POST版的方法中用它更新了City属性的值。清单15-3显示了UserProps.cshtml视图,它显示了City属性的值,并包含一个修改它的表单。 Listing 15-3. The Contents of the UserProps.cshtml File in the Views/Home Folder 清单15-3. Views/Home文件夹中UserProps.cshtml文件的内容 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";}<div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr></table></div> @using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Caution Don’t start the application when you have created the view. In the sections that follow, I demonstrate how to preserve the contents of the database, and if you start the application now, the ASP.NET Identity users will be deleted. 警告:创建了视图之后不要启动应用程序。在以下小节中,将演示如何保留数据库的内容,如果现在启动应用程序,将会删除ASP.NET Identity的用户。 15.2.2 Preparing for Database Migration 15.2.2 准备数据库迁移 The default behavior for the Entity Framework Code First feature is to drop the tables in the database and re-create them whenever classes that drive the schema have changed. You saw this in Chapter 14 when I added support for roles: When the application was started, the database was reset, and the user accounts were lost. Entity Framework Code First特性的默认行为是,一旦修改了派生数据库架构的类,便会删除数据库中的数据表,并重新创建它们。在第14章可以看到这种情况,在我添加角色支持时:当重启应用程序后,数据库被重置,用户账号也丢失。 Don’t start the application yet, but if you were to do so, you would see a similar effect. Deleting data during development is usually not a problem, but doing so in a production setting is usually disastrous because it deletes all of the real user accounts and causes a panic while the backups are restored. In this section, I am going to demonstrate how to use the database migration feature, which updates a Code First schema in a less brutal manner and preserves the existing data it contains. 不要启动应用程序,但如果你这么做了,会看到类似的效果。在开发期间删除数据没什么问题,但如果在产品设置中这么做了,通常是灾难性的,因为它会删除所有真实的用户账号,而备份恢复是很痛苦的事。在本小节中,我打算演示如何使用数据库迁移特性,它能以比较温和的方式更新Code First的架构,并保留架构中的已有数据。 The first step is to issue the following command in the Visual Studio Package Manager Console: 第一个步骤是在Visual Studio的“Package Manager Console(包管理器控制台)”中发布以下命令: Enable-Migrations –EnableAutomaticMigrations This enables the database migration support and creates a Migrations folder in the Solution Explorer that contains a Configuration.cs class file, the contents of which are shown in Listing 15-4. 它启用了数据库的迁移支持,并在“Solution Explorer(解决方案资源管理器)”创建一个Migrations文件夹,其中含有一个Configuration.cs类文件,内容如清单15-4所示。 Listing 15-4. The Contents of the Configuration.cs File 清单15-4. Configuration.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration: DbMigrationsConfiguration<Users.Infrastructure.AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(Users.Infrastructure.AppIdentityDbContext context) {// This method will be called after migrating to the latest version.// 此方法将在迁移到最新版本时调用// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data. E.g.// 例如,你可以使用DbSet<T>.AddOrUpdate()辅助器方法来避免创建重复的种子数据//// context.People.AddOrUpdate(// p => p.FullName,// new Person { FullName = "Andrew Peters" },// new Person { FullName = "Brice Lambson" },// new Person { FullName = "Rowan Miller" }// );//} }} Tip You might be wondering why you are entering a database migration command into the console used to manage NuGet packages. The answer is that the Package Manager Console is really PowerShell, which is a general-purpose tool that is mislabeled by Visual Studio. You can use the console to issue a wide range of helpful commands. See http://go.microsoft.com/fwlink/?LinkID=108518 for details. 提示:你可能会觉得奇怪,为什么要在管理NuGet包的控制台中输入数据库迁移的命令?答案是“Package Manager Console(包管理控制台)”是真正的PowerShell,这是Visual studio冒用的一个通用工具。你可以使用此控制台发送大量的有用命令,详见http://go.microsoft.com/fwlink/?LinkID=108518。 The class will be used to migrate existing content in the database to the new schema, and the Seed method will be called to provide an opportunity to update the existing database records. In Listing 15-5, you can see how I have used the Seed method to set a default value for the new City property I added to the AppUser class. (I have also updated the class file to reflect my usual coding style.) 这个类将用于把数据库中的现有内容迁移到新的数据库架构,Seed方法的调用为更新现有数据库记录提供了机会。在清单15-5中可以看到,我如何用Seed方法为新的City属性设置默认值,City是添加到AppUser类中自定义属性。(为了体现我一贯的编码风格,我对这个类文件也进行了更新。) Listing 15-5. Managing Existing Content in the Configuration.cs File 清单15-5. 在Configuration.cs文件中管理已有内容 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models;namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);}foreach (AppUser dbUser in userMgr.Users) {dbUser.City = Cities.PARIS;}context.SaveChanges();} }} You will notice that much of the code that I added to the Seed method is taken from the IdentityDbInit class, which I used to seed the database with an administration user in Chapter 14. This is because the new Configuration class added to support database migrations will replace the seeding function of the IdentityDbInit class, which I’ll update shortly. Aside from ensuring that there is an admin user, the statements in the Seed method that are important are the ones that set the initial value for the City property I added to the AppUser class, as follows: 你可能会注意到,添加到Seed方法中的许多代码取自于IdentityDbInit类,在第14章中我用这个类将管理用户植入了数据库。这是因为这个新添加的、用以支持数据库迁移的Configuration类,将代替IdentityDbInit类的种植功能,我很快便会更新这个类。除了要确保有admin用户之外,在Seed方法中的重要语句是那些为AppUser类的City属性设置初值的语句,如下所示: ...foreach (AppUser dbUser in userMgr.Users) { dbUser.City = Cities.PARIS;}context.SaveChanges();... You don’t have to set a default value for new properties—I just wanted to demonstrate that the Seed method in the Configuration class can be used to update the existing user records in the database. 你不一定要为新属性设置默认值——这里只是想演示Configuration类中的Seed方法,可以用它更新数据库中的已有用户记录。 Caution Be careful when setting values for properties in the Seed method for real projects because the values will be applied every time you change the schema, overriding any values that the user has set since the last schema update was performed. I set the value of the City property just to demonstrate that it can be done. 警告:在用于真实项目的Seed方法中为属性设置值时要小心,因为你每一次修改架构时,都会运用这些值,这会将自执行上一次架构更新之后,用户设置的任何数据覆盖掉。这里设置City属性的值只是为了演示它能够这么做。 Changing the Database Context Class 修改数据库上下文类 The reason that I added the seeding code to the Configuration class is that I need to change the IdentityDbInit class. At present, the IdentityDbInit class is derived from the descriptively named DropCreateDatabaseIfModelChanges<AppIdentityDbContext> class, which, as you might imagine, drops the entire database when the Code First classes change. Listing 15-6 shows the changes I made to the IdentityDbInit class to prevent it from affecting the database. 在Configuration类中添加种植代码的原因是我需要修改IdentityDbInit类。此时,IdentityDbInit类派生于描述性命名的DropCreateDatabaseIfModelChanges<AppIdentityDbContext> 类,和你相像的一样,它会在Code First类改变时删除整个数据库。清单15-6显示了我对IdentityDbInit类所做的修改,以防止它影响数据库。 Listing 15-6. Preventing Database Schema Changes in the AppIdentityDbContext.cs File 清单15-6. 在AppIdentityDbContext.cs文件是阻止数据库架构变化 using System.Data.Entity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Models;using Microsoft.AspNet.Identity; namespace Users.Infrastructure {public class AppIdentityDbContext : IdentityDbContext<AppUser> {public AppIdentityDbContext() : base("IdentityDb") { }static AppIdentityDbContext() {Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());}public static AppIdentityDbContext Create() {return new AppIdentityDbContext();} } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> {} } I have removed the methods defined by the class and changed its base to NullDatabaseInitializer<AppIdentityDbContext> , which prevents the schema from being altered. 我删除了这个类中所定义的方法,并将它的基类改为NullDatabaseInitializer<AppIdentityDbContext> ,它可以防止架构修改。 15.2.3 Performing the Migration 15.2.3 执行迁移 All that remains is to generate and apply the migration. First, run the following command in the Package Manager Console: 剩下的事情只是生成并运用迁移了。首先,在“Package Manager Console(包管理器控制台)”中执行以下命令: Add-Migration CityProperty This creates a new migration called CityProperty (I like my migration names to reflect the changes I made). A class new file will be added to the Migrations folder, and its name reflects the time at which the command was run and the name of the migration. My file is called 201402262244036_CityProperty.cs, for example. The contents of this file contain the details of how Entity Framework will change the database during the migration, as shown in Listing 15-7. 这创建了一个名称为CityProperty的新迁移(我比较喜欢让迁移的名称反映出我所做的修改)。这会在文件夹中添加一个新的类文件,而且其命名会反映出该命令执行的时间以及迁移名称,例如,我的这个文件名称为201402262244036_CityProperty.cs。该文件的内容含有迁移期间Entity Framework修改数据库的细节,如清单15-7所示。 Listing 15-7. The Contents of the 201402262244036_CityProperty.cs File 清单15-7. 201402262244036_CityProperty.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity.Migrations; public partial class Init : DbMigration {public override void Up() {AddColumn("dbo.AspNetUsers", "City", c => c.Int(nullable: false));}public override void Down() {DropColumn("dbo.AspNetUsers", "City");} }} The Up method describes the changes that have to be made to the schema when the database is upgraded, which in this case means adding a City column to the AspNetUsers table, which is the one that is used to store user records in the ASP.NET Identity database. Up方法描述了在数据库升级时,需要对架构所做的修改,在这个例子中,意味着要在AspNetUsers数据表中添加City数据列,该数据表是ASP.NET Identity数据库用来存储用户记录的。 The final step is to perform the migration. Without starting the application, run the following command in the Package Manager Console: 最后一步是执行迁移。无需启动应用程序,只需在“Package Manager Console(包管理器控制台)”中运行以下命令即可: Update-Database –TargetMigration CityProperty The database schema will be modified, and the code in the Configuration.Seed method will be executed. The existing user accounts will have been preserved and enhanced with a City property (which I set to Paris in the Seed method). 这会修改数据库架构,并执行Configuration.Seed方法中的代码。已有用户账号会被保留,且增强了City属性(我在Seed方法中已将其设置为“Paris”)。 15.2.4 Testing the Migration 15.2.4 测试迁移 To test the effect of the migration, start the application, navigate to the /Home/UserProps URL, and authenticate as one of the Identity users (for example, as Alice with the password MySecret). Once authenticated, you will see the current value of the City property for the user and have the opportunity to change it, as shown in Figure 15-3. 为了测试迁移的效果,启动应用程序,导航到/Home/UserProps URL,并以Identity中的用户(例如Alice,口令MySecret)进行认证。一旦已被认证,便会看到该用户City属性的当前值,并可以对其进行修改,如图15-3所示。 Figure 15-3. Displaying and changing a custom user property 图15-3. 显示和个性自定义用户属性 15.2.5 Defining an Additional Property 15.2.5 定义附加属性 Now that database migrations are set up, I am going to define a further property just to demonstrate how subsequent changes are handled and to show a more useful (and less dangerous) example of using the Configuration.Seed method. Listing 15-8 shows how I added a Country property to the AppUser class. 现在,已经建立了数据库迁移,我打算再定义一个属性,这恰恰演示了如何处理持续不断的修改,也为了演示Configuration.Seed方法更有用(至少无害)的示例。清单15-8显示了我在AppUser类上添加了一个Country属性。 Listing 15-8. Adding Another Property in the AppUserModels.cs File 清单15-8. 在AppUserModels.cs文件中添加另一个属性 using System;using Microsoft.AspNet.Identity.EntityFramework; namespace Users.Models {public enum Cities {LONDON, PARIS, CHICAGO} public enum Countries {NONE, UK, FRANCE, USA}public class AppUser : IdentityUser {public Cities City { get; set; }public Countries Country { get; set; }public void SetCountryFromCity(Cities city) {switch (city) {case Cities.LONDON:Country = Countries.UK;break;case Cities.PARIS:Country = Countries.FRANCE;break;case Cities.CHICAGO:Country = Countries.USA;break;default:Country = Countries.NONE;break;} }} } I have added an enumeration to define the country names and a helper method that selects a country value based on the City property. Listing 15-9 shows the change I made to the Configuration class so that the Seed method sets the Country property based on the City, but only if the value of Country is NONE (which it will be for all users when the database is migrated because the Entity Framework sets enumeration columns to the first value). 我已经添加了一个枚举,它定义了国家名称。还添加了一个辅助器方法,它可以根据City属性选择一个国家。清单15-9显示了对Configuration类所做的修改,以使Seed方法根据City设置Country属性,但只当Country为NONE时才进行设置(在迁移数据库时,所有用户都是NONE,因为Entity Framework会将枚举列设置为枚举的第一个值)。 Listing 15-9. Modifying the Database Seed in the Configuration.cs File 清单15-9. 在Configuration.cs文件中修改数据库种子 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models; namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);} foreach (AppUser dbUser in userMgr.Users) {if (dbUser.Country == Countries.NONE) {dbUser.SetCountryFromCity(dbUser.City);} }context.SaveChanges();} }} This kind of seeding is more useful in a real project because it will set a value for the Country property only if one has not already been set—subsequent migrations won’t be affected, and user selections won’t be lost. 这种种植在实际项目中会更有用,因为它只会在Country属性未设置时,才会设置Country属性的值——后继的迁移不会受到影响,因此不会失去用户的选择。 1. Adding Application Support 1. 添加应用程序支持 There is no point defining additional user properties if they are not available in the application, so Listing 15-10 shows the change I made to the Views/Home/UserProps.cshtml file to display the value of the Country property. 应用程序中如果没有定义附加属性的地方,则附加属性就无法使用了,因此,清单15-10显示了我对Views/Home/UserProps.cshtml文件的修改,以显示Country属性的值。 Listing 15-10. Displaying an Additional Property in the UserProps.cshtml File 清单15-10. 在UserProps.cshtml文件中显示附加属性 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";} <div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr> <tr><th>Country</th><td>@Model.Country</td></tr></table></div>@using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Listing 15-11 shows the corresponding change I made to the Home controller to update the Country property when the City value changes. 为了在City值变化时能够更新Country属性,清单15-11显示了我对Home控制器所做的相应修改。 Listing 15-11. Setting Custom Properties in the HomeController.cs File 清单15-11. 在HomeController.cs文件中设置自定义属性 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models; namespace Users.Controllers {public class HomeController : Controller {// ...other action methods omitted for brevity...// ...出于简化,这里忽略了其他动作方法... [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;user.SetCountryFromCity(city);await UserManager.UpdateAsync(user);return View(user);}// ...properties omitted for brevity...// ...出于简化,这里忽略了一些属性...} } 2. Performing the Migration 2. 准备迁移 All that remains is to create and apply a new migration. Enter the following command into the Package Manager Console: 剩下的事情就是创建和运用新的迁移了。在“Package Manager Console(包管理器控制台)”中输入以下命令: Add-Migration CountryProperty This will generate another file in the Migrations folder that contains the instruction to add the Country column. To apply the migration, execute the following command: 这将在Migrations文件夹中生成另一个文件,它含有添加Country数据表列的指令。为了运用迁移,可执行以下命令: Update-Database –TargetMigration CountryProperty The migration will be performed, and the value of the Country property will be set based on the value of the existing City property for each user. You can check the new user property by starting the application and authenticating and navigating to the /Home/UserProps URL, as shown in Figure 15-4. 这将执行迁移,Country属性的值将根据每个用户当前的City属性进行设置。通过启动应用程序,认证并导航到/Home/UserProps URL,便可以查看新的用户属性,如图15-4所示。 Figure 15-4. Creating an additional user property 图15-4. 创建附加用户属性 Tip Although I am focused on the process of upgrading the database, you can also migrate back to a previous version by specifying an earlier migration. Use the –Force argument make changes that cause data loss, such as removing a column. 提示:虽然我们关注了升级数据库的过程,但你也可以回退到以前的版本,只需指定一个早期的迁移即可。使用-Force参数进行修改,会引起数据丢失,例如删除数据表列。 15.3 Working with Claims 15.3 使用声明(Claims) In older user-management systems, such as ASP.NET Membership, the application was assumed to be the authoritative source of all information about the user, essentially treating the application as a closed world and trusting the data that is contained within it. 在旧的用户管理系统中,例如ASP.NET Membership,应用程序被假设成是用户所有信息的权威来源,本质上将应用程序视为是一个封闭的世界,并且只信任其中所包含的数据。 This is such an ingrained approach to software development that it can be hard to recognize that’s what is happening, but you saw an example of the closed-world technique in Chapter 14 when I authenticated users against the credentials stored in the database and granted access based on the roles associated with those credentials. I did the same thing again in this chapter when I added properties to the user class. Every piece of information that I needed to manage user authentication and authorization came from within my application—and that is a perfectly satisfactory approach for many web applications, which is why I demonstrated these techniques in such depth. 这是软件开发的一种根深蒂固的方法,使人很难认识到这到底意味着什么,第14章你已看到了这种封闭世界技术的例子,根据存储在数据库中的凭据来认证用户,并根据与凭据关联在一起的角色来授权访问。本章前述在用户类上添加属性,也做了同样的事情。我管理用户认证与授权所需的每一个数据片段都来自于我的应用程序——而且这是许多Web应用程序都相当满意的一种方法,这也是我如此深入地演示这些技术的原因。 ASP.NET Identity also supports an alternative approach for dealing with users, which works well when the MVC framework application isn’t the sole source of information about users and which can be used to authorize users in more flexible and fluid ways than traditional roles allow. ASP.NET Identity还支持另一种处理用户的办法,当MVC框架的应用程序不是有关用户的唯一信息源时,这种办法会工作得很好,而且能够比传统的角色授权更为灵活且流畅的方式进行授权。 This alternative approach uses claims, and in this section I’ll describe how ASP.NET Identity supports claims-based authorization. Table 15-4 puts claims in context. 这种可选的办法使用了“Claims(声明)”,因此在本小节中,我将描述ASP.NET Identity如何支持“Claims-Based Authorization(基于声明的授权)”。表15-4描述了声明(Claims)的情形。 提示:“Claim”在英文字典中不完全是“声明”的意思,根据本文的描述,感觉把它说成“声明”也不一定合适,所以在之后的译文中基本都写成中英文并用的形式,即“声明(Claims)”。根据表15-4中的声明(Claims)的定义:声明(Claims)是关于用户的一些信息片段。一个用户的信息片段当然有很多,每一个信息片段就是一项声明(Claim),用户的所有信息片段合起来就是该用户的声明(Claims)。请读者注意该单词的单复数形式——译者注 Table 15-4. Putting Claims in Context 表15-4. 声明(Claims)的情形 Question 问题 Answer 答案 What is it? 什么是声明(Claims)? Claims are pieces of information about users that you can use to make authorization decisions. Claims can be obtained from external systems as well as from the local Identity database. 声明(Claims)是关于用户的一些信息片段,可以用它们做出授权决定。声明(Claims)可以从外部系统获取,也可以从本地的Identity数据库获取。 Why should I care? 为何要关心它? Claims can be used to flexibly authorize access to action methods. Unlike conventional roles, claims allow access to be driven by the information that describes the user. 声明(Claims)可以用来对动作方法进行灵活的授权访问。与传统的角色不同,声明(Claims)让访问能够由描述用户的信息进行驱动。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework, but it is integrated into the standard authorization features, such as the Authorize attribute. 这不是直接由MVC框架使用的特性,但它集成到了标准的授权特性之中,例如Authorize注解属性。 Tip you don’t have to use claims in your applications, and as Chapter 14 showed, ASP.NET Identity is perfectly happy providing an application with the authentication and authorization services without any need to understand claims at all. 提示:你在应用程序中不一定要使用声明(Claims),正如第14章所展示的那样,ASP.NET Identity能够为应用程序提供充分的认证与授权服务,而根本不需要理解声明(Claims)。 15.3.1 Understanding Claims 15.3.1 理解声明(Claims) A claim is a piece of information about the user, along with some information about where the information came from. The easiest way to unpack claims is through some practical demonstrations, without which any discussion becomes too abstract to be truly useful. To get started, I added a Claims controller to the example project, the definition of which you can see in Listing 15-12. 一项声明(Claim)是关于用户的一个信息片段(请注意这个英文单词的单复数形式——译者注),并伴有该片段出自何处的某种信息。揭开声明(Claims)含义最容易的方式是做一些实际演示,任何讨论都会过于抽象根本没有真正的用处。为此,我在示例项目中添加了一个Claims控制器,其定义如清单15-12所示。 Listing 15-12. The Contents of the ClaimsController.cs File 清单15-12. ClaimsController.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} }} } Tip You may feel a little lost as I define the code for this example. Don’t worry about the details for the moment—just stick with it until you see the output from the action method and view that I define. More than anything else, that will help put claims into perspective. 提示:你或许会对我为此例定义的代码感到有点失望。此刻对此细节不必着急——只要稍事忍耐,当看到该动作方法和视图的输出便会明白。尤为重要的是,这有助于洞察声明(Claims)。 You can get the claims associated with a user in different ways. One approach is to use the Claims property defined by the user class, but in this example, I have used the HttpContext.User.Identity property to demonstrate the way that ASP.NET Identity is integrated with the rest of the ASP.NET platform. As I explained in Chapter 13, the HttpContext.User.Identity property returns an implementation of the IIdentity interface, which is a ClaimsIdentity object when working using ASP.NET Identity. The ClaimsIdentity class is defined in the System.Security.Claims namespace, and Table 15-5 shows the members it defines that are relevant to this chapter. 可以通过不同的方式获得与用户相关联的声明(Claims)。方法之一就是使用由用户类定义的Claims属性,但在这个例子中,我使用了HttpContext.User.Identity属性,目的是演示ASP.NET Identity与ASP.NET平台集成的方式(请注意这句话所表示的含义:用户类的Claims属性属于ASP.NET Identity,而HttpContext.User.Identity属性则属于ASP.NET平台。由此可见,ASP.NET Identity已经融合到了ASP.NET平台之中——译者注)。正如第13章所解释的那样,HttpContext.User.Identity属性返回IIdentity的接口实现,当使用ASP.NET Identity时,该实现是一个ClaimsIdentity对象。ClaimsIdentity类是在System.Security.Claims命名空间中定义的,表15-5显示了它所定义的与本章有关的成员。 Table 15-5. The Members Defined by the ClaimsIdentity Class 表15-5. ClaimsIdentity类所定义的成员 Name 名称 Description 描述 Claims Returns an enumeration of Claim objects representing the claims for the user. 返回表示用户声明(Claims)的Claim对象枚举 AddClaim(claim) Adds a claim to the user identity. 给用户添加一个声明(Claim) AddClaims(claims) Adds an enumeration of Claim objects to the user identity. 给用户添加Claim对象的枚举。 HasClaim(predicate) Returns true if the user identity contains a claim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
转载文章
...应用程序框架,它主要用于简化构建企业级Java Web应用的工作。在本文中,Struts被用来实现文件上传和下载功能,通过定义Action类、配置struts.xml文件以及使用拦截器等机制,实现了对HTTP请求的接收、处理及响应。 MIME类型(Multipurpose Internet Mail Extensions) , MIME类型是一种标准,用于指定数据内容的格式类型,如文本、图像、视频或应用程序特定的数据。在Web开发中,特别是文件上传和下载场景,服务器端和客户端需要根据MIME类型来正确解析和处理不同类型的文件。例如,在Struts框架中,通过配置MIME类型可以指示浏览器如何打开或保存从服务器下载的文件。 拦截器(Interceptor) , 在Struts 2框架中,拦截器是一个可插拔的对象,它可以参与到Action执行的整个生命周期中,并在特定阶段进行预处理或后处理操作。文章中的LoginInterceptor就是一个自定义拦截器,它负责检查用户是否已经登录,只有当用户已登录时才允许继续执行后续的操作(如文件上传或下载)。通过这种方式,拦截器增强了系统的安全性,确保了只有经过验证的用户才能访问受限资源。
2023-11-12 20:53:42
140
转载
Beego
...过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
风中飘零
Netty
...质,并辅以丰富的代码实例,帮助大家理解和解决此类问题。 2. 问题背景 WebSocket握手与Netty WebSocket是一种双向通信协议,允许服务端和客户端之间建立持久化的连接并进行全双工通信。在建立连接的过程中,首先需要完成一次“握手”操作,即客户端发送一个HTTP Upgrade请求,服务端响应确认升级为WebSocket协议。当这个握手过程出现问题时,Netty会抛出Invalid or incomplete WebSocket handshake response异常。 3. 握手失败原因分析 (1)格式不正确:WebSocket握手响应必须遵循特定的格式规范,包括但不限于状态码101(Switching Protocols)、Upgrade头部字段值为websocket、Connection头部字段值包含upgrade等。如果这些条件未满足,Netty在解析握手响应时就会报错。 java // 正确的WebSocket握手响应示例 HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS); response.headers().set(HttpHeaderNames.UPGRADE, "websocket"); response.headers().set(HttpHeaderNames.CONNECTION, "Upgrade"); (2)缺失关键信息:WebSocket握手过程中,客户端和服务端还会交换Sec-WebSocket-Key和Sec-WebSocket-Accept两个特殊头部字段。要是服务端在搞Sec-WebSocket-Accept这个值的时候算错了,或者压根儿没把这个值传回给客户端,那就等于说这次握手要黄了,也会造成连接失败的情况。 java // 计算Sec-WebSocket-Accept的Java代码片段 String key = request.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY); String accept = Base64.getEncoder().encodeToString( sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes(StandardCharsets.UTF_8) ); response.headers().set(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept); 4. 实战调试 排查与修复 当我们遇到Invalid or incomplete WebSocket handshake response异常时,可以通过以下步骤来定位问题: - 查看日志:详细阅读Netty打印的异常堆栈信息,通常可以从中发现具体的错误描述和发生错误的位置。 - 检查代码:对照WebSocket握手协议规范,逐一检查服务器端处理握手请求的代码逻辑,确保所有必需的头部字段都被正确设置和处理。 - 模拟客户端:利用如Wireshark或者Postman工具模拟发送握手请求,观察服务端的实际响应内容,对比规范看是否存在问题。 5. 结语 在Netty的世界里,Invalid or incomplete WebSocket handshake response并非无法逾越的鸿沟,它更像是我们在探索高性能网络编程旅程中的一个小小挑战。要知道,深入研究WebSocket那个握手协议的门道,再配上Netty这个神器的威力,我们就能轻轻松松地揪出并解决那些捣蛋的问题。这样一来,咱们就能稳稳当当地打造出既稳定又高效的WebSocket应用,让数据传输嗖嗖的,贼溜贼溜的!在实际开发中,让我们一起面对挑战,享受解决技术难题带来的乐趣吧!
2023-11-19 08:30:06
211
凌波微步
Golang
...模式,它位于客户端和服务器端应用之间,负责处理HTTP请求和响应的生命周期。在Golang的Gin框架中,中间件可以是一系列函数,它们按特定顺序执行以实现诸如身份验证、日志记录、性能监控等功能,从而增强应用程序的可扩展性和模块化。 路由参数 , 在Web应用程序中,路由参数是指URL路径中的占位符部分,用于捕获动态值。例如,在Gin框架中,“/users/:username”中的:username就是一个路由参数,当用户访问类似“/users/john”的URL时,路由会自动解析并将“john”作为变量值提供给处理该路由的函数使用,以便开发者可以根据该动态值执行相应的业务逻辑。 静态资源 , 静态资源是指Web应用程序中不需要服务器端动态处理的文件,如HTML、CSS、JavaScript、图片、字体等。这些文件在构建应用后内容不会改变,可以直接由Web服务器读取并发送给客户端浏览器。在Golang的Web应用中,通过配置静态文件目录来托管这些资源,使得客户端可以直接访问,从而减轻服务器的计算压力,提高网站加载速度。
2023-01-10 18:53:06
507
繁华落尽
Logstash
...gstash是开源的服务器端数据处理管道,可以动态地收集、过滤、转换和输出多种类型的数据。在本文的上下文中,用户使用Logstash从不同源获取日志数据,通过预定义的过滤规则进行处理,并将其输出到Elasticsearch存储以供进一步分析和检索。 Elasticsearch , Elasticsearch是一个分布式、RESTful风格的搜索和分析引擎,基于Apache Lucene构建而成,能够实现近乎实时的全文搜索和分析功能。在本文中,Elasticsearch被用作Logstash输出的目标,用于存储和索引经过处理的日志数据,以便于后续进行高效查询、可视化展示及监控。 Uniform Resource Identifier (URI) , URI是一种字符串型标识符,用于唯一地标识互联网上的资源或服务的位置以及访问方法。在文章的具体应用场景中,URI用于配置Logstash与Elasticsearch集群节点的连接地址,通常包含协议(如http或https)、主机名或IP地址以及端口号,例如http://localhost:9200,确保Logstash能准确无误地向指定的Elasticsearch节点发送数据。 SSL/TLS连接 , SSL(Secure Sockets Layer)和其继任者TLS(Transport Layer Security)是网络通信中广泛采用的安全协议,用于加密在网络上传输的数据,防止信息被窃取或篡改。在本文提到的场景下,启用SSL加密连接意味着Logstash与Elasticsearch之间的数据传输将得到安全保障,避免敏感日志信息在传输过程中遭到泄露。 基本认证 , 基本认证是一种HTTP身份验证机制,要求用户提供用户名和密码进行验证。在Logstash与Elasticsearch集成时,可以在URI中嵌入基本认证信息(如user:password@hostname),以此确保只有经过授权的用户才能访问和写入Elasticsearch集群中的数据。
2024-01-27 11:01:43
302
醉卧沙场
JSON
...的数据交换格式,设计用于人与机器都能轻松阅读和编写。在JSON中,数据以键值对的形式存储,也可以嵌套数组和其他JSON对象,形成复杂的数据结构。由于其语法简洁且易于解析,广泛应用于Web开发中的前后端数据交互、API接口响应以及不同系统间的数据传递。 RESTful API , Representational State Transfer(表述性状态转移)风格的API设计原则,基于HTTP协议进行资源访问。RESTful API使用标准HTTP方法(如GET、POST、PUT、DELETE等)来操作资源,并通过URI定位资源,返回的数据通常采用JSON格式。这种设计方式具有良好的可扩展性和易用性,使得JSON成为此类API实现数据交换的标准格式之一。 JSON Schema , 一种用于描述JSON数据结构和约束条件的标准模式语言。它定义了一种规范,允许开发者为JSON文档指定类型、属性要求、默认值以及其他验证规则。通过JSON Schema,可以确保在应用程序中接收或生成的JSON数据满足预设格式和要求,从而增强数据的一致性和准确性。 JSON Web Tokens (JWT) , 一种开放标准(RFC 7519),用于安全地在各方之间传输声明信息(claims)。JWT是一个经过数字签名或者加密的自包含JSON对象,可以作为用户身份验证的一种手段,在用户登录后生成并发送给客户端,客户端在后续请求时携带此Token,服务器端对其进行验证以确认用户的授权状态。这在现代Web应用的身份验证和授权机制中得到广泛应用,有助于提高数据传输的安全性。
2023-10-11 22:09:42
754
林中小径
Tornado
...技术趋势。最近,随着HTTP/3协议的普及以及云计算、边缘计算的发展,对实时性、高并发处理能力的需求日益增强。 2022年,Facebook开源了其内部用于构建高度可扩展、低延迟服务的异步Python网络库——Marauder。该库借鉴了Tornado的设计理念,并进一步优化了资源利用率和响应速度,为开发者提供了更强大的工具来应对复杂网络环境下的挑战。同时,各大云服务商如AWS、Google Cloud也陆续推出了基于异步IO模型的服务端SDK,以适应分布式系统和微服务架构下对性能与稳定性的严苛要求。 此外,针对网络安全问题,结合Tornado等高性能网络库的应用实践,业界专家也在不断深入研究如何在保证高效率的同时加强数据传输的安全性和隐私保护。例如,通过整合加密通信协议(如TLS 1.3)、实现自动重连时的身份验证机制,以及利用WebSockets进行安全的双向实时通信,从而全方位提升网络应用的信息安全保障水平。 综上所述,无论是在技术演进还是实际应用场景中,掌握和运用Tornado这类高性能网络库都是网络开发工程师提升核心竞争力的重要一环,而持续关注并学习相关领域的最新进展和技术方案,则是紧跟时代步伐、满足未来需求的关键所在。
2023-05-20 17:30:58
168
半夏微凉-t
Go Iris
...一个不存在的页面或者服务器遇到其他错误情况时,返回给用户的网页内容。一个优秀的错误页面,应该像你的好朋友一样,直截了当地告诉你:“哎呀,出问题啦!不过别担心,我给你提供几个可能的解决办法,咱们一起来看看能不能搞定它。”这样子做不仅能给用户带来更棒的体验,还能让我们有机会听到大家的真实声音,从而更好地改进和打磨我们的产品。 二、在Go Iris中处理错误页面的方法 在Go Iris中,我们可以使用中间件来处理错误页面。中间件是Go Iris的核心特性之一,它可以对每个请求进行处理,从而达到我们想要的功能。 1. 使用Iris库自带的中间件 Iris库为我们提供了一个叫做ServerError的中间件,这个中间件可以用于处理HTTP服务器端的错误。当你在用这个小工具的时候,一旦出了岔子,Iris这家伙可机灵了,它会立马启动这个中间件,然后乖乖地把错误消息送到我们手上。我们可以在这个中间件中定义自己的错误处理逻辑。 go app.Use(func(ctx iris.Context) { if err := ctx.Environment().Get("iris.ServerError").(error); err != nil { // do something to handle the error here... } }) 2. 自定义中间件 如果我们觉得ServerError中间件不能满足我们的需求,我们也可以自定义中间件来处理错误页面。首先,我们需要创建一个新的函数来接收错误信息: go func HandleError(err error, w http.ResponseWriter, r http.Request) { // handle the error here... } 然后,我们将这个函数注册为中间件: go app.Use(func(ctx iris.Context) { if err := ctx.Environment().Get("iris.ServerError").(error); err != nil { HandleError(err, ctx.ResponseWriter(), ctx.Request()) } }) 三、如何设计优秀的错误页面 一个优秀的错误页面需要具备以下几个特点: 1. 清晰明了 要告诉用户发生了什么问题,以及可能导致这个问题的原因。 2. 提供解决方案 尽可能给出一些解决问题的方法,让用户能够自行修复问题。 3. 友好的界面 要让用户感觉舒适,而不是让他们感到恐惧或沮丧。 四、总结 通过以上的讲解,我相信你已经掌握了在Go Iris中全局处理错误页面的方法。记住了啊,一个优秀的错误处理机制,那可是大有作用的。它不仅能让你在使用产品时有个更顺心畅快的体验,还能帮我们把你们的真实反馈收集起来,这样一来,我们就能够对产品进行更精准、更接地气的优化升级。所以,不要忽视了错误处理的重要性哦!
2023-12-19 13:33:19
410
素颜如水-t
SpringBoot
...洞:例如,在进行权限验证之前,就已经执行了敏感操作。 - 测试不足:在上线前没有充分地测试各种边界条件下的权限情况。 案例分享: 有一次,我在一个项目中负责权限模块的开发。最开始我觉得一切风平浪静,直到有天一个同事告诉我,他居然能删掉其他人的账户,这下可把我吓了一跳。折腾了一番后,我才明白问题出在哪——原来是在执行删除操作之前,我忘了仔细检查用户的权限,就直接动手删东西了。这个错误让我深刻认识到,即使是最基本的安全措施,也必须做到位。 3. 如何避免权限管理失败 既然已经知道了可能导致权限管理失败的因素,那么如何避免呢?这里有几个建议: - 严格遵循最小权限原则:确保每个用户仅能访问他们被明确允许访问的资源。 - 全面的测试:不仅要测试正常情况下的权限验证,还要测试各种异常情况,如非法请求等。 - 持续学习与更新:安全是一个不断变化的领域,新的攻击手段和技术层出不穷,因此保持学习的态度非常重要。 代码示例: 为了进一步加强我们的权限管理,我们可以使用更复杂的权限模型,如RBAC(基于角色的访问控制)。下面是一个使用Spring Security结合RBAC的简单示例: java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin().permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}password").roles("ADMIN"); } } 在这个配置中,我们定义了两种角色:USER和ADMIN。嘿,你知道吗?只要网址里有/admin/这串字符的请求,都得得有个ADMIN的大角色才能打开。其他的请求嘛,就简单多了,只要登录了就行。 4. 结语 权限管理的艺术 权限管理不仅是技术上的挑战,更是对开发者细心和耐心的考验。希望看完这篇文章,你不仅能get到一些实用的技术小技巧,还能深刻理解到权限管理这事儿有多重要,毕竟安全无小事嘛!记住,安全永远是第一位的! 好了,这就是今天的分享。如果你有任何想法或疑问,欢迎随时留言交流。希望我的经验对你有所帮助,让我们一起努力,构建更加安全的应用吧!
2024-11-02 15:49:32
61
醉卧沙场
转载文章
...转载内容。原文链接:https://blog.csdn.net/newlw/article/details/127608579。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 目 录 摘 要 I Abstract II 1绪论 1 1.1系统开发背景 1 1,2研究现状 1 1.3研究主要内容 3 2相关技术 5 2.1 SSM的技术原理 5 2.1.1 SSM语言及其特点 5 2.1.2 Java及Java Servlets概述 6 2.1.3 JavaBean简介 6 2.2 服务器配置 7 2.2.1 Tomcat安装及配置 8 2.2.2 数据库配置 8 3系统分析 11 3.1 可行性分析 11 3.1.1 技术可行性 11 3.1.2 操作可行性 11 3.1.3 经济可行性 11 3.1.4 法律可行性 11 3.2 腕表交易系统功能需求分析 11 3.3 数据库需求分析 12 4系统设计 13 4.1 系统功能模块设计 13 4.2系统流程设计 13 4.2.1 系统开发流程 13 4.2.2 用户登录流程 14 4.2.3 系统操作流程 15 4.2.4 添加信息流程 15 4.2.5 修改信息流程 16 4.2.6 删除信息流程 16 4.3系统用例分析 17 4.3.1 管理员用例图 17 4.3.2 用户用例图 18 4.4 数据库设计 19 4.4.1 tb_Ware(商品信息表) 19 4.4.2 tb_manager(管理员信息表) 19 4.4.3 tb_sub(订单生成表) 19 4.4.4 tb_Link(超级链接表) 20 4.4.5 tb_Affiche(公告信息表) 20 4.3 用SSM连接数据库 20 5系统实现 22 5.1 前台部分 22 5.1.1 前台总体框架 22 5.1.2 商城首页 22 5.1.3 产品详情页 23 5.1.4 评价 23 5.2 后台部分 24 5.2.1 后台主页 24 5.2.2 后台评价管理 25 5.2.3 商品管理 25 5.2.4 商品修改 26 5.2.5 分类管理 26 5.2.6 订单管理 27 5.2.7 腕表购物车管理 27 6系统测试 28 6.1系统测试的意义 28 6.2性能测试 29 6.3测试分析 29 总 结 30 致 谢 31 参考文献 31 3系统分析 3.1 可行性分析 腕表交易系统主要目标是实现网上展示腕表交易系统信息,购买腕表产品。在确定了目标后,我们从以下四方面对能否实现本系统目标进行可行性分析。 3.1.1 技术可行性 腕表交易系统主要采用Java技术,基于B/S结构,MYSQL数据库,主要包括前端应用程序的开发以及后台数据库的建立和维护两个方面。对于应用程序的开发要求具备功能要完备、使用应简单等特点,而对于数据库的建立和维护则要求建立一个数据完整性强、数据安全性好、数据稳定性高的库。腕表交易系统的开发技术具有很高可行性,且开发人员掌握了一定的开发技术,所以系统的开发具有可行性。 3.1.2 操作可行性 腕表交易系统的登录界面简单易于操作,采用常见的界面窗口来登录界面,通过电脑进行访问操作,会员只要平时使用过电脑都能进行访问操作。此系统的开发采用PHP语言开发,基于B/S结构,这些开发环境使系统更加完善。本系统具有易操作、易管理、交互性好的特点,在操作上是非常简单的。因此本系统可以进行开发。 3.1.3 经济可行性 腕表交易系统是基于B/S模式,采用MYSQL数据库储存数据,所要求的硬件和软件环境,市场上都很容易购买,程序开发主要是管理系统的开发和维护。所以程序在开发人力、财力上要求不高,而且此系统不是很复杂,开发周期短,在经济方面具有较高的可行性。 3.1.4 法律可行性 此腕表交易系统是自己设计的管理系统,具有很大的实际意义。开发环境软件和使用的数据库都是开源代码,因此对这个系统进行开发与普通的系统软件设计存在很大不同,没有侵权等问题,在法律上完全具有可行性。 综上所述,腕表交易系统在技术、经济、操作和法律上都具有很高的可行性,开发此程序是很必要的。 3.2 腕表交易系统功能需求分析 此基于SSM的腕表交易系统分前台功能和后台功能: 1)前台部分由用户使用,主要包括用户注册,腕表购物车管理,订单管理,个人资料管理,留言板管理 2)后台部分由管理员使用,主要包括管理员身份验证,商品管理,处理订单,用户信息管理,连接信息管理 3.3 数据库需求分析 数据库的设计通常是以一个已经存在的数据库管理系统为基础的,常用的数据库管理系统有MYSQL,SQL,Oracle等。我采用了Mysql数据库管理系统,建立的数据库名为db_business。 整个系统功能需要以下数据项: 用户:用户id、用户名称、登录密码、用户真实姓名、性别、邮箱地址、联系地址、联系电话、密码问题、答案、注册时间。 留言:主题id、作者姓名、Email、主题名称、留言内容、发布时间。 商品:商品id、名称、价格、图片路径、类型、简要介绍、存储地址、上传人姓名、发布时间、是否推荐。 订单:订单号、用户名、真实姓名、订购日期、Email、地址、邮编、付款方式、联系方式、运送方式、订单核对、其他。 管理员:管理员id、管理员名称、管理员密码。 公告:公告内容、公告时间。 4系统设计 4.1 系统功能模块设计 功能结构图如下: 图9 功能模块设计图 从图中可以看出,网上腕表交易系统可以分为前台和后台两个部分,前台部分由用户使用,主要包括用户注册,生成订单,腕表购物车管理,查看腕表购物车,查看留言,订购产品,订单查询和发布留言7个模块;本文转载自http://www.biyezuopin.vip/onews.asp?id=11975后台部分由管理员使用,主要包括管理员身份验证,商品管理,处理订单,用户信息管理,连接信息管理5个模块。 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"/><title>腕表商城</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><meta name="viewport" content="width=device-width, initial-scale=1"><!-- Favicon --><link rel="shortcut icon" type="image/x-icon" href="img/favicon.png"><link rel="stylesheet" type="text/css" href="<%=basePath%>home/css/font-awesome.min.css" /><link rel="stylesheet" type="text/css" href="<%=basePath%>home/css/bootstrap.css" /><link rel="stylesheet" type="text/css" href="<%=basePath%>home/css/style.css"><link rel="stylesheet" type="text/css" href="<%=basePath%>home/css/magnific-popup.css"><link rel="stylesheet" type="text/css" href="<%=basePath%>home/css/owl.carousel.css"><script type="text/javascript">function getprofenlei(){ var html = ""; $.ajax({url: "leixing.action?list&page=0&rows=30",type: "POST",async: false, contentType: "application/x-www-form-urlencoded;charset=UTF-8",success: function (data) { $.each(data.rows, function (i, val) { html += ' <li ><a href="home/search.jsp?fenlei='+val.id+'" >'+val.a1+' </a></li>';})} }); $("fenlei").html(html);}function gettop1(){var html = "";$.ajax({url: "leixing.action?list&page=0&rows=10",type: "POST",async: false,success: function (data) {var total='';//<div class="tab-pane active" id="nArrivals">// <div class="nArrivals owl-carousel" id="top1">$.each(data.rows, function (i, valmm) { html+='<div class="nArrivals owl-carousel" id="'+valmm.id+'">';$.ajax({url: "shangpin.action?list&page=0&rows=10",type: "POST",async: false,data: { fenlei:valmm.id },success: function (data) { $.each(data.rows, function (i, val) { html+='<div class="product-grid">'+'<div class="item">'+' <div class="product-thumb">'+' <div class="image product-imageblock"> <a href="home/details.jsp?ids='+val.id+'"> <img data-name="product_image" style="width:223px;height:285px;" src="<%=basePath%>'+val.tupian1+'" alt="iPod Classic" title="iPod Classic" class="img-responsive"> <img style="width:223px;height:285px;" src="<%=basePath%>'+val.tupian1+'" alt="iPod Classic" title="iPod Classic" class="img-responsive"> </a> </div>'+' <div class="caption product-detail text-left">'+' <h6 data-name="product_name" class="product-name mt_20"><a href="home/details.jsp?ids='+val.id+'" title="Casual Shirt With Ruffle Hem">'+val.biaoti+'</a></h6>'+' <div class="rating"> <span class="fa fa-stack"><i class="fa fa-star-o fa-stack-1x"></i><i class="fa fa-star fa-stack-1x"></i></span> <span class="fa fa-stack"><i class="fa fa-star-o fa-stack-1x"></i><i class="fa fa-star fa-stack-1x"></i></span> <span class="fa fa-stack"><i class="fa fa-star-o fa-stack-1x"></i><i class="fa fa-star fa-stack-1x"></i></span> <span class="fa fa-stack"><i class="fa fa-star-o fa-stack-1x"></i><i class="fa fa-star fa-stack-1x"></i></span> <span class="fa fa-stack"><i class="fa fa-star-o fa-stack-1x"></i><i class="fa fa-star fa-stack-x"></i></span> </div>'+'<span class="price"><span class="amount"><span class="currencySymbol">$</span>'+val.jiage+'</span>'+'</span>'+'<div class="button-group text-center">'+' <div class="wishlist"><a href="home/details.jsp?ids='+val.id+'"><span>wishlist</span></a></div>'+'<div class="quickview"><a href="home/details.jsp?ids='+val.id+'"><span>Quick View</span></a></div>'+'<div class="compare"><a href="home/details.jsp?ids='+val.id+'"><span>Compare</span></a></div>'+'<div class="add-to-cart"><a href="home/details.jsp?ids='+val.id+'"><span>Add to cart</span></a></div>'+'</div>'+'</div>'+'</div>'+'</div>'+' </div>'; })html+='</div>'; } })}) $("nArrivals").html(html); } }); 本篇文章为转载内容。原文链接:https://blog.csdn.net/newlw/article/details/127608579。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-21 18:24:50
66
转载
Struts2
...truts2会自动将HTTP请求参数映射到模型对象(Model)的属性上。通过重写getModel()方法返回模型对象实例,开发者可以简化表单数据与业务模型之间的交互过程,无需在Action类中逐个定义和处理请求参数。 数据绑定(Data Binding) , 在Web开发中,数据绑定是指将用户通过表单提交的数据自动填充到服务器端的对象属性中的过程。在本文语境下,Struts2模型驱动模式实现了这一机制,它能根据请求参数名与模型对象属性名的对应关系,自动进行数据转换并赋值,极大地提高了开发效率和代码可维护性。 类型转换器(Type Converter) , 类型转换器在Struts2框架中扮演着重要角色,主要用于解决不同数据类型之间转换的问题。在模型驱动模式下,当HTTP请求参数需要映射到模型对象的不同类型属性时,Struts2会使用相应的类型转换器将字符串类型的请求参数转换为目标属性类型(如Date、Enum等)。如果未配置合适的类型转换器,可能会导致转换异常,影响程序正常运行。例如,在文章示例中,User类的birthDate属性就需要一个日期类型的转换器来进行正确的数据绑定。
2023-10-28 09:39:32
110
烟雨江南
Apache Solr
...通常是由于与Solr服务器之间的通信问题引起的。本文呢,咱们就来好好唠唠怎么搞定SolrServerException这个小捣蛋,而且我还会手把手地给你献上一些实例代码,包你一看就明白! 1. 确保Solr服务器正在运行 首先,你需要确保Solr服务器正在运行。你可以通过运行以下命令来检查: bash curl http://localhost:8983/solr/admin/healthcheck 如果你看到类似于"OK"的消息,那么Solr服务器正在运行。 2. 检查网络连接 如果Solr服务器正在运行但仍然出现SolrServerException,那么可能是网络连接问题。你应该检查你的网络设置,确保能够正确地连接到Solr服务器。 3. 检查Solr配置 如果以上两种方法都不能解决问题,那么可能是Solr的配置出现了问题。你最好抽空瞅瞅Solr的那个配置文件,尤其是Solr的核心配置部分,瞧瞧里面有没有啥错误或者遗漏的地方。 4. 使用SSL证书 有时,由于配置的HTTPS证书导致的,如证书中的IP配置错误,不是Solr服务所在的IP,那么客户端访问就可能出现上述的问题。所以在配置证书时,要特别注意配置哪些IP来访问该Solr服务。 例如,在Java中,我们可以使用如下代码创建一个带有自签名证书的SSL套接字工厂: java KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream("/path/to/keystore"), "password".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509ExtendedTrustManager xtm = (X509ExtendedTrustManager) tmf.getTrustManagers()[0]; X509Certificate cert = (X509Certificate) ks.getCertificateChain(ks.aliases().nextElement())[0]; xtm.checkClientTrusted(new X509Certificate[]{cert}, "SSL"); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{xtm}, null); SSLSocketFactory ssf = sslContext.getSocketFactory(); 然后,我们可以在连接Solr服务器时使用这个套接字工厂: java HttpURLConnection conn = (HttpURLConnection) new URL(solrUrl).openConnection(); conn.setSSLSocketFactory(ssf); 5. 尝试其他Solr服务器 如果你无法确定问题出在哪里,你可以尝试在另一台机器上启动一个Solr服务器,看看是否还能出现同样的问题。这可以帮助你排除网络或者硬件故障的可能性。 总结:以上就是解决SolrServerException的一些常见方法。当你遇到这种错误的时候,就得像个侦探一样,把所有可能捣乱的因素都给排查一遍,然后根据实际情况,灵活地采取最适合的解决办法。希望这篇文章能对你有所帮助。
2023-03-23 18:45:13
462
凌波微步-t
NodeJS
...式调用的模式,参与到HTTP请求处理流程中。当一个HTTP请求到达服务器后,中间件会按照注册顺序逐个执行,每个中间件都可以对请求进行预处理、后处理或者完全处理(例如发送响应)。中间件能够访问请求对象(req)、响应对象(res)以及next函数(用于调用下一个中间件),从而实现诸如身份验证、日志记录、错误处理等多种功能。 错误处理中间件 , 在Node.js和Express等框架中,错误处理中间件是专门用来捕获和处理程序运行时产生的错误的一种中间件。不同于常规中间件,错误处理中间件通常接收四个参数,即错误对象(err)、请求对象(req)、响应对象(res)和next函数。当应用中的其他部分抛出错误且未被妥善处理时,错误处理中间件会被调用,它负责记录错误信息、设置合适的HTTP状态码,并向客户端返回错误消息,以确保应用程序不会因未处理的异常而崩溃。 HTTP响应 , HTTP响应是在HTTP协议下,服务器对客户端发起的HTTP请求所做出的反馈信息。在Node.js应用中,HTTP响应对象(res)代表了这种反馈信息,它可以控制各种响应头、状态码以及响应体内容。例如,在本文给出的自定义错误处理中间件示例中,通过调用res.status(500)设置了HTTP状态码为500(表示服务器内部错误),然后使用res.send( Something broke! )方法将错误消息作为响应体发送给客户端。
2023-12-03 08:58:21
90
繁华落尽-t
HessianRPC
...杠杠的,所以在Web服务、手机APP开发,甚至嵌入式设备这些领域里头,它都大显身手,混得风生水起。 三、如何利用Hessian进行大数据量高效传输 在大数据量的传输过程中,Hessian提供了以下几种方法: 1. 序列化和反序列化 Hessian支持对象的序列化和反序列化,可以将复杂的业务对象转换为简单的字符串,然后在网络上传输,接收端再将字符串转换回对象。 2. HTTP请求 Hessian可以将对象作为HTTP请求体发送,接收端同样可以解析请求体得到对象。 3. Socket编程 Hessian也可以通过Socket编程的方式进行数据传输,这种方式更加灵活,适用于需要实时通信的场景。 下面我们分别通过一个例子来演示这些方法。 四、使用Hessian进行序列化和反序列化 首先,我们创建一个简单的类User: java public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } // getters and setters... } 然后,我们可以使用Hessian的writeValueTo()方法将User对象序列化为字符串: java User user = new User("Tom", 20); String serialized = Hessian2.dump(user); 接收到这个字符串后,我们可以通过Hessian的readObjectFrom()方法将其反序列化为User对象: java User deserialized = (User) Hessian2.unmarshal(serialized); 五、使用Hessian进行HTTP请求 在Spring框架中,我们可以使用HessianProxyFactoryBean来创建一个代理对象,然后通过这个代理对象来调用远程服务。 例如,我们在服务器端有一个接口UserService: java public interface UserService { User getUser(String id); } 然后,客户端可以通过如下方式来调用远程服务: java HessianProxyFactoryBean factory = new HessianProxyFactoryBean(); factory.setServiceUrl("http://localhost:8080/service/UserService"); factory.afterPropertiesSet(); UserService userService = (UserService) factory.getObject(); User user = userService.getUser("1"); 六、使用Hessian进行Socket编程 如果需要进行实时通信,我们可以直接使用Socket编程。首先,在服务器端创建一个监听器: java ServerSocket serverSocket = new ServerSocket(8080); while (true) { Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); String request = readRequest(inputStream); String response = handleRequest(request); writeResponse(response, outputStream); } 然后,在客户端创建一个连接: java Socket socket = new Socket("localhost", 8080); OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); writeRequest(request, outputStream); String response = readResponse(inputStream); 七、结论 总的来说,Hessian是一种非常强大的工具,可以帮助我们高效地进行大数据量的传输。甭管是Web服务、手机APP,还是嵌入式小设备,你都能发现它的存在。在接下来的工作日子里,咱们得好好琢磨和掌握这款工具,这样一来,工作效率自然就能蹭蹭往上涨啦!
2023-11-16 15:02:34
468
飞鸟与鱼-t
Go Gin
... - 路由:路由是将HTTP请求映射到相应处理函数的关键部分。例如,我们可以通过以下方式定义一个路由: go router := gin.Default() router.GET("/", func(c gin.Context) { c.JSON(200, gin.H{ "message": "Welcome to Gin!", }) }) 在这个例子中,当我们访问网站的根路径时,服务器会返回一个JSON响应,内容为"Welcome to Gin!"。 - 中间件:中间件是在请求到达目标处理函数之前或者之后执行的一系列操作。例如,我们可以定义一个中间件,用于记录每次请求的处理时间: go router.Use(func(c gin.Context) { start := time.Now() c.Next() // 传递控制权给下一个中间件或处理函数 duration := time.Since(start) log.Printf("%s took %s", c.Request.Method, duration) }) 四、创建Go Gin应用 接下来,我们将创建一个简单的Go Gin应用程序。 首先,我们需要导入所需的包: go import ( "fmt" "log" "github.com/gin-gonic/gin" ) 然后,我们可以创建一个函数,用于初始化我们的应用: go func main() { router := gin.Default() // 在这里添加你的路由和中间件... router.Run(":8080") } 在这个函数中,我们创建了一个新的路由器实例,并调用了其Run方法来启动我们的应用程序。 五、第一个Hello World示例 现在,让我们来看一个简单的例子,它将输出"Hello, Gin!"。 go router := gin.Default() router.GET("/", func(c gin.Context) { c.String(200, "Hello, Gin!") }) 当你运行这个程序并访问"http://localhost:8080/"时,你应该可以看到"Hello, Gin!"。 六、总结 Go Gin是一个强大而易于使用的Web开发框架。经过这篇教程的学习,你现在对如何亲手安装Go Gin这套工具已经门儿清了,而且还掌握了创建并跑起一个基础的Go Gin应用程序的独门秘籍。接下来,你可以试着解锁更多Go Gin的玩法,比如捣鼓捣鼓错误处理、尝试尝试模板渲染这些功能,这样一来,你的编程技能肯定能噌噌噌地往上涨!最后,祝愿你在学习Go Gin的过程中愉快!
2024-01-04 17:07:23
527
林中小径-t
MyBatis
...理解了MyBatis拦截器的工作机制以及如何解决批量插入数据场景下拦截器失效的问题后,我们不妨进一步关注近期关于数据库性能优化和事务管理的相关实践与研究。 近期,随着微服务架构的普及和技术的发展,数据库性能优化成为众多开发者关注的重点。尤其在大数据量、高并发场景下,如何高效利用MyBatis等持久层框架进行批处理操作显得尤为重要。例如,有技术团队通过深入研究MyBatis源码并结合JDBC驱动特性,提出了一种新的批处理执行策略,不仅确保了拦截器的正常执行,还显著提升了批量插入的性能。 同时,在事务管理领域,随着分布式事务解决方案如Seata、TCC模式的广泛应用,如何将MyBatis拦截器与分布式事务相结合,实现细粒度的事务控制和业务逻辑拦截,也成为行业热议的话题。不少企业级项目实践中,已经成功地将拦截器应用于分布式事务的边界切面,实现了诸如事务日志记录、资源锁定状态监控等功能。 此外,对于MyBatis插件化设计思路的理解,也可以帮助开发者更好地借鉴到其他ORM框架或者编程语言中的类似模块设计中,比如Hibernate的拦截器(Interceptor)或Spring AOP面向切面编程等,从而提升整体系统的可维护性和扩展性。 综上所述,针对MyBatis拦截器的深入探讨不仅能解决特定问题,更能启发我们在实际开发工作中对数据库操作优化、事务管理乃至更广泛的架构设计层面产生新的思考与应用。
2023-05-12 21:47:49
152
寂静森林_
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
groups user
- 显示指定用户的所属组。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
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
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"