private static AuthorizationRequest createAuthorizationRequest(string securityNameSpace, string action) { AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.Namespace = securityNameSpace; authorizationRequest.Action = action; return authorizationRequest; }
public void UpdateProfile(AuthorizationRequest clientRequest) { this.Name = clientRequest.Name; this.Surname = clientRequest.Surname; this.Status = true; Debug.Log("Updating profile from client request. [{0} {1}]", this.Name, this.Surname); }
public string GetAuthorizationUrl(AuthorizationRequest request) { return String.Format(CultureInfo.InvariantCulture, AuthorizeUrl, Uri.EscapeDataString(AppConstants.OneDriveClientId), Uri.EscapeDataString(AppConstants.oneDriveResourceId), Uri.EscapeDataString(RedirectUrl.ToString()) ); }
public Tuple<string, object> GetAuthorizationView(AuthorizationRequest request, NancyContext context) { var application = this.applicationStore.First(app => app.Id.ToString().Equals(request.ClientId, StringComparison.OrdinalIgnoreCase)); return new Tuple<string, object>( "authorize", new AuthorizeViewModel { Body = "View model body", Name = application.Name, Description = application.Description, Permissions = application.Permissions }); }
public ConsentViewModel(ConsentInputModel model, string returnUrl, AuthorizationRequest request, Client client, IEnumerable<Scope> scopes) { RememberConsent = model?.RememberConsent ?? true; ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(); ReturnUrl = returnUrl; ClientName = client.ClientName; ClientUrl = client.ClientUri; ClientLogoUrl = client.LogoUri; AllowRememberConsent = client.AllowRememberConsent; IdentityScopes = scopes.Where(x => x.Type == ScopeType.Identity).Select(x => new ScopeViewModel(x, ScopesConsented.Contains(x.Name) || model == null)).ToArray(); ResourceScopes = scopes.Where(x => x.Type == ScopeType.Resource).Select(x => new ScopeViewModel(x, ScopesConsented.Contains(x.Name) || model == null)).ToArray(); }
public async Task<AuthorizationToken> ObtainAccessAuthorizationToken(AuthorizationRequest authorizationRequest) { var baseAddress = new Uri("https://api.neteller.com/v1/"); using (var httpClient = new HttpClient { BaseAddress = baseAddress }) { httpClient.DefaultRequestHeaders.TryAddWithoutValidation( "authorization", this.BuildBasicAuthorizationHeader(authorizationRequest.ClientId, authorizationRequest.ClientSecret)); using (var content = new StringContent(string.Empty, Encoding.Default, "multipart/form-data")) { using (var response = await httpClient.PostAsync("oauth2", content)) { return JsonConvert.DeserializeObject<AuthorizationToken>(await response.Content.ReadAsStringAsync()); } } } }
public ConsentViewModel(ConsentInputModel model, string returnUrl, AuthorizationRequest request, Client client, Resources resources) { RememberConsent = model?.RememberConsent ?? true; ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(); ReturnUrl = returnUrl; ClientName = client.ClientName; ClientUrl = client.ClientUri; ClientLogoUrl = client.LogoUri; AllowRememberConsent = client.AllowRememberConsent; IdentityScopes = resources.IdentityResources.Select(x => new ScopeViewModel(x, ScopesConsented.Contains(x.Name) || model == null)).ToArray(); ResourceScopes = resources.ApiResources.SelectMany(x=>x.Scopes).Select(x => new ScopeViewModel(x, ScopesConsented.Contains(x.Name) || model == null)).ToArray(); if (resources.OfflineAccess) { ResourceScopes = ResourceScopes.Union(new ScopeViewModel[] { ScopeViewModel.GetOfflineAccess(ScopesConsented.Contains(IdentityServerConstants.StandardScopes.OfflineAccess) || model == null) }); } }
async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl, AuthorizationRequest context) { var providers = HttpContext.Authentication.GetAuthenticationSchemes() .Where(x => x.DisplayName != null) .Select(x => new ExternalProvider { DisplayName = x.DisplayName, AuthenticationScheme = x.AuthenticationScheme }); var allowLocal = true; if (context?.ClientId != null) { var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId); if (client != null) { allowLocal = client.EnableLocalLogin; if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any()) { providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)); } } } return new LoginViewModel { EnableLocalLogin = allowLocal, ReturnUrl = returnUrl, Email = context?.LoginHint, ExternalProviders = providers.ToArray() }; }
protected void Page_Load(object sender, EventArgs e) { HttpContext context = HttpContext.Current; //string IP4Address = (string)(context.Session["IP4Address"]); string sesionPay = (string)(context.Session["sesionPay"]); string transactionToken = Request.Form["transactionToken"]; //string customerEmail = Request.Form["customerEmail"]; string channel = Request.Form["channel"]; string _cardHolder = (string)(context.Session["_cardHolder"]); string _recurrence = (string)(context.Session["_recurrence"]); string _order = (string)(context.Session["_order"]); DataContractJsonSerializer serCardHolder = new DataContractJsonSerializer(typeof(CardHolder)); MemoryStream msCardHolder = new MemoryStream(Encoding.UTF8.GetBytes(_cardHolder)); CardHolder _objCardHolder = (CardHolder)serCardHolder.ReadObject(msCardHolder); DataContractJsonSerializer serRecurrence = new DataContractJsonSerializer(typeof(Recurrence)); MemoryStream msRecurrence = new MemoryStream(Encoding.UTF8.GetBytes(_recurrence)); Recurrence _objRecurrence = (Recurrence)serRecurrence.ReadObject(msRecurrence); DataContractJsonSerializer serOrder = new DataContractJsonSerializer(typeof(Order)); MemoryStream msOrder = new MemoryStream(Encoding.UTF8.GetBytes(_order)); Order _objOrder = (Order)serOrder.ReadObject(msOrder); Order objOrder = new Order(); objOrder.tokenId = transactionToken; objOrder.productId = _objOrder.productId; //341198214 - REC VISANET objOrder.purchaseNumber = _objOrder.purchaseNumber; objOrder.amount = _objOrder.amount; objOrder.currency = _objOrder.currency; CardHolder objCardHolder = new CardHolder(); objCardHolder.documentType = _objCardHolder.documentType; //0= DNI, 1= Canet de extranjería, 2= Pasaporte objCardHolder.documentNumber = _objCardHolder.documentNumber; Recurrence objRecurrence = new Recurrence(); objRecurrence.beneficiaryId = _objRecurrence.beneficiaryId; objRecurrence.type = _objRecurrence.type; objRecurrence.frequency = _objRecurrence.frequency; objRecurrence.maxAmount = _objRecurrence.maxAmount; objRecurrence.amount = _objRecurrence.amount; AuthorizationRequest objAuthorizationRequest = new AuthorizationRequest(); objAuthorizationRequest.channel = channel; objAuthorizationRequest.captureType = "manual"; objAuthorizationRequest.countable = true; objAuthorizationRequest.order = objOrder; objAuthorizationRequest.cardHolder = objCardHolder; objAuthorizationRequest.recurrence = objRecurrence; string body = JsonHelper.JsonSerializer <AuthorizationRequest>(objAuthorizationRequest); merchantId = (string)(context.Session["_merchantId"]); endpointurl = ConfigurationManager.AppSettings["endpointurl"]; url = "https://" + endpointurl + "/api.authorization/v3/authorization/ecommerce/" + merchantId; HttpWebRequest request; request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add("Authorization", sesionPay); StreamWriter writer; writer = new StreamWriter(request.GetRequestStream()); writer.Write(body); writer.Close(); HttpWebResponse response; StreamReader reader; string respuesta; try { response = request.GetResponse() as HttpWebResponse; reader = new StreamReader(response.GetResponseStream()); respuesta = reader.ReadToEnd(); reader.Close(); } catch (WebException ex) { reader = new StreamReader(ex.Response.GetResponseStream(), true); respuesta = reader.ReadToEnd(); reader.Close(); } Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(respuesta); Response.End(); }
private ConsentViewModel CreateConsentViewModel(ConsentInputModel model, string returnUrl, AuthorizationRequest request, Client client, Resources resources) { var vm = new ConsentViewModel { RememberConsent = model?.RememberConsent ?? true, ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty <string>(), ReturnUrl = returnUrl, ClientName = client.ClientName ?? client.ClientId, ClientUrl = client.ClientUri, ClientLogoUrl = client.LogoUri, AllowRememberConsent = client.AllowRememberConsent }; vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess) { vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] { GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null) }); } return(vm); }
/// <summary> /// Checks if the redirect URI is for a native client. /// </summary> /// <returns></returns> public static bool IsNativeClient(this AuthorizationRequest context) { return(!context.RedirectUri.StartsWith("https", StringComparison.Ordinal) && !context.RedirectUri.StartsWith("http", StringComparison.Ordinal)); }
public static void Thread1(object sock) { int maDH; Console.WriteLine("start connect with customer client"); X509Certificate2 caCertificate = new X509Certificate2("d:/file/ca.crt"); string gatewayPublicKey; string merchantPrivateKey = File.ReadAllText("d:/file/MerchantPrivateKey.xml"); X509Certificate2 merchantCertificate = new X509Certificate2("d:/file/merchant.crt"); X509Certificate2 gatewayCertificate = new X509Certificate2("d:/file/gateway.crt"); X509Certificate2 customerCertificate; Common c = new Common(); Socket socket = (Socket)sock; string receiveMessage = c.receive(ref socket); string[] firstMessage = receiveMessage.Split('-'); string s; //thông điệp nhận được là Hủy đơn hàng hoặc init request if (firstMessage[0].CompareTo("HUYDONHANG") == 0) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "localhost"; builder.UserID = "sa"; builder.Password = "******"; builder.InitialCatalog = "QuanLyBanSach"; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); string sql; StringBuilder sb = new StringBuilder(); sb.Append("DELETE FROM ChiTietDonHang WHERE MaDonHang = @maDH;"); sql = sb.ToString(); using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@maDH", firstMessage[1]); int rowsAffected = command.ExecuteNonQuery(); } sb.Clear(); sb.Append("DELETE FROM DonHang WHERE MaDonHang = @maDH;"); sql = sb.ToString(); using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@maDH", firstMessage[1]); int rowsAffected = command.ExecuteNonQuery(); } connection.Close(); } } else { InitiateRequest initiateRequest = new InitiateRequest(firstMessage[0], firstMessage[1], firstMessage[2], firstMessage[3], firstMessage[4]); //tạo init response gatewayPublicKey = gatewayCertificate.GetRSAPublicKey().ToXmlString(false); InitiateResponse initiateResponse = new InitiateResponse(initiateRequest.getLIDC(), initiateRequest.getLanguage(), initiateRequest.getRRPID(), initiateRequest.getBrandID(), c.ByteArrayToString(merchantCertificate.GetRawCertData()), c.ByteArrayToString(gatewayCertificate.GetRawCertData())); string sendMessage = initiateResponse.ToMessage(merchantPrivateKey); c.send(sendMessage, ref socket); //nhận purchase request receiveMessage = c.receive(ref socket); string[] purchase = receiveMessage.Split('-'); customerCertificate = new X509Certificate2(c.StringToByteArray(purchase[5])); if (c.VerifyCertificate(caCertificate, customerCertificate) == false) { Console.WriteLine("verify purchase request certificate false"); s = initiateResponse.getTransID() + ":" + c.Random(2) + ":" + 4 + ":" + "xac thuc that bai"; PurchaseResponse purchaseResponse = new PurchaseResponse(s); c.send(purchaseResponse.ToMessage(), ref socket); } else { PurchaseRequest purchaseRequest = new PurchaseRequest(purchase[0], purchase[1], purchase[2], purchase[3], purchase[4], purchase[5]); if (purchaseRequest.verify() == false)//xác thực purchase request { Console.WriteLine("verify purchase request false"); s = initiateResponse.getTransID() + ":" + purchaseRequest.getRRPID() + ":" + 4 + ":" + "xac thuc that bai"; PurchaseResponse purchaseResponse = new PurchaseResponse(s); c.send(purchaseResponse.ToMessage(), ref socket); } else { Console.WriteLine("verify purchase request true"); maDH = purchaseRequest.getMaDH(); //tạo authorization request gửi tới gateway AuthorizationRequest authorizationRequest = new AuthorizationRequest(purchaseRequest.getTransID(), Convert.ToDouble(purchaseRequest.getTien()), merchantPrivateKey, gatewayPublicKey, purchaseRequest.getCustommerCertificate(), c.ByteArrayToString(merchantCertificate.GetRawCertData()), purchaseRequest.getMessageToGateway(), purchaseRequest.getDigitalEnvelop()); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1235); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(iep); c.send(authorizationRequest.ToMessage(), ref client); //nhận authorization response receiveMessage = c.receive(ref client); string[] splitAuthRES = receiveMessage.Split('-'); AuthorizationResponse authorizationResponse; if (splitAuthRES.Length < 5)//trường hợp nhận thông báo lỗi từ isuuer { gatewayCertificate = new X509Certificate2(c.StringToByteArray(splitAuthRES[3])); if (c.VerifyCertificate(caCertificate, gatewayCertificate) == true)//kiểm tra chứng chỉ nhận từ gateway { Console.WriteLine("verify authorization response certificate true"); authorizationResponse = new AuthorizationResponse(splitAuthRES[0], splitAuthRES[1], splitAuthRES[2], splitAuthRES[3]); if (authorizationResponse.verifyMessage() == true) { Console.WriteLine("verify authorization response true"); //tạo purchase response và gởi customer string[] messageRES = authorizationResponse.getMessage().Split(':'); PurchaseResponse purchaseResponse = new PurchaseResponse(messageRES[0] + ":" + purchaseRequest.getRRPID() + ":" + messageRES[2] + ":" + messageRES[3]); c.send(purchaseResponse.ToMessage(), ref socket); } } } else { gatewayCertificate = new X509Certificate2(c.StringToByteArray(splitAuthRES[6])); if (c.VerifyCertificate(caCertificate, gatewayCertificate) == true)//kiểm tra chứng chỉ nhận từ gateway { Console.WriteLine("verify authorization response certificate true"); authorizationResponse = new AuthorizationResponse(splitAuthRES[0], splitAuthRES[1], splitAuthRES[2], splitAuthRES[3], splitAuthRES[4], splitAuthRES[5], splitAuthRES[6]); if (authorizationResponse.verifyMessage() == true) { Console.WriteLine("verify authorization response true"); //lưu token SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "localhost"; builder.UserID = "sa"; builder.Password = "******"; builder.InitialCatalog = "Bank"; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); string sql; StringBuilder sb = new StringBuilder(); sb.Clear(); sb.Append("INSERT Token (TransID, SignToken, EncryptToken, EncryptKey) "); sb.Append("VALUES (@id, @sign, @token, @key);"); sql = sb.ToString(); using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@id", authorizationResponse.getTransID()); command.Parameters.AddWithValue("@sign", authorizationResponse.getSignToken()); command.Parameters.AddWithValue("@token", authorizationResponse.getEncryptToken()); command.Parameters.AddWithValue("@key", authorizationResponse.getEncryptKeyToken()); int rowsAffected = command.ExecuteNonQuery(); } connection.Close(); } //tạo purchase response và gởi customer string[] messageRES = authorizationResponse.getMessage().Split(':'); PurchaseResponse purchaseResponse = new PurchaseResponse(messageRES[0] + ":" + purchaseRequest.getRRPID() + ":" + messageRES[2] + ":" + messageRES[3]); c.send(purchaseResponse.ToMessage(), ref socket); //Console.WriteLine(purchaseResponse.getMessage()); //tạo capture request gửi tới gateway string merchantCard = "012541AR09O5"; string merchantCVV = "012345"; string merchantDateValid = "25062019"; //---->lấy token string signToken = "", encryptToken = "", encryptKeyToken = ""; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); string sql; sql = "SELECT TransID, SignToken, EncryptToken, EncryptKey FROM Token;"; using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader sqlReader = command.ExecuteReader()) { while (sqlReader.Read()) { if (sqlReader.GetString(0).CompareTo(authorizationResponse.getTransID()) == 0) { signToken = sqlReader.GetString(1); encryptToken = sqlReader.GetString(2); encryptKeyToken = sqlReader.GetString(3); } } } } connection.Close(); } CaptureRequest captureRequest = new CaptureRequest(purchaseRequest.getTransID(), merchantCard, merchantCVV, merchantDateValid, Convert.ToInt64(purchaseRequest.getTien()), gatewayPublicKey, signToken, encryptToken, encryptKeyToken); c.send(captureRequest.ToMessage(), ref client); //nhận capture response từ gateway receiveMessage = c.receive(ref client); string[] splitCaptureResponse = receiveMessage.Split('-'); gatewayCertificate = new X509Certificate2(c.StringToByteArray(splitCaptureResponse[3])); if (c.VerifyCertificate(caCertificate, gatewayCertificate) == true) { Console.WriteLine("verify capture response certificate true"); CaptureResponse captureResponse = new CaptureResponse(splitCaptureResponse[0], splitCaptureResponse[1], splitCaptureResponse[2], splitCaptureResponse[3]); if (captureResponse.verify() == true) { Console.WriteLine("verify capture response true"); using (SqlConnection connection = new SqlConnection(builder.ConnectionString))//lưu capture response { connection.Open(); string sql; StringBuilder sb = new StringBuilder(); sb.Clear(); //lưu capture response sb.Append("INSERT LogCaptureResponse (SignMessage, EncryptMessage, EncryptKey) "); sb.Append("VALUES (@sign, @encrypt, @key);"); sql = sb.ToString(); using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@sign", captureResponse.getSignMessage()); command.Parameters.AddWithValue("@encrypt", captureResponse.getEncryptMessage()); command.Parameters.AddWithValue("@key", captureResponse.getEncryptKey()); int rowsAffected = command.ExecuteNonQuery(); } //xác nhận tình trạng thanh toán của đơn hàng connection.Close(); } builder.InitialCatalog = "QuanLyBanSach"; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); string sql; StringBuilder sb = new StringBuilder(); sb.Clear(); sb.Append("UPDATE DonHang SET DaThanhToan = @thanhtoan WHERE MaDonHang = @id"); sql = sb.ToString(); using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@thanhtoan", 1); command.Parameters.AddWithValue("@id", maDH); int rowsAffected = command.ExecuteNonQuery(); } connection.Close(); } } } } } } client.Close(); } } } socket.Close(); }
private async Task <(SignInResult SignInResult, ApplicationUser User)> PasswordSignInAsync(AuthorizationRequest context, string modelUsername, string modelPassword, bool modelRememberLogin, bool lockoutOnFailure) { var user = await _userManager.FindByNameAsync(modelUsername); if (user == null) { return(SignInResult.Failed, user); } if (context?.ClientId == FrontNames.FrontAdmin) { var isAdmin = await _userManager.IsInRoleAsync(user, Roles.Admin); if (!isAdmin) { return(SignInResult.Failed, user); } } return(await _signInManager.PasswordSignInAsync(user, modelPassword, modelRememberLogin, lockoutOnFailure: true), user); }
private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl, AuthorizationRequest context) { var loginProviders = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); var providers = loginProviders .Where(x => x.DisplayName != null) .Select(x => new ExternalProvider { DisplayName = x.DisplayName, AuthenticationScheme = x.Name }); var allowLocal = true; if (context?.ClientId != null) { var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId); if (client != null) { allowLocal = client.EnableLocalLogin; if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any()) { providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)); } } } return(new LoginViewModel { EnableLocalLogin = allowLocal, ReturnUrl = returnUrl, Email = context?.LoginHint, ExternalProviders = providers.ToArray() }); }
private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl, AuthorizationRequest context) { var allowLocal = true; if (context?.ClientId != null) { var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId); if (client != null) { allowLocal = client.EnableLocalLogin; } } return(new LoginViewModel { ReturnUrl = returnUrl, Email = context?.LoginHint, }); }
public async Task <IActionResult> Login(LoginInputModel model, string button) { // check if we are in the context of an authorization request AuthorizationRequest context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); // the user clicked the "cancel" button if (button != "login") { if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.GrantConsentAsync(context, ConsentResponse.Denied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl })); } return(Redirect(model.ReturnUrl)); } else { // since we don't have a valid context, then we just go back to the home page return(Redirect("~/")); } } if (ModelState.IsValid) { DiscoveryResponse disco = await DiscoveryClient.GetAsync("http://localhost:5000"); TokenClient tokenClient = new TokenClient(disco.TokenEndpoint, "MvcServer", "secret"); var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1"); var client = new HttpClient(); client.SetBearerToken(tokenResponse.AccessToken); try { var response = await client.GetAsync("http://localhost:5001/api/values/" + model.Username + "/" + model.Password); if (!response.IsSuccessStatusCode) { throw new Exception("Resource server is not working!"); } else { var content = await response.Content.ReadAsStringAsync(); User user = JsonConvert.DeserializeObject <User>(content); if (user != null) { await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.UserId, user.UserName)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; } ; // context.Result = new GrantValidationResult( //user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)), //OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime, //user.Claims); // issue authentication cookie with subject ID and username await HttpContext.SignInAsync(user.UserId, user.UserName, props); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl })); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(model.ReturnUrl)); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials")); ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage); } } catch (Exception ex) { await _events.RaiseAsync(new UserLoginFailureEvent("Resource server", "is not working!")); ModelState.AddModelError("", "Resource server is not working"); } } // something went wrong, show form with error var vm = await BuildLoginViewModelAsync(model); return(View(vm)); }
public AuthorizationResponse Authorization(AuthorizationRequest request) { AuthorizationDirective directive = request.directive; var response = new AuthorizationResponse(directive); #region Validate request if (directive.header.payloadVersion != "3") { [email protected] = new AlexaErrorResponsePayload(AlexaErrorTypes.INVALID_DIRECTIVE, "Invalid payload version."); return(response); } #endregion Validate request #region Verify Access if ((directive.payload.grantee == null) || (directive.payload.grantee.type != "BearerToken")) { [email protected] = new AlexaErrorResponsePayload(AlexaErrorTypes.INVALID_DIRECTIVE, "Invalid bearer token."); return(response); } try { if (!PremiseServer.CheckAccessTokenAsync(directive.payload.grantee.localAccessToken).GetAwaiter().GetResult()) { [email protected] = new AlexaErrorResponsePayload(AlexaErrorTypes.INVALID_AUTHORIZATION_CREDENTIAL, "Not authorized on local premise server."); return(response); } } catch (Exception ex) { [email protected] = new AlexaErrorResponsePayload(AlexaErrorTypes.INTERNAL_ERROR, ex.Message); return(response); } #endregion Verify Access try { if (PremiseServer.HomeObject == null) { [email protected] = new AlexaErrorResponsePayload(AlexaErrorTypes.ENDPOINT_UNREACHABLE, "Premise Server."); return(response); } using (PremiseServer.AsyncObjectsLock.Lock()) { PremiseServer.HomeObject.SetValueAsync("AlexaAsyncAuthorizationCode", directive.payload.grant.access_token).GetAwaiter().GetResult(); PremiseServer.HomeObject.SetValueAsync("AlexaAsyncAuthorizationRefreshToken", directive.payload.grant.refresh_token).GetAwaiter().GetResult(); PremiseServer.HomeObject.SetValueAsync("AlexaAsyncAuthorizationClientId", directive.payload.grant.client_id).GetAwaiter().GetResult(); PremiseServer.HomeObject.SetValueAsync("AlexaAsyncAuthorizationSecret", directive.payload.grant.client_secret).GetAwaiter().GetResult(); DateTime expiry = DateTime.UtcNow.AddSeconds(directive.payload.grant.expires_in); PremiseServer.HomeObject.SetValueAsync("AlexaAsyncAuthorizationCodeExpiry", expiry.ToString(CultureInfo.InvariantCulture)).GetAwaiter().GetResult(); } const string message = "Skill is now enabled and authorized to send async updates to Alexa. A task has been started to subscribe to property change events."; PremiseServer.InformLastContactAsync(message).GetAwaiter().GetResult(); PremiseServer.WriteToWindowsApplicationEventLog(EventLogEntryType.Information, message, 60); Task.Run(async() => { // Generate Discovery Json await PremiseServer.HomeObject.SetValueAsync("GenerateDiscoveryJson", "True").ConfigureAwait(false); // Signal sending async property change events - this will also subscribe to all properties await PremiseServer.HomeObject.SetValueAsync("SendAsyncEventsToAlexa", "True").ConfigureAwait(false); }); } catch (Exception ex) { [email protected] = new AlexaErrorResponsePayload(AlexaErrorTypes.INTERNAL_ERROR, ex.Message); return(response); } return(response); }
/// <summary> /// Envia uma requisição-autorizacao-tid para o webservice Cielo para que a transação /// seja autorizada segundo as configurações previamente feitas. /// </summary> /// <returns>A transação retornada pela Cielo e seu respectivo status</returns> /// <param name="transaction">A transação previamente configurada</param> public Transaction authorizationRequest(Transaction transaction) { AuthorizationRequest request = AuthorizationRequest.create(transaction); return(TransacaoElement.unserialize(transaction, sendHttpRequest(serialize(request)))); }
public async Task Authenticate_should_return_jwt_and_refresh_token_logging_ip() { // given string ipAddress = "9.8.7.6"; string refreshToken = "refresh token"; string jwtToken = "jwt token"; string email = "*****@*****.**"; string password = "******"; var roadkillUser = new RoadkillIdentityUser() { Id = "1", UserName = email, NormalizedUserName = email.ToUpperInvariant(), Email = email, NormalizedEmail = email.ToUpperInvariant(), RoleClaims = new List <string>() }; var model = new AuthorizationRequest() { Email = email, Password = password }; _userManagerMock.FindByEmailAsync(email) .Returns(Task.FromResult(roadkillUser)); _signinManagerMock.PasswordSignInAsync(roadkillUser, password, true, false) .Returns(Task.FromResult(SignInResult.Success)); var claims = new List <Claim>() { new Claim("any", "thing") } as IList <Claim>; _userManagerMock.GetClaimsAsync(roadkillUser) .Returns(Task.FromResult(claims)); _jwtTokenService .CreateToken(claims, roadkillUser.Email) .Returns(jwtToken); var httpContext = new DefaultHttpContext(); httpContext.Connection.RemoteIpAddress = IPAddress.Parse(ipAddress); _authorizationController.ControllerContext.HttpContext = httpContext; _jwtTokenService .CreateRefreshToken(roadkillUser.Email, ipAddress) .Returns(refreshToken); // when ActionResult <AuthorizationResponse> actionResult = await _authorizationController.Authenticate(model); // then actionResult.Result.ShouldBeOfType <OkObjectResult>(); var okResult = actionResult.Result as OkObjectResult; var response = okResult.Value as AuthorizationResponse; response.ShouldNotBeNull(); response.JwtToken.ShouldBe(jwtToken); response.RefreshToken.ShouldBe(refreshToken); }
private async Task RaiseLoginSuccessAsync(string username, AuthorizationRequest context) { ApplicationUser user = await _userManager.FindByNameAsync(username); await _eventService.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId : context?.ClientId)); }
/// <summary>Sets the UMA multipart form parameters from the AuthorizationRequest provided and posts the request.</summary> /// <param name="httpClient">The target of this extension method.</param> /// <param name="uri">The <see cref="Uri"/> endpoint to post to.</param> /// <param name="request">An <see cref="AuthorizationRequest"/> request.</param> /// <returns>An HttpResponseMessage.</returns> public static Task <HttpResponseMessage> PostUmaAsync(this HttpClient httpClient, Uri uri, AuthorizationRequest request) { string?ticket = request.Ticket; PermissionTicketToken?permissionTicketToken = request.Permissions; if (ticket == null && permissionTicketToken == null) { throw new ArgumentException("You must either provide a permission ticket or the permissions you want to request."); } Dictionary <string, string> paramDict = new Dictionary <string, string>(); paramDict.Add(OAuth2Constants.UmaGrantType, OAuth2Constants.GrantType); paramDict.Add("ticket", ticket !); paramDict.Add("claim_token", request.ClaimToken !); paramDict.Add("claim_token_format", request.ClaimTokenFormat !); paramDict.Add("pct", request.Pct !); paramDict.Add("rpt", request.RptToken !); paramDict.Add("scope", request.Scope !); paramDict.Add("audience", request.Audience !); paramDict.Add("subject_token", request.SubjectToken !); if (permissionTicketToken !.Permissions != null) { foreach (Permission permission in permissionTicketToken.Permissions) { string resourceId = permission.ResourceId; List <string>?scopes = permission.Scopes; StringBuilder value = new StringBuilder(); if (resourceId != null) { value.Append(resourceId); } if (scopes != null && (scopes.Count > 0)) { value.Append('#'); foreach (string scope in scopes) { string val = value.ToString(); if (!val.EndsWith('#')) { value.Append(','); } value.Append(scope); } } paramDict.Add(value.ToString(), "permission"); } } RequestMetadata?metadata = request.Metadata; if (metadata != null) { if (metadata.IncludeResourceName) { paramDict.Add(metadata.IncludeResourceName.ToString(CultureInfo.InvariantCulture), "response_include_resource_name"); } if (metadata.Limit > 0) { paramDict.Add(metadata.Limit.ToString(CultureInfo.InvariantCulture), "response_permissions_limit"); } } using (HttpContent ?content = new FormUrlEncodedContent(paramDict !)) { content.Headers.Add(@"Content-Type", @"application/x-www-form-urlencoded"); return(httpClient.PostAsync(uri, content)); } }
private ConsentViewModel CreateConsentViewModel(ConsentInputModel model, string returnUrl, AuthorizationRequest request) { var vm = new ConsentViewModel { RememberConsent = model?.RememberConsent ?? true, ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty <string>(), Description = model?.Description, ReturnUrl = returnUrl, ClientName = request.Client.ClientName ?? request.Client.ClientId, ClientUrl = request.Client.ClientUri, ClientLogoUrl = request.Client.LogoUri, AllowRememberConsent = request.Client.AllowRememberConsent }; vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => this.CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)) .ToArray(); var apiScopes = new List <ScopeViewModel>(); foreach (var parsedScope in request.ValidatedResources.ParsedScopes) { var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName); if (apiScope != null) { var scopeVm = this.CreateScopeViewModel(parsedScope, apiScope, vm.ScopesConsented.Contains(parsedScope.RawValue) || model == null); apiScopes.Add(scopeVm); } } if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess) { apiScopes.Add(this.GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)); } vm.ApiScopes = apiScopes; return(vm); }
protected internal virtual async Task <ConsentViewModel> CreateConsentViewModelAsync(AuthorizationRequest authorizationRequest, ConsentForm postedForm) { if (authorizationRequest == null) { throw new ArgumentNullException(nameof(authorizationRequest)); } var model = await this.CreateConsentViewModelAsync(authorizationRequest, postedForm, null); return(model); }
public AuthorizationResponse GetUser(AuthorizationRequest request) { return(new AuthorizationResponse(new SQLHelper().GetUser(request.Login, request.Password))); }
public override bool ProcessPayment(Payment payment, ref string message) { var info = payment as CreditCardPayment; if (ReferenceEquals(info, null)) { payment.Status = PaymentStatus.Failed.ToString(); message = "AuthorizeNet gateway supports only CreditCardPayment"; return(false); } string[] validateSettings = { "MerchantLogin", "MerchantPassword" }; foreach (var validateSetting in validateSettings) { if (!Settings.ContainsKey(validateSetting) || string.IsNullOrWhiteSpace(Settings[validateSetting])) { payment.Status = PaymentStatus.Failed.ToString(); message = string.Format("{0} not configured", validateSetting); return(false); } } var transactionType = (TransactionType)Enum.Parse(typeof(TransactionType), info.TransactionType); payment.Status = PaymentStatus.Processing.ToString(); var gateway = new Gateway(Settings["MerchantLogin"], Settings["MerchantPassword"]); bool isTestMode; if (Settings.ContainsKey("TestMode") && bool.TryParse(Settings["TestMode"], out isTestMode)) { gateway.TestMode = isTestMode; } var description = string.Format("{0} transaction for order id {1}", transactionType, info.OrderForm.OrderGroupId); IGatewayRequest request = null; switch (transactionType) { case TransactionType.Authorization: case TransactionType.Sale: request = new AuthorizationRequest(info.CreditCardNumber, string.Format("{0}{1}", info.CreditCardExpirationMonth, info.CreditCardExpirationYear), info.Amount, description, transactionType == TransactionType.Sale); break; case TransactionType.Capture: request = new PriorAuthCaptureRequest(info.Amount, info.ValidationCode); break; case TransactionType.Credit: request = new CreditRequest(info.ValidationCode, info.Amount, info.CreditCardNumber); break; case TransactionType.Void: request = new VoidRequest(info.ValidationCode); break; } if (request == null) { payment.Status = PaymentStatus.Failed.ToString(); message = string.Format("Unsupported transation type {0}", transactionType); return(false); } request.AddCardCode(info.CreditCardSecurityCode); var invoice = info.OrderForm.OrderGroupId; var order = info.OrderForm.OrderGroup as Order; if (order != null) { invoice = order.TrackingNumber; } request.AddInvoice(invoice); request.AddTax(info.OrderForm.TaxTotal); // Find the address var address = info.OrderForm.OrderGroup.OrderAddresses .FirstOrDefault(a => String.Compare(a.OrderAddressId, info.BillingAddressId, StringComparison.OrdinalIgnoreCase) == 0); if (address != null) { request.AddCustomer(address.Email, address.FirstName, address.LastName, address.Line1 + " " + address.Line2, address.StateProvince, address.PostalCode); } //foreach (var lineItem in info.OrderForm.LineItems) //{ // request.AddLineItem(lineItem.LineItemId, lineItem.DisplayName, lineItem.Description, // (int)lineItem.Quantity, lineItem.PlacedPrice, false); //} try { var response = gateway.Send(request, description); if (!response.Approved) { payment.Status = PaymentStatus.Denied.ToString(); message = "Transaction Declined: " + response.Message; return(false); } info.StatusCode = response.ResponseCode; info.StatusDesc = response.Message; info.ValidationCode = response.TransactionID; info.AuthorizationCode = response.AuthorizationCode; // transaction is marked as completed every time the payment operation succeeds even if it is void transaction type payment.Status = PaymentStatus.Completed.ToString(); } catch (Exception ex) { payment.Status = PaymentStatus.Failed.ToString(); throw new ApplicationException(ex.Message); } return(true); }
public async Task <IActionResult> Login(LoginViewModel model) { if (ModelState.IsValid) { // Check if we are in the context of an authorization request AuthorizationRequest context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, lockoutOnFailure : true); if (result.Succeeded) { // Set language cookie ApplicationUser user = await _userManager.FindByEmailAsync(model.Email); await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName, clientId : context?.Client.ClientId)); Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(user.Language)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential = true, Path = "/", HttpOnly = false, SameSite = SameSiteMode.Strict } ); if (model.ReturnUrl != null) { return(RedirectToLocal(model.ReturnUrl)); } return(RedirectToAction(nameof(HomeController.Overview), "Home")); } if (result.IsNotAllowed) { await _events.RaiseAsync(new UserLoginFailureEvent(model.Email, "Email confirmation required", clientId : context?.Client.ClientId)); return(RedirectToAction(nameof(AccountController.Login), new { model.ReturnUrl, alert = LoginAlert.EmailConfirmationRequired })); } if (result.IsLockedOut) { await _events.RaiseAsync(new UserLoginFailureEvent(model.Email, "Locked out", clientId : context?.Client.ClientId)); ApplicationUser user = await _userManager.FindByEmailAsync(model.Email); var lockoutEnd = (DateTimeOffset)await _userManager.GetLockoutEndDateAsync(user); var lockoutViewModel = new LockoutViewModel { LockoutEndMinutes = (int)(lockoutEnd.UtcDateTime - DateTime.UtcNow).TotalMinutes + 1 }; return(View("Lockout", lockoutViewModel)); } else { await _events.RaiseAsync(new UserLoginFailureEvent(model.Email, "Invalid credentials", clientId : context?.Client.ClientId)); ModelState.AddModelError(string.Empty, _localizer["InvalidLoginAttempt"]); return(View(nameof(AccountController.Login), model)); } } return(View(nameof(AccountController.Login), model)); }
public void GetRedirectUrl() { var mocker = new AutoMoqer(); var properties = new Dictionary <string, IList <string> > { { OAuthTokens.ResponseType, new[] { ResponseType.Code } }, { OAuthTokens.ClientId, new[] { "1" } }, { OAuthTokens.RedirectUri, new[] { "http://mydomain.com" } } }; mocker.GetMock <IRequest>().Setup(x => x.Values).Returns(properties); var request = new AuthorizationRequest(mocker.GetMock <IRequest>().Object, mocker.GetMock <IOAuthServiceLocator>().Object); try { properties[OAuthTokens.RedirectUri] = new[] { "http://wrong.com" }; request.GetRedirectUri(new ConsumerImpl { Domain = "test.com" }); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } try { properties[OAuthTokens.RedirectUri] = new[] { "wrong.com" }; request.GetRedirectUri(new ConsumerImpl { Domain = "test.com" }); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } try { properties[OAuthTokens.RedirectUri] = new[] { "/test.com/test" }; request.GetRedirectUri(new ConsumerImpl { Domain = "test.com" }); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } properties[OAuthTokens.RedirectUri] = new[] { "http://test.com/response" }; var result = request.GetRedirectUri(new ConsumerImpl { Domain = "test.com" }); Assert.AreEqual("http://test.com/response", result); result = request.GetRedirectUri(new ConsumerImpl { Domain = "test.com", RedirectUrl = "http://test.com/response" }); Assert.AreEqual("http://test.com/response", result); }
protected internal virtual async Task <ConsentViewModel> CreateConsentViewModelAsync(AuthorizationRequest authorizationRequest, ConsentForm postedForm, string returnUrl) { if (authorizationRequest == null) { throw new ArgumentNullException(nameof(authorizationRequest)); } var model = new ConsentViewModel { Client = authorizationRequest.Client, Form = await this.CreateConsentFormAsync(authorizationRequest, postedForm, returnUrl), PersistenceEnabled = authorizationRequest.Client.AllowRememberConsent }; return(await Task.FromResult(model)); }
public static AuthorizationCodeResult AuthorizationCode(this Controller controller, AuthorizationRequest request) { return(new AuthorizationCodeResult(request)); }
public async Task <ProcessConsentResult> ProcessConsent(ConsentInputModel model) { ProcessConsentResult result = new ProcessConsentResult(); ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (model.Button == "no") { grantedConsent = ConsentResponse.Denied; } // user clicked 'yes' - validate the data else if (model.Button == "yes" && model != null) { // if the user consented to some scope, build the response model if (model.ScopesConsented != null && model.ScopesConsented.Any()) { System.Collections.Generic.IEnumerable <string> scopes = model.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesConsented = scopes.ToArray() }; } else { result.ValidationError = ConsentOptions.MustChooseOneErrorMessage; } } else { result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage; } if (grantedConsent != null) { // validate return url is still valid AuthorizationRequest request = await this._interaction.GetAuthorizationContextAsync(model.ReturnUrl); if (request == null) { return(result); } // communicate outcome of consent back to identityserver await this._interaction.GrantConsentAsync(request, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint result.RedirectUri = model.ReturnUrl; } else { // we need to redisplay the consent UI result.ViewModel = await this.BuildViewModelAsync(model.ReturnUrl, model); } return(result); }
public AuthorizationResponse AutorizarAcessoRecurso(AuthorizationRequest request) { throw new NotImplementedException(); }
public async Task <AuthorizationResponse> AuthorizationAsync(AuthorizationRequest request) { using var activity = MyTelemetry.StartActivity("Authorization base on session token"); if (string.IsNullOrEmpty(request.Token) || string.IsNullOrEmpty(request.BrandId) || string.IsNullOrEmpty(request.BrokerId)) { return(new AuthorizationResponse() { Result = false }); } var(result, baseToken) = TokensManager.ParseBase64Token <JetWalletToken>(request.Token, AuthConst.GetSessionEncodingKey(), DateTime.UtcNow); if (result != TokenParseResult.Ok) { activity.SetStatus(Status.Error); return(new AuthorizationResponse() { Result = false }); } if (!string.IsNullOrEmpty(baseToken.SessionRootId)) { _logger.LogWarning("Cannot Authorization session base on token with existing RootSession: {rootIdText}", baseToken.SessionRootId); activity.SetStatus(Status.Error); return(new AuthorizationResponse() { Result = false }); } var token = new JetWalletToken() { Id = baseToken.Id, Expires = DateTime.UtcNow.AddMinutes(_settings.SessionLifeTimeMinutes), SessionRootId = Guid.NewGuid().ToString("N"), SessionId = Guid.NewGuid().ToString("N"), BrandId = request.BrandId, BrokerId = request.BrokerId }; token.Id.AddToActivityAsTag("clientId"); token.BrokerId.AddToActivityAsTag("brokerId"); token.BrandId.AddToActivityAsTag("brandId"); token.SessionRootId.AddToActivityAsTag("sessionRootId"); var clientIdentity = new JetClientIdentity(request.BrokerId, request.BrandId, baseToken.Id); var response = await _clientRegistrationService.GetOrRegisterClientAsync(clientIdentity); if (response.Result != ClientRegistrationResponse.RegistrationResult.Ok) { _logger.LogError("Cannot register client. Client already register with another brand. BrokerId/BrandId/ClientId: {brokerId}/{brandId}/{clientId}", clientIdentity.BrokerId, clientIdentity.BrandId, clientIdentity.ClientId); activity.SetStatus(Status.Error); return(new AuthorizationResponse() { Result = false }); } ClientWallet wallet = null; var wallets = await _clientWalletService.GetWalletsByClient(clientIdentity); if (string.IsNullOrEmpty(request.WalletId)) { wallet = wallets?.Wallets?.FirstOrDefault(w => w.IsDefault) ?? wallets?.Wallets?.FirstOrDefault(); } else { wallet = wallets?.Wallets?.FirstOrDefault(w => w.WalletId == request.WalletId); } if (wallet == null) { request.WalletId.AddToActivityAsTag("walletId"); _logger.LogWarning("Cannot Authorization session, wallet do not found. WalletId {walletId}. ClientId: {clientId}", request.WalletId, token.Id); activity.SetStatus(Status.Error); return(new AuthorizationResponse() { Result = false }); } token.WalletId = wallet.WalletId; token.WalletId.AddToActivityAsTag("walletId"); var session = token.IssueTokenAsBase64String(AuthConst.GetSessionEncodingKey()); var dueData = DateTime.UtcNow.AddHours(_settings.RootSessionLifeTimeHours); var publicKey = MyRsa.ReadPublicKeyFromPem(request.PublicKeyPem); var entity = SpotSessionNoSql.Create(request.BrokerId, request.BrandId, baseToken.Id, dueData, publicKey, token.SessionRootId); await _writer.InsertOrReplaceAsync(entity); await _sessionAuditService.NewSessionAudit(baseToken, token, request.UserAgent, request.Ip); _logger.LogInformation("Session Authorization is success. RootSessionId: {rootIdText}. ClientId:{clientId}", token.SessionRootId, token.ClientId()); return(new AuthorizationResponse() { Result = true, Token = session }); }
private void SendAuthorization(string name, string surname) { AuthorizationRequest request = new AuthorizationRequest(); request.Name = name; request.Surname = surname; Debug.Log("Sending authorization to server [{0} {1}].", name, surname); if (this.m_localClient.SendMessage(MessageType.AuthorizationRequest, request)) { Task.Delay(500).ContinueWith(_ => this.m_guiContacts.LocalContact.SetUsername(name, surname)); } }
public Transaction Process(AuthorizationRequest authorizationRequest) { throw new Exception("I always throw"); }
private static string GetAuthorizationRequestData(User user) { if (user != null && !string.IsNullOrEmpty(user.Username)) { // Create and return request data var request = new AuthorizationRequest { CmsUserName = user.Username, CmsRoles = String.Join(",", user.GetGroupNames()) }; return Util.SerializeDataContractJson(request); } else { return string.Empty; } }
private async Task <IActionResult> SuccessfullLogin(LoginInputModel model, UserViewModel userIdentity, AuthorizationRequest context) { await _events.RaiseAsync(new UserLoginSuccessEvent(userIdentity.UserName, userIdentity.UserName, userIdentity.Name, clientId : context == null ? userIdentity.UserName : context.ClientId)); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl })); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(model.ReturnUrl)); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { _logger.LogInformation($"Redirecting to ReturnUrl: {model.ReturnUrl}"); return(Redirect(model.ReturnUrl)); } if (!ValidateUrl(model.ReturnUrl)) { _logger.LogInformation($"Invalid return URL Redirecting to: {model.ReturnUrl}"); return(RedirectToAction("Index", "Grants")); } // user might have clicked on a malicious link - should be logged await _events.RaiseAsync(new MaliciousRedirectUrlEvent(model.ReturnUrl, model.Username)); throw new Exception("invalid return URL"); }
static void Main(string[] args) { IRepositoryFactory repositoryFactory = RepositoryFactory.Instance; ISymmetricAlgorithmProvider symmetricAlgorithmProvider = SymmetricAlgorithmProvider.Instance; using (var traceManager = new TraceManager("trace.txt")) { using (var dbContext = new KerberosStorageContext()) { using (var unitOfWork = new UnitOfWork(dbContext, repositoryFactory)) { var users = unitOfWork.Repository<User, int>() .Query() .Filter(p => p.Email.Equals("*****@*****.**", StringComparison.OrdinalIgnoreCase)) .Get(); var user = users.FirstOrDefault(); if (user != null) { IAuthenticationService authenticationService = new AuthenticationService( unitOfWork, symmetricAlgorithmProvider, traceManager); var authenticationRequest = new AuthenticationRequest { ServerId = "authentication server", TimeStamp = DateTime.Now, UserId = user.Email }; traceManager.Trace("Authentication Request Sent", authenticationRequest); IAuthenticationReply authenticationReply = authenticationService.Authenticate(authenticationRequest); traceManager.Trace("TGS encrypted received", Tuple.Create(authenticationReply.TgsBytes, authenticationReply.TgtBytes)); ITgsToken tgsToken = authenticationService.DecryptReply(user.Email, authenticationReply); traceManager.Trace("TGS decrypted: ", tgsToken); IAuthorizationService authorizationService = new AuthorizationService( unitOfWork, symmetricAlgorithmProvider, traceManager); byte[] authenticator = authorizationService.CreateAuthenticator(user.Email, tgsToken.SessionKey); traceManager.Trace("Auth authenticator encrypted", authenticator); var authorizationRequest = new AuthorizationRequest { AutheticatorBytes = authenticator, TgtBytes = authenticationReply.TgtBytes }; IAuthorizationReply authorizationReply = authorizationService.Authorize(authorizationRequest); traceManager.Trace("Authorization reply received", Tuple.Create(authorizationReply.ServiceTicket, authorizationReply.ServiceToken)); IServiceToken serviceToken = authorizationService.DecryptReply(user.Email, authorizationReply, tgsToken.SessionKey); traceManager.Trace("Service token decrypted", serviceToken); IDataService dataService = new DataService(unitOfWork, symmetricAlgorithmProvider, traceManager); authenticator = dataService.CreateAuthenticator(user.Email, serviceToken.SessionKey); var dataServiceRequest = new DataServiceRequest { Authenticator = authenticator, ServiceTicket = authorizationReply.ServiceTicket }; traceManager.Trace("Data service request sent", dataServiceRequest); IDataServiceReply dataServiceReply = dataService.GetAccess(dataServiceRequest); ITimeStampContainer timeStampContainer = dataService.DecryptReply(user.Email, dataServiceReply, serviceToken.SessionKey); if (Math.Abs((DateTime.UtcNow - new DateTime(timeStampContainer.TimeStamp, DateTimeKind.Utc)).Ticks) < new TimeSpan(1, 0, 0).Ticks) { traceManager.Trace("The operation has been completed successfully."); } } } } } }
public LoginController(AuthorizationRequest authorizationRequest) { this.authorizationRequest = authorizationRequest; }
public ActionResult Authorization([FromServices] IJwtSigningEncodingKey signingEncodingKey, [FromBody] AuthorizationRequest authorizationRequest) { #region Valid input data if (authorizationRequest == null) { return(BadRequest("Empty request")); } try { var validator = new AuthorizationRequestValidator(); var validationResult = validator.Validate(authorizationRequest); if (!validationResult.IsValid) { return(BadRequest("Invalid input data request")); } } catch (Exception e) { _logger.LogError($"Authorization failed. User data failed validation. Full validator exception message: {e.Message}"); return(StatusCode(StatusCodes.Status500InternalServerError, "Internal server error")); } #endregion #region Check authorization var blResult = _authorizationService.CheckAuthorization(authorizationRequest); if (blResult.ResultConnection != ServiceResult.ResultConnectionEnum.Correct) { _logger.LogError($"Authorization failed. Authorization service return error: {blResult.Message}"); return(Conflict(blResult.Message)); } #endregion var authorizationResult = _authorizationService.AuthorizationUser(authorizationRequest); if (authorizationResult.sessionToken == null || authorizationResult.userRole == null) { return(StatusCode(StatusCodes.Status500InternalServerError, "Failed to authenticate user, try again")); } var claims = new[] { new Claim(ClaimTypes.Role, authorizationResult.userRole.GetRoleName()), new Claim(AuthorizationDataModel.ClaimLogin, authorizationRequest.Login), new Claim(AuthorizationDataModel.ClaimSessionToken, authorizationResult.sessionToken) }; var token = new JwtSecurityToken( AuthorizationDataModel.ValidIssuer, AuthorizationDataModel.ValidAudience, claims, expires: authorizationResult.authorizationFinish, signingCredentials: new SigningCredentials( signingEncodingKey.GetKey(), signingEncodingKey.SigningAlgorithm) ); string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); var result = new AuthorizationResult(authorizationRequest.Login, authorizationResult.userRole, jwtToken, authorizationResult.authorizationFinish); _logger.LogInfo($"New user authorization (user: {authorizationRequest.Login})"); return(Ok(result)); }
protected internal virtual async Task <ConsentViewModel> CreateConsentViewModelAsync(AuthorizationRequest authorizationRequest, string userCode) { if (authorizationRequest == null) { throw new ArgumentNullException(nameof(authorizationRequest)); } var model = await this.CreateConsentViewModelAsync(authorizationRequest, null, null); model.Form.UserCode(userCode); return(model); }
public ValidationResult ValidateRequest(AuthorizationRequest request, NancyContext context) { return new ValidationResult(ErrorType.None); }
public CommitPreauthorizedPaymentResponse CommitPayment(string companyKey, Guid orderId, AccountDetail account, decimal preauthAmount, decimal amount, decimal meterAmount, decimal tipAmount, string transactionId, string reAuthOrderId = null, bool isForPrepaid = false, string kountSessionId = null, string customerIpAddress = null) { // No need to use preauthAmount for CMT because we can't preauthorize try { var orderDetail = _orderDao.FindById(orderId); if (orderDetail == null) { throw new Exception("Order not found"); } var creditCard = _creditCardDao.FindById(account.DefaultCreditCard.GetValueOrDefault()); var commitTransactionId = transactionId; if (_serverPaymentSettings.PaymentMode == PaymentMethod.RideLinqCmt) { InitializeServiceClient(); var pairingToken = orderDetail.IsManualRideLinq ? _orderDao.GetManualRideLinqById(orderId).PairingToken : _orderDao.FindOrderPairingById(orderId).PairingToken; var request = new CmtRideLinqAuthorizationRequest { PairingToken = pairingToken, CofToken = creditCard.Token, LastFour = creditCard.Last4Digits, SessionId = kountSessionId, Email = account.Email, CustomerIpAddress = customerIpAddress, BillingFullName = creditCard.NameOnCard }; if (creditCard.ZipCode.HasValue()) { request.ZipCode = creditCard.ZipCode; } var requestUrl = string.Format("payment/{0}/authorize/{1}", request.PairingToken, request.CofToken); _logger.LogMessage("Trying to authorize payment for CMT RideLinq (settling an overdue payment). Url: {0} Request {1}", requestUrl, request.ToJson()); try { var response = _cmtMobileServiceClient.Post(requestUrl, request); if (response != null && response.StatusCode == HttpStatusCode.OK) { _logger.LogMessage("Call to CMT RideLinq authorize succeeded"); return(new CommitPreauthorizedPaymentResponse { IsSuccessful = true, AuthorizationCode = "NoAuthCodeReturnedFromCmtRideLinqAuthorize", Message = "Success", TransactionId = commitTransactionId, TransactionDate = DateTime.UtcNow }); } } catch (WebServiceException ex) { _logger.LogMessage("Response: {0} {1} (Body: {2})", ex.StatusCode, ex.StatusDescription, ex.ResponseBody); var cmtErrorCode = ex.ResponseBody.FromJson <ErrorResponse>(); if (cmtErrorCode.ResponseCode == CmtErrorCodes.TripAlreadyAuthorized) { // this should be considered a success _logger.LogMessage("Received error code 615, consider it a success"); return(new CommitPreauthorizedPaymentResponse { IsSuccessful = true, AuthorizationCode = "NoAuthCodeReturnedFromCmtRideLinqAuthorize", Message = "Success", TransactionId = commitTransactionId, TransactionDate = DateTime.UtcNow }); } return(new CommitPreauthorizedPaymentResponse { IsSuccessful = false, TransactionId = commitTransactionId, Message = ex.ResponseBody }); } return(new CommitPreauthorizedPaymentResponse { IsSuccessful = false, TransactionId = commitTransactionId }); } else { string authorizationCode = null; var orderStatus = _orderDao.FindOrderStatusById(orderId); if (orderStatus == null) { throw new Exception("Order status not found"); } var deviceId = orderStatus.VehicleNumber; var driverId = orderStatus.DriverInfos == null ? 0 : orderStatus.DriverInfos.DriverId.To <int>(); var employeeId = orderStatus.DriverInfos == null ? string.Empty : orderStatus.DriverInfos.DriverId; var tripId = orderStatus.IBSOrderId.Value; var fleetToken = _serverPaymentSettings.CmtPaymentSettings.FleetToken; var customerReferenceNumber = orderStatus.ReferenceNumber.HasValue() ? orderStatus.ReferenceNumber : orderDetail.IBSOrderId.ToString(); var tempPaymentInfo = _orderDao.GetTemporaryPaymentInfo(orderId); var cvv = tempPaymentInfo != null ? tempPaymentInfo.Cvv : null; var authRequest = new AuthorizationRequest { FleetToken = fleetToken, DeviceId = deviceId, Amount = (int)(amount * 100), CardOnFileToken = creditCard.Token, CustomerReferenceNumber = customerReferenceNumber, DriverId = driverId, EmployeeId = employeeId, ShiftUuid = orderDetail.Id.ToString(), Fare = (int)(meterAmount * 100), Tip = (int)(tipAmount * 100), TripId = tripId, ConvenienceFee = 0, Extras = 0, Surcharge = 0, Tax = 0, Tolls = 0, Cvv2 = cvv }; // remove temp payment info _orderDao.DeleteTemporaryPaymentInfo(orderId); var authResponse = Authorize(authRequest); var isSuccessful = authResponse.ResponseCode == 1; var isCardDeclined = authResponse.ResponseCode == 607; if (isSuccessful) { commitTransactionId = authResponse.TransactionId.ToString(CultureInfo.InvariantCulture); authorizationCode = authResponse.AuthorizationCode; } return(new CommitPreauthorizedPaymentResponse { IsSuccessful = isSuccessful, AuthorizationCode = authorizationCode, Message = authResponse.ResponseMessage, TransactionId = commitTransactionId, IsDeclined = isCardDeclined, TransactionDate = isSuccessful ? (DateTime?)authResponse.AuthorizationDate : null }); } } catch (Exception ex) { return(new CommitPreauthorizedPaymentResponse { IsSuccessful = false, TransactionId = transactionId, Message = ex.Message }); } }