public async Task <String> GetToken(string userName, String pswd) { using (HttpClient client = new HttpClient()) { client.BaseAddress = this.uriApi; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(this.Header); UserOAuth usuario = new UserOAuth { userName = userName, pswd = pswd }; String json = JsonConvert.SerializeObject(usuario); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); String request = "/api/Auth/Validation"; HttpResponseMessage response = await client.PostAsync(request, content); if (response.IsSuccessStatusCode) { String data = await response.Content.ReadAsStringAsync(); JObject jobject = JObject.Parse(data); String token = jobject.GetValue("response").ToString(); return(token); } else { return(null); } } }
protected override Result <UserOAuth> Callback(string content) { //https://www.douban.com/service/auth2/token //var content = response.Content; var result = new Result <UserOAuth>(); try { JToken error; var data = JObject.Parse(content); if (data.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } var user = new UserOAuth(); var accessToken = data[AccessTokenKey].Value <string>(); var expiresIn = data[ExpiresInKey].Value <int>(); user.AccessToken = accessToken; user.ExpiredOn = DateTime.Now.AddSeconds(expiresIn); user.OpenId = data["douban_user_id"].Value <string>(); } catch (Exception e) { result.Message = e.Message + content; } return(result); }
protected override Result <UserOAuth> Callback(string content) { //https://api.weibo.com/oauth2/access_token var result = new Result <UserOAuth>(); try { JToken error; var data = JObject.Parse(content); if (data.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } var user = new UserOAuth(); var accessToken = data[AccessTokenKey].Value <string>(); var expiresIn = data[ExpiresInKey].Value <int>(); user.AccessToken = accessToken; user.ExpiredOn = DateTime.Now.AddSeconds(expiresIn); user.OpenId = data["uid"].Value <string>(); result.Data = user; result.Status = true; } catch (Exception e) { result.Message = e.Message + content; } return(result); }
public IActionResult Validation(UserOAuth usuario) { Usuario user = this.repo.UserLogin(usuario.userName, usuario.pswd); if (user == null) { return(Unauthorized()); } else { String UserJson = JsonConvert.SerializeObject(user); Claim[] claims = new[] { new Claim("UserData", UserJson) }; JwtSecurityToken token = new JwtSecurityToken( issuer: this.helperToken.Issuer, audience: this.helperToken.Audience, claims: claims, expires: DateTime.UtcNow.AddMinutes(15), notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials(this.helperToken.GetKeyToken(), SecurityAlgorithms.HmacSha256) ); return(Ok(new { response = new JwtSecurityTokenHandler().WriteToken(token) })); } }
protected override Result <UserOAuth> Callback(string content) { //https://api.kaixin001.com/oauth2/access_token //var content = response.Content; var result = new Result <UserOAuth>(); JToken error; var param = JObject.Parse(content); if (param.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } var user = new UserOAuth(); var accessToken = param[AccessTokenKey].Value <string>(); var refreshToken = param[RefreshTokenKey].Value <string>(); var expiresIn = param[ExpiresInKey].Value <int>(); user.AccessToken = accessToken; user.RefreshToken = refreshToken; user.ExpiredOn = DateTime.Now.AddSeconds(expiresIn); if (!string.IsNullOrEmpty(accessToken)) { try { //https://api.kaixin001.com/users/me // todo /* * var request = new RestRequest(OAuth.UserInfoResource); * request.AddParameter(AccessTokenKey, accessToken); * * content = Client.Execute(request).Content; * * var data = JObject.Parse(content); * * if (data.TryGetValue(ErrorKey, out error)) * { * result.Message = error.Value<string>(); * return result; * } * user.OpenId = data["uid"].Value<string>(); * user.Name = data["uname"].Value<string>(); */ result.Data = user; result.Status = true; } catch (Exception e) { result.Message = e.Message + content; } } return(result); }
protected override Result <UserOAuth> Callback(string content) { //https://openapi.360.cn/oauth2/access_token //var content = response.Content; var result = new Result <UserOAuth>(); JToken error; var param = JObject.Parse(content); if (param.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } var user = new UserOAuth(); var accessToken = param[AccessTokenKey].Value <string>(); var refreshToken = param[RefreshTokenKey].Value <string>(); var expiresIn = param[ExpiresInKey].Value <int>(); var scope = param[ScopeKey].Value <string>(); user.Scope = scope; user.AccessToken = accessToken; user.RefreshToken = refreshToken; user.ExpiredOn = DateTime.Now.AddSeconds(expiresIn); if (!string.IsNullOrEmpty(accessToken)) { try { //https://openapi.360.cn/user/me.json var qs = QueryString.Create(AccessTokenKey, accessToken).ToString(); content = Client.GetStringAsync(Provider.UserEndpoint + qs).Result; var data = JObject.Parse(content); if (data.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } user.OpenId = data["id"].Value <string>(); user.OpenName = data["name"].Value <string>(); result.Data = user; result.Status = true; } catch (Exception e) { result.Message = e.Message + content; } } return(result); }
private bool SyncUserOAuth(int userId, UserSignInRequest.AuthParam param) { var o = new UserOAuth(); o.Id = userId; o.Provider = param.Provider; o.AccessToken = param.AccessToken; o.RefreshToken = param.RefreshToken; o.ExpiredOn = DateTime.Now.AddSeconds(param.Expire); return(DefaultStorage.UserOAuthUpdate(o)); }
///<summary> /// 用户第三方授权信息更新 ///</summary> ///<param name="o">用户第三方授权信息</param> ///<returns></returns> public bool UserOAuthUpdate(UserOAuth o) { return(Try(nameof(UserOAuthUpdate), () => { var cmd = SqlBuilder.Update("UserOAuth") .Column("OpenName", o.OpenName) .Column("Scope", o.Scope) .Column("AccessToken", o.AccessToken) .Column("RefreshToken", o.RefreshToken) .Column("ExpiredOn", o.ExpiredOn) .Column("Extra", o.Extra) .Column("ModifiedBy", o.ModifiedBy) .Column("ModifiedOn", o.ModifiedOn) .Where("Id=@id and OpenId=@openId and Provider=@provider", new { o.Id, o.OpenId, o.Provider }) .ToCommand(); return PassportConn.Execute(cmd) > 0; })); }
private bool CreateUserOAuth(int userId, UserSignInRequest.AuthParam param) { var now = DateTime.Now; var o = new UserOAuth(); o.Id = userId; o.OpenId = param.OpenId; o.Provider = param.Provider; o.OpenName = param.OpenName; o.Scope = param.Scope; o.AccessToken = param.AccessToken; o.RefreshToken = param.RefreshToken; o.ExpiredOn = DateTime.Now.AddSeconds(param.Expire); o.CreatedOn = now; o.ModifiedBy = string.Empty; o.ModifiedOn = now; return(DefaultStorage.UserOAuthCreate(o)); }
protected override Result <UserOAuth> Callback(string content) { var result = new Result <UserOAuth>(); try { JToken error; var data = JObject.Parse(content); if (data.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } var user = new UserOAuth(); var accessToken = data[AccessTokenKey].Value <string>(); var expiresIn = data[ExpiresInKey].Value <int>(); user.AccessToken = accessToken; user.ExpiredOn = DateTime.Now.AddSeconds(expiresIn); user.RefreshToken = data[RefreshTokenKey].Value <string>(); user.OpenId = data["unionid"].Value <string>(); if (string.IsNullOrEmpty(user.OpenId)) { user.OpenId = data["openid"].Value <string>(); } user.OpenName = Name; user.Scope = data[ScopeKey].Value <string>(); result.Data = user; result.Status = true; } catch (Exception e) { result.Message = e.Message + content; } return(result); }
///<summary> /// 用户第三方授权信息创建 ///</summary> ///<param name="o">用户第三方授权信息</param> ///<returns></returns> public bool UserOAuthCreate(UserOAuth o) { return(Try(nameof(UserOAuthCreate), () => { var cmd = SqlBuilder.Insert("UserOAuth") .Column("Id", o.Id) .Column("OpenId", o.OpenId) .Column("Provider", o.Provider) .Column("OpenName", o.OpenName) .Column("Scope", o.Scope) .Column("AccessToken", o.AccessToken) .Column("RefreshToken", o.RefreshToken) .Column("ExpiredOn", o.ExpiredOn) .Column("Extra", o.Extra) .Column("CreatedOn", o.CreatedOn) .Column("ModifiedBy", o.ModifiedBy) .Column("ModifiedOn", o.ModifiedOn) .ToCommand(); return PassportConn.Execute(cmd) > 0; })); }
/// <summary> /// 用户在第三方平台登录成功并授权后触发事件 /// </summary> /// <param name="o"></param> protected virtual int OnAuthorized(UserOAuth o) { var handler = Authorized; return(handler?.Invoke(o) ?? 0); }
protected override Result <UserOAuth> Callback(string content) { //https://graph.qq.com/oauth2.0/token //var content = response.Content; var result = new Result <UserOAuth>(); if (content.Contains("callback")) { var lpos = content.IndexOf('('); var rpos = content.IndexOf(')'); content = content.Substring(lpos + 1, rpos - lpos - 1); JToken error; var data = JObject.Parse(content); if (data.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } } var param = QueryHelpers.ParseQuery(content); var user = new UserOAuth(); var accessToken = param[AccessTokenKey]; var expiresIn = Convert.ToInt32(param[ExpiresInKey]); user.AccessToken = accessToken; user.RefreshToken = param[RefreshTokenKey]; user.ExpiredOn = DateTime.Now.AddSeconds(expiresIn); if (!string.IsNullOrEmpty(accessToken)) { var qs = QueryString.Create(AccessTokenKey, accessToken).ToString(); content = Client.GetStringAsync(Provider.UserEndpoint + qs).Result; /* * var request = new RestRequest(OAuth.UserInfoResource); * request.AddParameter(AccessTokenKey, accessToken); * content = Client.Execute(request).Content; * * var lpos = content.IndexOf('('); * var rpos = content.IndexOf(')'); * content = content.Substring(lpos + 1, rpos - lpos - 1); */ try { JToken error; var data = JObject.Parse(content); if (data.TryGetValue(ErrorKey, out error)) { result.Message = error.Value <string>(); return(result); } user.OpenId = data["openid"].Value <string>(); result.Data = user; result.Status = true; } catch (Exception e) { result.Message = e.Message + content; } } return(result); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { // configure app settings // Get global administrators list and cast to int[] _ApplicationSettings.GlobalAdministrators = _config.GetSection("SiteSettings:GlobalAdministrators") .AsEnumerable() .Where(x => x.Value != null) .Select(x => int.Parse(x.Value)) .ToArray(); _ApplicationSettings.LogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), _config["Logging:Level"]); // inject redis and app settings IDatabase Redis = RedisStore.RedisCache; services.AddScoped(_ => Redis); services.AddScoped(_ => _ApplicationSettings); var OAuthService = services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => options = new CookieAuthenticationOptions { LoginPath = new PathString("/Login"), LogoutPath = new PathString("/Logout"), AccessDeniedPath = "/", ExpireTimeSpan = new TimeSpan(30, 0, 0, 0), SlidingExpiration = true }); var loginProviders = _ApplicationSettings.OAuthProviders; foreach (var loginProvider in loginProviders) { OAuthService.AddOAuth(loginProvider.AuthenticationScheme, options => { options.ClientId = loginProvider.ClientId; options.ClientSecret = loginProvider.ClientSecret; options.SaveTokens = loginProvider.SaveTokens; options.AuthorizationEndpoint = loginProvider.AuthorizationEndpoint; options.TokenEndpoint = loginProvider.TokenEndpoint; options.UserInformationEndpoint = loginProvider.UserInformationEndpoint; options.CallbackPath = new PathString(loginProvider.CallbackPath); foreach (var scope in loginProvider.Scope) { options.Scope.Add(scope); } // This looks f*****g ugly though, need to find out how to move it to a class options.Events = new OAuthEvents { // https://auth0.com/blog/authenticating-a-user-with-linkedin-in-aspnet-core/ // The OnCreatingTicket event is called after the user has been authenticated and the OAuth middleware has // created an auth ticket. We need to manually call the UserInformationEndpoint to retrieve the user's information, // parse the resulting JSON to extract the relevant information, and add the correct claims. OnCreatingTicket = async context => { await UserOAuth.RegisterUser(context, loginProvider, Redis, _ApplicationSettings); },/* * // Here until I figure out what magic kestrel needs to actually work with https. * // Apparently it's not a thing you should do (which is why I have it proxied behind nginx): https://github.com/aspnet/KestrelHttpServer/issues/1108 * // but it's still f*****g annoying having my redirect_uri's going to http, because https causes a weird handshake bug because asdfklsflkashfdaslkf * // I'm a "professional", btw. There's no way you'd actually think that looking at my code though. * OnRedirectToAuthorizationEndpoint = context => { * var uri = HttpUtility.ParseQueryString(context.RedirectUri); * uri["redirect_uri"] = uri["redirect_uri"].Replace("http","https"); * context.Response.Redirect(uri.ToString()); * return Task.FromResult(0); * },*/ OnRemoteFailure = async context => { await UserOAuth.OAuthRemoteFailure(context, loginProvider, Redis, _ApplicationSettings); context.HttpContext.Response.StatusCode = 500; } }; }); } // configure MVC // Debug ssl fix, all you have to do is enable ssl, ctrl+f5 so it won't go into debug mode, jump into IE to install the cert // the-get f****d that's f*****g stupid but it works // https://stackoverflow.com/questions/40965442/an-error-occurred-attempting-to-determine-the-process-id-of-dotnet-exe-which-is // not doing ssl anyway, but for reference when I change my mind later services.AddMvc(Options => { Options.RespectBrowserAcceptHeader = true; }) .AddMvcOptions(Options => { Options.Filters.Add(new ActionFilter(Redis)); }); }
/// <summary> /// 用户在第三方平台登录成功并授权后触发 /// 生成系统帐号 /// </summary> /// <param name="o"></param> /// <returns>用户Id</returns> private int Authorized(UserOAuth o) { int userId; var openUser = DefaultStorage.UserOAuthGet(o.Provider, o.OpenId); if (openUser != null) { userId = openUser.Id; Task.Factory.StartNew(() => { o.Id = userId; o.CreatedOn = DateTime.Now; try { DefaultStorage.UserOAuthUpdate(o); } catch (Exception e) { Logger.LogError(1, "OAuth {0} Authorized UserOAuthUpdate 失败 UserId({1}} {2}", o.Provider, userId, e.Message); } }); } else { userId = DefaultStorage.UserIdGet(o.OpenId, o.Provider); if (userId == 0) { var user = new User(); var profile = new UserProfile(); var now = DateTime.Now; user.Guid = Guid.NewGuid().ToString("N"); user.Name = o.OpenId; user.Email = string.Empty; user.Mobile = string.Empty; user.Nickname = o.OpenName ?? ""; user.Password = string.Empty; user.Role = UserRole.Buyer; user.Grade = UserGrade.One; user.Limitation = UserLimitation.None; user.Permission = UserPermission.None; user.Avatar = string.Empty; user.Status = UserStatus.Normal; user.AuthedOn = null; user.CreatedBy = o.Provider; user.CreatedOn = now; user.ModifiedBy = ""; user.ModifiedOn = now; profile.Code = string.Empty; profile.Name = string.Empty; profile.Gender = Gender.Secrect; profile.Marital = Marital.Secrect; profile.Birthday = null; profile.Phone = string.Empty; profile.Mobile = string.Empty; profile.RegionId = string.Empty; profile.Street = string.Empty; profile.SignUpIp = ""; profile.SignUpBy = 0; profile.TraceCode = ""; profile.LastSignInIp = ""; profile.LastSignInOn = now; user.Profile = profile; userId = DefaultStorage.UserCreate(user); } if (userId > 0) { Task.Factory.StartNew(() => { o.Id = userId; o.CreatedOn = DateTime.Now; try { DefaultStorage.UserOAuthCreate(o); } catch (Exception e) { Logger.LogError(1, "OAuth {0} Authorized UserOAuthCreate 失败 UserId({1}} {2}", o.Provider, userId, e.Message); } }); } } return(userId); }