public AdapterPresentation(AuthView currentState, AdfsConfig adfsConfig, string param) { viewId = currentState; this.adfsConfig = adfsConfig; this.param = param; rspDto = null; }
/// <summary> /// Sends password and username and get a jwt token in the result package. /// </summary> /// <param name="userForAuthentication"></param> /// <returns></returns> public async Task <AuthResponseDto> Login(UserForAuthenticationDto userForAuthentication) { string content = userForAuthentication.ToString(); StringContent bodyContent = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage httpResponse = await _client.PostAsync("/token", bodyContent); string responseContent = await httpResponse.Content.ReadAsStringAsync(); AuthResponseDto result = JsonSerializer.Deserialize <AuthResponseDto>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); Console.WriteLine("Access granted is: " + httpResponse.IsSuccessStatusCode); result.Status = (int)httpResponse.StatusCode; if (!httpResponse.IsSuccessStatusCode) { result.Message = httpResponse.ReasonPhrase; return(result); } await _localStorage.SetItemAsync("authToken", result.Access_Token); ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(userForAuthentication.Username); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Access_Token); return(result); }
public AdapterPresentation(AuthView currentState, AdfsConfig adfsConfig) { viewId = currentState; this.adfsConfig = adfsConfig; param = null; rspDto = null; }
public async Task Logout() { User = null; await _localStorage.RemoveItemAsync(userKeyInLocal); _navi.NavigateTo("signin"); }
//public AdapterPresentation(AuthView currentState, AdfsConfig adfsConfig, ServiceStatus svcStatus, string svcDetail) //{ // viewId = currentState; // this.adfsConfig = adfsConfig; // rspStatus = svcStatus; // param = svcDetail; // rspDto = null; //} public AdapterPresentation(AuthView currentState, AdfsConfig adfsConfig, AuthResponseDto rspDto) { viewId = currentState; this.adfsConfig = adfsConfig; // rspStatus = rspDto.Status; this.rspDto = rspDto; param = (string)rspDto.Detail; }
private string BuildEncodedAuthResponse(string result) { var response = new AuthResponseDto() { Result = result, ExpirationUtc = DateTime.UtcNow + TimeSpan.FromSeconds(responseTimeoutInSeconds) }; var protector = _dataProtectionProvider.CreateProtector("response"); return(protector.Protect(JsonSerializer.Serialize(response))); }
private void doFile(string fileName) { WebClientImpl client = new WebClientImpl(new WebClientConfig()); string s = File.ReadAllText(fileName); AuthResponseDto rsp = new AuthResponseDto(ServiceStatusCode.SIGNATURE); rsp.Signature = Convert.FromBase64String(s); Assert.IsNotNull(rsp.Signature, "signature not null"); Assert.IsNotNull(rsp.UserCertificate, "signer cert not null"); Assert.AreEqual("MIDCHE28RCLRX077", rsp.UserSerialNumber, "signer serial number"); Assert.AreEqual("MIDCHE28RCLRX077:PN", rsp.UserPseudonym, "signer pseudonym"); }
public async Task <AuthResponseDto> Login(AuthResponseDto authResult) { await _localStorage.SetItemAsync("authToken", authResult.Token); await _localStorage.SetItemAsync("refreshToken", authResult.RefreshToken); ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(authResult.Token); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", authResult.Token); return(new AuthResponseDto { IsAuthSuccessful = true }); }
public async Task Guardar() { interceptor.RegisterEvent(); await http.AdicionarCSRF(); AuthResponseDto = await http.POST <AuthResponseDto>($"{Api.Usuario}/Token", Usuario); if (AuthResponseDto != null && AuthResponseDto.IsAuthSuccessful) { await AuthenticationService.Login(AuthResponseDto); navigation.NavigateTo("/Finalizar"); } }
// copied from WebClientImpl._parse500Response(RspStatusAndBody,bool) AuthResponseDto _parse500Response(string rspBody, bool asynchronous) { string sCode, sReason, sDetail; string sPortalUrl = null; XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; doc.Load(new StringReader(rspBody)); XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("soapenv", "http://www.w3.org/2003/05/soap-envelope"); manager.AddNamespace("mss", "http://uri.etsi.org/TS102204/v1.1.2#"); manager.AddNamespace("ki", "http://kiuru.methics.fi/mssp"); manager.AddNamespace("sc1", "http://www.swisscom.ch/TS102204/ext/v1.0.0"); string cursor = null; try { cursor = "Subcode"; sCode = doc.SelectSingleNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault/soapenv:Code/soapenv:Subcode/soapenv:Value", manager).InnerText; cursor = "Reason"; sReason = doc.SelectSingleNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault/soapenv:Reason/soapenv:Text", manager).InnerText; cursor = "Detail"; sDetail = doc.SelectSingleNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault/soapenv:Detail", manager).InnerText; //sDetail = doc.SelectSingleNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault/soapenv:Detail/ki:detail", manager).InnerText; try { cursor = "UserAssistance"; sPortalUrl = doc.SelectSingleNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault/soapenv:Detail/sc1:UserAssistance/sc1:PortalUrl", manager).InnerText; } catch (NullReferenceException) { } // sPortalUrl = null; } catch (NullReferenceException) { return(new AuthResponseDto(ServiceStatusCode.UnknownResponse, "Missing <" + cursor + "> in SOAP Fault")); } catch (Exception ex) { return(new AuthResponseDto(ServiceStatusCode.UnknownResponse, "Soap Fault parsing error (cursor=<" + cursor + ">): " + ex.Message)); } // SOAP Fault Subcode: check the allowed values ServiceStatusCode rc; Match match = new Regex(@"^mss:_(\d\d\d)$").Match(sCode); if (match.Success) { try { rc = (ServiceStatusCode)Enum.Parse(typeof(ServiceStatusCode), match.Groups[1].Value); } catch (OverflowException) { string s = "code='" + sCode + "', reason='" + sReason + "', detail='" + sDetail + "'"; return(new AuthResponseDto(ServiceStatusCode.UnsupportedStatusCode, s)); }; if (!asynchronous) { if (/* rc == ServiceStatusCode.EXPIRED_TRANSACTION || */ rc == ServiceStatusCode.OUSTANDING_TRANSACTION || rc == ServiceStatusCode.REQUEST_OK) { return(new AuthResponseDto(ServiceStatusCode.IllegalStatusCode, rc.ToString())); } ; } } else { string s = "code='" + sCode + "', reason='" + sReason + "', detail='" + sDetail + "', portalUrl='" + sPortalUrl + "'"; return(new AuthResponseDto(ServiceStatusCode.UnsupportedStatusCode, s)); }; AuthResponseDto rspDto = new AuthResponseDto(rc, sDetail); if (sPortalUrl != null) { rspDto.Extensions[AuthResponseExtension.UserAssistencePortalUrl] = sPortalUrl; } return(rspDto); }
// Authentication should perform the actual authentication and return at least one Claim on success. // proofData contains a dictionnary of strings to objects that have been asked in the BeginAuthentication public IAdapterPresentation TryEndAuthentication(IAuthenticationContext ctx, IProofData proofData, System.Net.HttpListenerRequest request, out Claim[] claims) { string formAction, upn, msspTransId, logInfo; int state; if (proofData.Properties.ContainsKey("Retry")) { formAction = "Retry"; } else { try { formAction = (string)proofData.Properties["Action"]; } catch (KeyNotFoundException) { formAction = null; } }; //if (formAction == null && proofData.Properties.ContainsKey("SignOut")) { // // if user modifies URL manually during a session, the Cancel action is not captured by ADFS but leaks to this method // formAction = "SignOut"; //}; logger.TraceEvent(TraceEventType.Verbose, 0, "TryEndAuthentication(act:" + formAction + ", ctx:" + _str(ctx) + ", prf:" + _str(proofData) + ", req:" + _str(request)); Logging.Log.TryEndAuthenticationStart(formAction, _str(ctx), _str(proofData), _str(request)); CultureInfo culture = new CultureInfo(ctx.Lcid); upn = (string)ctx.Data[USERUPN]; state = (int)ctx.Data[STATE]; try { // msspTransId is expected to be absent in some error cases, e.g. error 107 msspTransId = (string)ctx.Data[MSSPTRXID]; } catch (KeyNotFoundException) { msspTransId = null; }; logInfo = "upn:\"" + upn + "\", msspTransId:\"" + msspTransId + "\""; claims = null; if (formAction == "Continue") { switch (state) { case 3: logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_OK: " + logInfo + ", state:" + state); Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId); claims = ClaimsHwToken; return(null); case 1: case 31: // fall through for looping below break; default: logger.TraceEvent(TraceEventType.Error, 0, "BAD_STATE: " + logInfo + ", state:" + state); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, "BAD_STATE"); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, "action:\"Conitnue\"; state:" + state)); } // check session age, i.e. timespan(Now, authBegin) int ageSeconds = (int)((DateTime.UtcNow.Ticks / 10000 - (long)ctx.Data[AUTHBEGIN]) / 1000); if (ageSeconds >= cfgMid.RequestTimeOutSeconds) { ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_CONT: " + logInfo + ", state:" + ctx.Data[STATE] + ", age:" + ageSeconds); Logging.Log.AuthenticationTimeout(state, (int)ctx.Data[STATE], ageSeconds, upn, msspTransId); return (((int)ctx.Data[SESSTRIES] < cfgAdfs.SessionMaxTries) ? new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, "Timeout.") : // TODO: construct new ErrorCode for easier I18N new AdapterPresentation(AuthView.AuthError, cfgAdfs, "Timeout.")); } AuthRequestDto req = new AuthRequestDto(); req.PhoneNumber = (string)ctx.Data[MSISDN]; req.DataToBeSigned = (string)ctx.Data[DTBS]; bool needCheckUserSerialNumber = !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) || !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch) || cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch); if (needCheckUserSerialNumber /* cfgMid.UserSerialNumberPolicy != UserSerialNumberPolicy.ignore */ && ctx.Data.ContainsKey(UKEYSN)) { req.UserSerialNumber = (string)ctx.Data[UKEYSN]; } AuthResponseDto rsp; for (int i = ageSeconds; i <= cfgMid.RequestTimeOutSeconds; i += cfgMid.PollResponseIntervalSeconds) { rsp = getWebClient().PollSignature(req, msspTransId); switch (rsp.Status.Code) { case ServiceStatusCode.SIGNATURE: case ServiceStatusCode.VALID_SIGNATURE: ctx.Data[STATE] = 10; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_OK: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId); // EventLog.WriteEntry(EVENTLOGSource, "Authentication success for " + upn, EventLogEntryType.SuccessAudit, 100); claims = ClaimsHwToken; return(null); case ServiceStatusCode.OUSTANDING_TRANSACTION: ctx.Data[STATE] = 11; logger.TraceEvent(TraceEventType.Verbose, 0, "AUTHN_PENDING: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationPending(state, (int)ctx.Data[STATE], upn, msspTransId); System.Threading.Thread.Sleep(1000); break; case ServiceStatusCode.EXPIRED_TRANSACTION: ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_MID: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); case ServiceStatusCode.PB_SIGNATURE_PROCESS: ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SIGN_PROCESS: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); case ServiceStatusCode.USER_CANCEL: ctx.Data[STATE] = 14; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_CANCEL: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationCancel(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); default: ctx.Data[STATE] = 12; logger.TraceEvent(TraceEventType.Error, 0, "TECH_ERROR: " + logInfo + ", state:" + ctx.Data[STATE] + ", srvStatusCode:" + (int)rsp.Status.Code + ", srvStatusMsg:\"" + rsp.Status.Message + "\", srvStatusDetail:\"" + (string)rsp.Detail + "\""); if (rsp.Status.Color == ServiceStatusColor.Yellow || rsp.Status.Color == ServiceStatusColor.Green) { Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); } else { Logging.Log.AuthenticationTechnicalError(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code), (string)rsp.Detail); }; return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, rsp)); } } ; // for-loop ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_ADFS: " + logInfo + ", state:" + ctx.Data[STATE]); Logging.Log.AuthenticationTimeout(state, (int)ctx.Data[STATE], cfgMid.RequestTimeOutSeconds, upn, msspTransId); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, "Timeout.")); } else if (formAction == "Retry") { switch (state) { case 13: case 5: case 35: case 4: case 14: case 34: { // check session age and number of retries int ageSeconds = (int)((DateTime.UtcNow.Ticks / 10000 - (long)ctx.Data[SESSBEGIN]) / 1000); if (ageSeconds >= cfgAdfs.SessionTimeoutSeconds) { logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SESSION_TIMEOUT: " + logInfo + ", state:" + ctx.Data[STATE] + ", age:" + ageSeconds); Logging.Log.SessionTimeout(state, (int)ctx.Data[STATE], ageSeconds, upn, msspTransId); ctx.Data[STATE] = 22; } else if ((int)ctx.Data[SESSTRIES] >= cfgAdfs.SessionMaxTries) { logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SESSION_OVERTRIES: " + logInfo + ", state:" + ctx.Data[STATE]); Logging.Log.SessionTooMuchRetries(state, (int)ctx.Data[STATE], (int)ctx.Data[SESSTRIES], upn, msspTransId); ctx.Data[STATE] = 22; } ; if ((int)ctx.Data[STATE] == 22) { return(new AdapterPresentation(AuthView.AutoLogout, cfgAdfs)); } } // start a new asynchronous RequestSignature AuthRequestDto req = new AuthRequestDto(); req.PhoneNumber = (string)ctx.Data[MSISDN]; req.UserLanguage = (UserLanguage)Enum.Parse(typeof(UserLanguage), resMgr.GetString(RES_LANG, culture)); string uiTrxId = Util.BuildRandomBase64Chars(cfgAdfs.LoginNonceLength); req.DataToBeSigned = _buildMobileIdLoginPrompt(req.UserLanguage, culture, uiTrxId); req.TimeOut = cfgMid.RequestTimeOutSeconds; bool needCheckUserSerialNumber = !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) || !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch) || cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch); if (needCheckUserSerialNumber /* cfgMid.UserSerialNumberPolicy != UserSerialNumberPolicy.ignore */ && ctx.Data.ContainsKey(UKEYSN)) { req.UserSerialNumber = (string)ctx.Data[UKEYSN]; } ctx.Data[AUTHBEGIN] = DateTime.UtcNow.Ticks / 10000; AuthResponseDto rsp = getWebClient().RequestSignature(req, true /* async */); ctx.Data[SESSTRIES] = (int)ctx.Data[SESSTRIES] + 1; string logMsg = "svcStatus:" + (int)rsp.Status.Code + ", mssTransId:\"" + rsp.MsspTransId + "\", state:"; switch (rsp.Status.Code) { case ServiceStatusCode.VALID_SIGNATURE: case ServiceStatusCode.SIGNATURE: ctx.Data[STATE] = 33; ctx.Data[MSSPTRXID] = rsp.MsspTransId; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.TransferCtx, cfgAdfs)); case ServiceStatusCode.REQUEST_OK: ctx.Data[STATE] = 31; ctx.Data[MSSPTRXID] = rsp.MsspTransId; ctx.Data[DTBS] = req.DataToBeSigned; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationContinue(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.SignRequestSent, cfgAdfs, req.PhoneNumber, uiTrxId, cfgMid.PollResponseDelaySeconds * 1000)); case ServiceStatusCode.USER_CANCEL: ctx.Data[STATE] = 34; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationCancel(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); case ServiceStatusCode.EXPIRED_TRANSACTION: case ServiceStatusCode.PB_SIGNATURE_PROCESS: ctx.Data[STATE] = 35; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); default: ctx.Data[STATE] = 32; logger.TraceEvent((rsp.Status.Color == ServiceStatusColor.Yellow ? TraceEventType.Warning : TraceEventType.Error), 0, logMsg + ctx.Data[STATE] + ", errMsg:\"" + rsp.Status.Message + "\", errDetail:\"" + rsp.Detail + "\""); Logging.Log.AuthenticationTechnicalError(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code), rsp.Detail.ToString()); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, rsp)); } ; default: logger.TraceEvent(TraceEventType.Error, 0, "BAD_STATE: " + logInfo + ", state:" + state); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, "BAD_STATE"); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, "action:\"Retry\"; state:" + state)); } } //else if (formAction == "SignOut") //{ // logger.TraceEvent(TraceEventType.Verbose, 0, "SIGNOUT: " + logInfo + "; state:" + state); // return new AdapterPresentation(AuthView.AutoLogout, cfgAdfs); // could lead to endless-loop //} else { logger.TraceEvent(TraceEventType.Error, 0, "Unsupported formAction: " + formAction); Logging.Log.AuthenticationBadForm(state, (int)ctx.Data[STATE], upn, msspTransId, formAction); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, new AuthResponseDto(ServiceStatusCode.GeneralClientError))); } }
public async Task Initialize() { User = await _localStorage.GetItemAsync <AuthResponseDto>(userKeyInLocal); }