asp.net mvc auth2.0简化版——服务端
- public class AuthController : Controller
- {
- private static readonly List<string> client_id_list = new List<string>() { "123456789" };
- private static readonly List<string> response_type_list = new List<string>() { "code" };
- private static readonly List<UserInfo> user_list = new List<UserInfo>();
- private static readonly List<UserCode> user_code_list = new List<UserCode>();
- private static readonly List<UserToken> user_token_list = new List<UserToken>();
- public AuthController()
- {
- user_list.Add(new Models.UserInfo("admin", "admin", 33, "male"));
- user_list.Add(new Models.UserInfo("test", "tgest", 22, "female"));
- }
- [HttpGet]
- public ActionResult Authorize()
- {
- return View();
- }
- [HttpPost]
- public ActionResult SubmitAuthorize()
- {
- return View();
- }
- public ActionResult Error()
- {
- return View();
- }
- [HttpGet]
- public ActionResult Login()
- {
- return View();
- }
- [HttpPost]
- public ActionResult Login(UserInfo userinfo)
- {
- var username = userinfo.UserName;
- var password = userinfo.Password;
- //取得重定向的信息
- var redirect_uri = Session["redirect_uri"] ?? "";
- var state = Session["state"] ?? "";
- string code = Guid.NewGuid().ToString();
- //验证用户名密码
- if (user_list.Count(f => f.UserName == username >> f.Password == password) == 0)
- return this.Json("用户名或密码不正确", JsonRequestBehavior.AllowGet);
- //保存code到DB/Redis,默认存在30秒
- user_code_list.Add(new UserCode() { UserName = username, Code = code, ExpiryDate = DateTime.Now.AddSeconds(30) });
- //绑定code与userid,因为后面查询用户信息的时候要用到,默认存在30秒
- //_oAuth2ServerServices.BingCodeAndUser(username, code);
- //重定向
- string url = string.Format(HttpUtility.UrlDecode(redirect_uri.ToString()) + "?code={0}&state={1}", code, state);
- Response.Redirect(url);
- return null;
- //return View();
- }
- //
- // GET: /Authorize/
- public ActionResult Index(string client_id, string response_type, string redirect_uri, string scope, string state = "")
- {
- if (!client_id_list.Contains(client_id))
- {
- return this.Json(new { msg = "client_id error", code = "-1" }, JsonRequestBehavior.AllowGet);
- }
- if (!response_type_list.Contains(response_type))
- {
- return this.Json(new { msg = "response_type error", code = "-1" }, JsonRequestBehavior.AllowGet);
- }
- //保存用户请求的所有信息到指定容器(session)
- Session.Add("client_id", client_id);
- Session.Add("response_type", response_type);
- Session.Add("redirect_uri", redirect_uri);
- Session.Add("state", state);
- Session.Add("scope", scope);
- Redirect("/Auth/Login?client_id=" + client_id + "&redirect_uri=" + HttpUtility.UrlEncode(redirect_uri) + "&response_type=" + response_type);
- //重定向到用户授权页面(当然你可以自定义自己的页面)
- return View("Login");
- }
- // <summary>
- /// 获取或刷新token。
- /// token可能保存在DB/Redis等
- /// </summary>
- /// <param name="code"></param>
- /// <param name="grant_type"></param>
- /// <param name="client_id"></param>
- /// <param name="client_secret"></param>
- /// <returns></returns>
- public ActionResult Token(string code, string grant_type, string client_id)
- {
- Response.ContentType = "application/json";
- Response.AddHeader("Cache-Control", "no-store");
- //获取token
- if (grant_type == "authorization_code")
- {
- //判断code是否过期
- if (!user_code_list.Exists(f => f.Code == code >> f.ExpiryDate > DateTime.Now))
- {
- return this.Json("code 不存在或已过期", JsonRequestBehavior.AllowGet);
- }
- //判断client_id与client_secret是否正确
- if (!client_id_list.Contains(client_id))
- {
- return this.Json("client_id不正确", JsonRequestBehavior.AllowGet);
- }
- //通过code获取userid,然后用token与userid做绑定,最后把code设置成消失(删除)
- var user_code = user_code_list.FirstOrDefault(f => f.Code == code);
- if (user_code == null)
- {
- return this.Json("code不存在或已过期", JsonRequestBehavior.AllowGet);
- }
- //username
- string username = user_code.UserName;
- //新建token
- string access_token = Guid.NewGuid().ToString();
- //保存token,默认是30分钟
- user_token_list.Add(new UserToken() { UserName = username, Code = code, ExpiryDate = DateTime.Now.AddMinutes(30), Token = access_token });
- //删除code
- user_code_list.RemoveAll(f => f.Code == code);
- //返回token
- return this.Json(access_token, JsonRequestBehavior.AllowGet);
- }
- //刷新token
- else if (grant_type == "refresh_token")
- {
- //新建token
- string new_access_token = Guid.NewGuid().ToString();
- //替换保存新的token,默认是30分钟
- var user_token = user_token_list.FirstOrDefault(f => f.Code == code);
- user_token.Token = new_access_token;
- user_token.ExpiryDate = DateTime.Now.AddMinutes(30);
- //返回新建的token
- return this.Json(new_access_token, JsonRequestBehavior.AllowGet);
- }
- return this.Json("error grant_type=" + grant_type, JsonRequestBehavior.AllowGet);
- }
- /// <summary>
- /// 通过token获取用户信息
- /// </summary>
- /// <param name="oauth_token"></param>
- /// <returns></returns>
- public ActionResult UserInfo(string token)
- {
- var user_token = user_token_list.FirstOrDefault(f => f.Token == token);
- if (user_token == null || user_token.ExpiryDate < DateTime.Now)
- {
- return this.Json("token无效", JsonRequestBehavior.AllowGet);
- }
- UserInfo u = user_list.FirstOrDefault(f => f.UserName == user_token.UserName);
- return this.Json(u, JsonRequestBehavior.AllowGet);
- }
============ 欢迎各位老板打赏~ ===========
与本文相关的文章
- · asp.net mvc auth2.0简化版——客户端
- · The instance of entity type ‘Customer’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked.
- · .NET8实时更新nginx ip地址归属地
- · 解决.NET Blazor子组件不刷新问题
- · .NET8如何在普通类库中引用 Microsoft.AspNetCore
- · .NET8 Mysql SSL error
- · ASP.NET Core MVC的Razor视图渲染中文乱码的问题
- · .NETCORE 依赖注入服务生命周期
- · asp.net zero改mysql
- · .NET5面试汇总
- · .Net连接Mysql数据库的Convert Zero Datetime日期问题
- · vue使用element-ui中的Message 、MessageBox 、Notification