public IActionResult SignIn([FromQuery] string login = "", [FromQuery] string password = "") { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) { return(BadRequest()); } var user = db.Users .Where(u => u.Login == login) .Where(u => u.Password == Security.ValidatePassword(password, u.Salt)) .SingleOrDefault(); if (user == null) { return(BadRequest("Неправильно введен login или password")); } else { return(Ok(new { id_user = user.Id, user.Name, user.Surname, token = Jwt.CreateToken(user.Login, user.Role, signingSymmetricKey) })); } }
public async Task <Response> SignIn(CollaboratorViewModel model) { try { Collaborator _collaborator = null; if (!string.IsNullOrEmpty(model.Email)) { _collaborator = await this._repository.GetByEmail(model.Email); } if (_collaborator != null) { bool authorized = Crypto.ComparePassword(model.Password, new Encoded(_collaborator.Password)); if (authorized) { var _model = this._mapper.Map <CollaboratorViewModel>(_collaborator); var _auth = new Auth <CollaboratorViewModel>(Jwt.CreateToken(model.Email), _model); return(Ok(_auth, HttpMessage.Login_Authorized)); } else { return(Unauthorized("A conta informada é inválida!")); } } else { return(Unauthorized("A conta informada é inválida!")); } } catch (Exception except) { return(await InternalServerError(except.Message)); } }
public Response <JwtDto> Login(string account, string password) { var response = new Response <JwtDto>(); var user = students.SingleOrDefault(t => t.Account == account); if (user != null) { if (user.Password.Equals(password)) { response.Msg = "登录成功"; var token = new JwtDto() { AccessToken = Jwt.CreateToken(user, TokenType.AccessToken), RefreshToken = Jwt.CreateToken(user, TokenType.RefreshToken) }; response.Data = token; } else { response.Status = 400; response.Msg = "用户密码不正确!"; } } else { response.Status = 400; response.Msg = "用户名不存在!"; } return(response); }
public Task <Result <LoginResponse> > Get(LoginUserRequest req) => _db.QuerySingle <AccountRecord>(@"SELECT UserId, Password FROM NotifyApp.Users WHERE IsDisabled = 0 AND Email = @email", new { email = req.Email }) .Then(x => BCrypt.Net.BCrypt.Verify(req.Password, x.Password) ? Result.Success(x) : Result.Errored <AccountRecord>(ResultStatus.InvalidRequest, "Unauthorized")) .Then(x => new LoginResponse { Token = Jwt.CreateToken(_secret, x.UserId.ToString().PadLeft(16), req.Email) });
public Response <string> RefreshToken(string refreshToken) { Student student; var response = new Response <string>(); if (Jwt.ValidateRefreshToken(refreshToken.ToStringX().Replace("Bearer ", ""), out student)) { response.Data = Jwt.CreateToken(student, TokenType.AccessToken); } else { response.Status = 401; response.Msg = "Unauthorized"; } return(response); }
public void should_generate_jwt() { var mockAppId = "ffffffff-ffff-ffff-ffff-ffffffffffff"; var mockRsaPrivateKey = @"-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQCRgWt83vGoI2vx+BIu1R39nLDvGLEvC8R4drrIvsiJkAvIlVZt PlbeoifYJGDQwtlAR3a8i+B3/AP5tZEoWw+z+VWLX50aRjzHyTn22ih8OeGDoiBw N3ysCTfQ/x8sDER6uSn8ElxfB9AEZTcRA+4rCRbmj+YLV/Nm+qSNoOIM4wIDAQAB AoGAC8IZnY2mmZ/DKVqSnZY7RjNTWP710odw6QsvLOm96t/pE9x9j3ZqLrOL5LuL 11Lnm3oq7jGfghKrf5JcmJZDPnhWoGgZvtqFizt1l6y1GY/xlooWhOzEuK9kIrBS PDhOjnvmLrQIB88Rjgq0LkxjNYsCa5d1zslkB2SfM7sOF4ECQQDkEzk/J0KnAa14 +T00BD5apQsDMU7Tz3aPA1IbmqsKY6wOuHcxrFBMmw3crce6jjq32w36samIPSwG ucf/JngtAkEAo1IjyJLlVlFA74lGTJTbZ5drrotoYm/YeAnbe6Rhj6pXDfz+lVdQ 5ta/B0TKa1UEgx7pHs39Tmpl2IdfC5ozTwJBANVvL/lrsjI7na1CAQZ2miuVm9Kn CA+rbFW1U9dFTJ7yW4eDFPhFOvgVeklzzx9EDqsTsedS70XxiQvaO9EInRkCQFKn TELCzNvNTU6sq24wW4VmpXF1TgObVPMTEgfV3iYF7/69Td4ojWH1xkGYd9Sv9xOg vhv/5bUctaRKhjhp9pMCQE8BLxzAMlS81dobP3GrCRLdlN/y9R7pu2hyURFFXUw5 j0hq3fgBZz1QLpLxY3TfkM3oFDVhpGvskzjINLk6hxc= -----END RSA PRIVATE KEY-----"; var tok = Jwt.CreateToken(mockAppId, mockRsaPrivateKey); Assert.IsFalse(string.IsNullOrEmpty(tok)); }
private static string DoRequest(Uri uri, Credentials creds = null) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var req = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get, }; SetUserAgent(ref req, creds); // attempt bearer token auth req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); using (LogProvider.OpenMappedContext("VersionedApiRequest.DoRequest", uri.GetHashCode())) { Logger.Debug($"GET {uri}"); var sendTask = Configuration.Instance.Client.SendAsync(req); sendTask.Wait(); if (!sendTask.Result.IsSuccessStatusCode) { Logger.Error($"FAIL: {sendTask.Result.StatusCode}"); if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"], "true", StringComparison.OrdinalIgnoreCase) == 0) { sendTask.Result.EnsureSuccessStatusCode(); } } string json; var readTask = sendTask.Result.Content.ReadAsStreamAsync(); readTask.Wait(); using (var sr = new StreamReader(readTask.Result)) { json = sr.ReadToEnd(); } Logger.Debug(json); return(json); } }
/// <summary> /// Send a request to the versioned Nexmo API. /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter. /// </summary> /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param> /// <param name="uri">The URI to communicate with</param> /// <param name="payload">Parameters required by the endpoint (do not include credentials)</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static NexmoResponse DoRequest(string method, Uri uri, object payload, Credentials creds = null) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var req = new HttpRequestMessage { RequestUri = uri, Method = new HttpMethod(method), }; SetUserAgent(ref req, creds); // do we need to use basic auth? // TODO / HACK: this is a newer auth method that needs to be incorporated better in the future if (uri.AbsolutePath.StartsWith("/accounts/") || uri.AbsolutePath.StartsWith("/v2/applications")) { var authBytes = Encoding.UTF8.GetBytes(creds.ApiKey + ":" + creds.ApiSecret); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes)); } else { // attempt bearer token auth req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); } var data = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore })); req.Content = new ByteArrayContent(data); req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); using (LogProvider.OpenMappedContext("VersionedApiRequest.DoRequest", uri.GetHashCode())) { Logger.Debug($"{method} {uri} {payload}"); var sendTask = Configuration.Instance.Client.SendAsync(req); sendTask.Wait(); if (!sendTask.Result.IsSuccessStatusCode) { Logger.Error($"FAIL: {sendTask.Result.StatusCode}"); if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"], "true", StringComparison.OrdinalIgnoreCase) == 0) { sendTask.Result.EnsureSuccessStatusCode(); } return(new NexmoResponse { Status = sendTask.Result.StatusCode }); } string json; var readTask = sendTask.Result.Content.ReadAsStreamAsync(); readTask.Wait(); using (var sr = new StreamReader(readTask.Result)) { json = sr.ReadToEnd(); } Logger.Debug(json); return(new NexmoResponse { Status = sendTask.Result.StatusCode, JsonResponse = json }); } }
/// <summary> /// Sends a GET request to the Nexmo API using a JWT and returns the full HTTP resonse message /// this is primarily for pulling a raw stream off an API call -e.g. a recording /// </summary> /// <param name="uri"></param> /// <param name="creds"></param> /// <returns>HttpResponseMessage</returns> /// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception> public static HttpResponseMessage DoGetRequestWithJwt(Uri uri, Credentials creds) { var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY); var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var req = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get }; SetUserAgent(ref req, creds); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); logger.LogDebug($"GET {uri}"); var result = Configuration.Instance.Client.SendAsync(req).Result; try { result.EnsureSuccessStatusCode(); return(result); } catch (HttpRequestException ex) { logger.LogError($"FAIL: {result.StatusCode}"); throw new NexmoHttpRequestException(ex.Message, ex) { HttpStatusCode = result.StatusCode }; } }
/// <summary> /// Send a request to the versioned Nexmo API. /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter. /// </summary> /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param> /// <param name="uri">The URI to communicate with</param> /// <param name="payload">Parameters required by the endpoint (do not include credentials)</param> /// <param name="authType">Authorization type used on the API</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <exception cref="NexmoHttpRequestException">thrown if an error is encountered when talking to the API</exception> public static T DoRequestWithJsonContent <T>(string method, Uri uri, object payload, AuthType authType, Credentials creds) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower(); var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"]; var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY); var req = new HttpRequestMessage { RequestUri = uri, Method = new HttpMethod(method), }; SetUserAgent(ref req, creds); if (authType == AuthType.Basic) { var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes)); } else if (authType == AuthType.Bearer) { // attempt bearer token auth req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); } else if (authType == AuthType.Query) { var sb = BuildQueryString(new Dictionary <string, string>(), creds); req.RequestUri = new Uri(uri + (sb.Length != 0 ? "?" + sb : "")); } else { throw new ArgumentException("Unkown Auth Type set for function"); } var json = JsonConvert.SerializeObject(payload, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); logger.LogDebug($"Request URI: {uri}"); logger.LogDebug($"JSON Payload: {json}"); var data = Encoding.ASCII.GetBytes(json); req.Content = new ByteArrayContent(data); req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var json_response = SendHttpRequest(req).JsonResponse; return(JsonConvert.DeserializeObject <T>(json_response)); }
/// <summary> /// Sends an HTTP GET request to the Nexmo API without any additional parameters /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uri"></param> /// <param name="authType"></param> /// <param name="creds"></param> /// <exception cref="NexmoHttpRequestException">Thrown if the API encounters a non-zero result</exception> private static T SendGetRequest <T>(Uri uri, AuthType authType, Credentials creds) { var logger = Logger.LogProvider.GetLogger(LOGGER_CATEGORY); var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var apiKey = (creds?.ApiKey ?? Configuration.Instance.Settings["appSettings:Nexmo.api_key"])?.ToLower(); var apiSecret = creds?.ApiSecret ?? Configuration.Instance.Settings["appSettings:Nexmo.api_secret"]; var req = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get }; SetUserAgent(ref req, creds); if (authType == AuthType.Basic) { var authBytes = Encoding.UTF8.GetBytes(apiKey + ":" + apiSecret); req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes)); } else if (authType == AuthType.Bearer) { req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); } logger.LogDebug($"GET {uri}"); var json = SendHttpRequest(req).JsonResponse; return(JsonConvert.DeserializeObject <T>(json)); }
private static string DoRequest(Uri uri, Credentials creds = null) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var req = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get, }; SetUserAgent(ref req); // attempt bearer token auth req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); using (Configuration.Instance.ApiLogger.BeginScope("VersionedApiRequest.DoRequest {0}", uri.GetHashCode())) { Configuration.Instance.ApiLogger.LogDebug($"GET {uri}"); var sendTask = Configuration.Instance.Client.SendAsync(req); sendTask.Wait(); //if (!sendTask.Result.IsSuccessStatusCode) // throw new Exception("Error while retrieving resource."); string json; var readTask = sendTask.Result.Content.ReadAsStreamAsync(); readTask.Wait(); using (var sr = new StreamReader(readTask.Result)) { json = sr.ReadToEnd(); } Configuration.Instance.ApiLogger.LogDebug(json); return(json); } }
/// <summary> /// Send a request to the versioned Nexmo API. /// Do not include credentials in the parameters object. If you need to override credentials, use the optional Credentials parameter. /// </summary> /// <param name="method">HTTP method (POST, PUT, DELETE, etc)</param> /// <param name="uri">The URI to communicate with</param> /// <param name="payload">Parameters required by the endpoint (do not include credentials)</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static NexmoResponse DoRequest(string method, Uri uri, object payload, Credentials creds = null) { var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"]; var appKeyPath = creds?.ApplicationKey ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]; var req = new HttpRequestMessage { RequestUri = uri, Method = new HttpMethod(method), }; SetUserAgent(ref req); // attempt bearer token auth req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Jwt.CreateToken(appId, appKeyPath)); var data = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload)); req.Content = new ByteArrayContent(data); req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); using (Configuration.Instance.ApiLogger.BeginScope("ApiRequest.DoRequest {0}", uri.GetHashCode())) { Configuration.Instance.ApiLogger.LogDebug($"{method} {uri} {payload}"); var sendTask = Configuration.Instance.Client.SendAsync(req); sendTask.Wait(); if (!sendTask.Result.IsSuccessStatusCode) { Configuration.Instance.ApiLogger.LogError($"FAIL: {sendTask.Result.StatusCode}"); return(new NexmoResponse { Status = sendTask.Result.StatusCode }); } string json; var readTask = sendTask.Result.Content.ReadAsStreamAsync(); readTask.Wait(); using (var sr = new StreamReader(readTask.Result)) { json = sr.ReadToEnd(); } Configuration.Instance.ApiLogger.LogDebug(json); return(new NexmoResponse { Status = sendTask.Result.StatusCode, JsonResponse = json }); } }
public void should_generate_jwt() { var tok = Jwt.CreateToken(Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"], Configuration.Instance.Settings["appSettings:Nexmo.Application.Key"]); Assert.IsFalse(string.IsNullOrEmpty(tok)); }