public void LogOut() { if (this.authenticationState != AuthenticationState.Authenticated) throw new Exception("Not logged in"); httpClient.GetString(this.FreeWay2SmsHost + "entry"); this.authenticationState = AuthenticationState.LogOut; }
public void LogOut() { if (this.authenticationState != AuthenticationState.Authenticated) throw new Exception("Not logged in"); httpClient.GetString(this.PrimaryHost + "Logout"); this.authenticationState = AuthenticationState.LogOut; }
private IEnumerable<IAuthenticationMethod> GetOrderedAuthenticationMethods(AuthenticationState authenticationState, IEnumerable<IAuthenticationMethod> matchingAuthenticationMethods) { var skippedAuthenticationMethods = new List<IAuthenticationMethod>(); foreach (var authenticationMethod in matchingAuthenticationMethods) { if (authenticationState.ExecutedAuthenticationMethods.Contains(authenticationMethod)) { skippedAuthenticationMethods.Add(authenticationMethod); continue; } yield return authenticationMethod; } foreach (var authenticationMethod in skippedAuthenticationMethods) yield return authenticationMethod; }
public async override Task <AuthenticationState> GetAuthenticationStateAsync() { if (await _storageService.ContainKeyAsync("User")) { var userInfo = await _storageService.GetItemAsync <ClientUserInfo>("User"); var claims = new[] { // new Claim(ClaimTypes.NameIdentifier, userInfo.ID), new Claim("AccessToken", userInfo.Token), new Claim("Expiration", userInfo.Expiration.ToString()) }; var identity = new ClaimsIdentity(claims, "BearerToken"); var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); } return(new AuthenticationState(new ClaimsPrincipal())); }
public async Task MarkUserAsLoggedOutTest() { LocalStorageServiceMock localStorageService = new LocalStorageServiceMock(); ApiConnectorMock mock = new ApiConnectorMock(); CustomAuthenticationStateProvider authenticationStateProvider = new CustomAuthenticationStateProvider(localStorageService, mock, navigationManagerMock); bool wasStateChanged = false; authenticationStateProvider.AuthenticationStateChanged += async(result) => { wasStateChanged = true; AuthenticationState state = await result; Assert.IsNull(state.User.Identity.Name); }; await authenticationStateProvider.MarkUserAsAuthenticated(user); await authenticationStateProvider.MarkUserAsLoggedOut(); Assert.IsTrue(wasStateChanged); Assert.IsNull(mock.CurrentUser); Assert.IsFalse(localStorageService.SetItems.ContainsKey("accessToken")); Assert.IsFalse(localStorageService.SetItems.ContainsKey("refreshToken")); }
protected override async Task <bool> ValidateAuthenticationStateAsync( AuthenticationState authenticationState, CancellationToken cancellationToken) { // Get the user manager from a new scope to ensure it fetches fresh data var scope = _scopeFactory.CreateScope(); try { var userManager = scope.ServiceProvider.GetRequiredService <UserManager <TUser> >(); return(await ValidateSecurityStampAsync(userManager, authenticationState.User)); } finally { if (scope is IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync(); } else { scope.Dispose(); } } }
/// <summary> /// Retrieve user info from local memory /// </summary> /// <returns></returns> public async override Task <AuthenticationState> GetAuthenticationStateAsync() { if (await _storageService.ContainKeyAsync("User")) { var userInfo = await _storageService.GetItemAsync <LocalUserInfo>("User"); var claims = new[] { new Claim("Email", userInfo.Email), new Claim("FirstName", userInfo.FirstName), new Claim("LastName", userInfo.LastName), new Claim("AccessToken", userInfo.AccessToken), new Claim(ClaimTypes.NameIdentifier, userInfo.Id) }; var identity = new ClaimsIdentity(claims, "BearerToken"); var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); } return(new AuthenticationState(new ClaimsPrincipal())); }
=> TimeSpan.FromSeconds(10); // TODO read from config protected override Task <bool> ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CancellationToken cancellationToken) { var sid = authenticationState.User.Claims .Where(c => c.Type.Equals("sid")) .Select(c => c.Value) .FirstOrDefault(); var name = authenticationState.User.Claims .Where(c => c.Type.Equals("name")) .Select(c => c.Value) .FirstOrDefault() ?? string.Empty; System.Diagnostics.Debug.WriteLine($"\nValidate: {name} / {sid}"); if (sid != null && Cache.HasSubjectId(sid)) { var data = Cache.Get(sid); System.Diagnostics.Debug.WriteLine($"NowUtc: {DateTimeOffset.UtcNow.ToString("o")}"); System.Diagnostics.Debug.WriteLine($"ExpUtc: {data.Expiration.ToString("o")}"); if (DateTimeOffset.UtcNow >= data.Expiration) { System.Diagnostics.Debug.WriteLine($"*** EXPIRED ***"); Cache.Remove(sid); return(Task.FromResult(false)); } } else { System.Diagnostics.Debug.WriteLine($"(not in cache)"); } return(Task.FromResult(true)); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var token = await _storageService.GetItemAsync <string>("token"); if (token != null) { var request = new HttpRequestMessage(HttpMethod.Get, "authorize"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var rr = await _client.SendAsync(request); if (!rr.IsSuccessStatusCode) { await _storageService.RemoveItemAsync("token"); return(new AuthenticationState(new ClaimsPrincipal())); } var identity = new ClaimsIdentity(new[] { new Claim("token", token), new Claim("username", await _storageService.GetItemAsync <string>("username")), }, "JWT"); var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); } return(new AuthenticationState(new ClaimsPrincipal())); }
protected override async Task OnAfterRenderAsync(bool firstRender) { if (_loaded) { return; } _loaded = true; _creating = NavigationManager.ToBaseRelativePath(NavigationManager.Uri).ToLowerInvariant(). StartsWith("admin/screens/create", StringComparison.InvariantCulture); if (Id <= 0 && !_creating) { return; } _resolutions = await ResolutionsService.GetAsync(); _model = _creating ? new ScreenViewModel() : await Service.GetAsync(Id); _screenResolutions = await ResolutionsByScreenService.GetByScreen(Id); _authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); _editing = _creating || NavigationManager.ToBaseRelativePath(NavigationManager.Uri).ToLowerInvariant(). StartsWith("admin/screens/edit/", StringComparison.InvariantCulture); if (_editing) { SetCheckboxes(); } StateHasChanged(); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { if (_tcsAuthState != null) { return(await _tcsAuthState.Task); } var token = await _sessionStorage.GetItemAsync <string>(AuthTokenName); if (string.IsNullOrEmpty(token)) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = await _httpClient.GetAsync("me"); if (response.IsSuccessStatusCode) { var userName = await response.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(userName)) { var authState = new AuthenticationState( new ClaimsPrincipal( new ClaimsIdentity( claims: new[] { new Claim(ClaimTypes.Name, userName) }, authenticationType: "UniverseAuthentication"))); _tcsAuthState = new TaskCompletionSource <AuthenticationState>(); _tcsAuthState.TrySetResult(authState); return(authState); } } return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); }
private void LoginBtn_Click(object sender, RoutedEventArgs e) { errorUserName.Visibility = Visibility.Collapsed; errorPassword.Visibility = Visibility.Collapsed; User = new UserModel { UserName = usernameText.Text, Password = passwordText.Password }; AuthenticationState authState = Login.Check(User); if (authState == AuthenticationState.UserNotFound) { errorUsernameText.Text = "User not found"; errorUserName.Visibility = Visibility.Visible; } else if (authState == AuthenticationState.WrongPassword) { errorPasswordText.Text = "You've entered a wrong password"; errorPassword.Visibility = Visibility.Visible; } else if (authState == AuthenticationState.Authenticated) { if (User.Role.Name == "Admin") { AdminPanelWindow win = new AdminPanelWindow(this); win.Show(); } else { TeacherPanelWindow win = new TeacherPanelWindow(this); win.Show(); } this.Hide(); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { // Get the auth token of the logged in user string authToken = await _localStorageService.GetItemAsStringAsync("authToken"); var identity = new ClaimsIdentity(); _httpClient.DefaultRequestHeaders.Authorization = null; // If an auth token is found, build an identity and update the Bearer token if (!string.IsNullOrEmpty(authToken)) { identity = new ClaimsIdentity(ParseClaimsFromJwt(authToken), "jwt"); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); } // Set the user with the identity, and the state with the user var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); // Notify the rest of the client that the authentication has changed and either someone is logged in or not NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { using var scope = _scopeFactory.CreateScope(); var userManager = scope.ServiceProvider.GetService <UserManager <TUser> >(); var state = base.GetAuthenticationStateAsync().Result; var user = await userManager !.GetUserAsync(state.User); AuthenticationState result = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); if (user != null) { var roles = await userManager !.GetRolesAsync(user); var principalFactory = new UserClaimsPrincipalFactory <TUser>(userManager, new OptionsWrapper <IdentityOptions>(_options)); var principal = await principalFactory.CreateAsync(user); var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(principal.Identity, roles.Select(role => new Claim(ClaimTypes.Role, role)))); result = new AuthenticationState(claimsPrincipal); } NotifyAuthenticationStateChanged(Task.FromResult(result)); return(result); }
public async Task <SignInResult> SignInAsync(TCredential credentials) { try { var claims = await _http.PostJsonWithPdAsync <Dictionary <string, string> >(_options.LoginUrl, credentials); authenticationState = BuildAuthenticationState(claims); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); LastSignInResult = SignInResult.Success; } catch (HttpRequestException e) { try { LastSignInResult = e.GetSignInResult(); } catch { throw e; } } return(LastSignInResult); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { try { var token = await LocalStorage.GetItemAsync <string>("token"); if (string.IsNullOrWhiteSpace(token)) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } var handler = new JwtSecurityTokenHandler(); var readToken = handler.ReadJwtToken(token.Substring(token.IndexOf(' ') + 1)); var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(readToken.Claims, "apiauth")); var state = new AuthenticationState(authenticatedUser); return(state); } catch (Exception exception) { logger.LogError(exception, "Authentification failed"); return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } }
// NEU in Teil 3 public override async Task <AuthenticationState> GetAuthenticationStateAsync() { if (this.CurrentLoginInfo != null && !String.IsNullOrEmpty(this.CurrentLoginInfo.Token) && !String.IsNullOrEmpty(proxy.BaseUrl)) { const string authType = "MiracleList WebAPI Authentication"; var identity = new ClaimsIdentity(new[] { new Claim("Backend", proxy.BaseUrl), new Claim(ClaimTypes.Sid, this.CurrentLoginInfo.Token), // use SID claim for token new Claim(ClaimTypes.Name, this.CurrentLoginInfo.Username), }, authType); var cp = new ClaimsPrincipal(identity); var state = new AuthenticationState(cp); Console.WriteLine($"{nameof(AuthenticationManager)}.{nameof(GetAuthenticationStateAsync)}: {this.CurrentLoginInfo.Username}"); return(state); } else { Console.WriteLine($"{nameof(AuthenticationManager)}.{nameof(GetAuthenticationStateAsync)}: No user!"); var state = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); return(state); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { // Ambil Cookie dari Local Storage var savedToken = await GetTokenAsync(); if (!string.IsNullOrEmpty(savedToken)) { _claims = ParseClaimsFromJwt(savedToken); var claimsIdentity = new ClaimsIdentity(_claims, Constants.AuthenticationType.ServerAuthentication); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authenticationState = new AuthenticationState(claimsPrincipal); return(await Task.FromResult(authenticationState)); } else { var claimsIdentity = new ClaimsIdentity(); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authenticationState = new AuthenticationState(claimsPrincipal); return(await Task.FromResult(authenticationState)); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { string authToken = await _localStorageService.GetItemAsStringAsync("authToken"); var identity = new ClaimsIdentity(); _http.DefaultRequestHeaders.Authorization = null; if (!string.IsNullOrEmpty(authToken)) { try { identity = new ClaimsIdentity(ParseClaimsFromJwt(authToken), "jwt"); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); } catch { await _localStorageService.RemoveItemAsync("authToken"); identity = new ClaimsIdentity(); } } var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); }
public override CircuitHost CreateCircuitHost( HttpContext httpContext, CircuitClientProxy client, string baseUri, string uri, ClaimsPrincipal user) { // We do as much intialization as possible eagerly in this method, which makes the error handling // story much simpler. If we throw from here, it's handled inside the initial hub method. var components = ResolveComponentMetadata(httpContext, client); var scope = _scopeFactory.CreateScope(); var encoder = scope.ServiceProvider.GetRequiredService <HtmlEncoder>(); var jsRuntime = (RemoteJSRuntime)scope.ServiceProvider.GetRequiredService <IJSRuntime>(); var componentContext = (RemoteComponentContext)scope.ServiceProvider.GetRequiredService <IComponentContext>(); jsRuntime.Initialize(client); componentContext.Initialize(client); var authenticationStateProvider = scope.ServiceProvider.GetService <AuthenticationStateProvider>() as IHostEnvironmentAuthenticationStateProvider; if (authenticationStateProvider != null) { var authenticationState = new AuthenticationState(httpContext.User); // TODO: Get this from the hub connection context instead authenticationStateProvider.SetAuthenticationState(Task.FromResult(authenticationState)); } var navigationManager = (RemoteNavigationManager)scope.ServiceProvider.GetRequiredService <NavigationManager>(); var navigationInterception = (RemoteNavigationInterception)scope.ServiceProvider.GetRequiredService <INavigationInterception>(); if (client.Connected) { navigationManager.AttachJsRuntime(jsRuntime); navigationManager.Initialize(baseUri, uri); navigationInterception.AttachJSRuntime(jsRuntime); } else { navigationManager.Initialize(baseUri, uri); } var rendererRegistry = new RendererRegistry(); var renderer = new RemoteRenderer( scope.ServiceProvider, _loggerFactory, rendererRegistry, jsRuntime, client, encoder, _loggerFactory.CreateLogger <RemoteRenderer>()); var circuitHandlers = scope.ServiceProvider.GetServices <CircuitHandler>() .OrderBy(h => h.Order) .ToArray(); var circuitHost = new CircuitHost( _circuitIdFactory.CreateCircuitId(), scope, client, rendererRegistry, renderer, components, jsRuntime, circuitHandlers, _loggerFactory.CreateLogger <CircuitHost>()); Log.CreatedCircuit(_logger, circuitHost); // Initialize per - circuit data that services need (circuitHost.Services.GetRequiredService <ICircuitAccessor>() as DefaultCircuitAccessor).Circuit = circuitHost.Circuit; circuitHost.SetCircuitUser(user); return(circuitHost); }
private void RenderNotAuthorizedInDefaultLayout(RenderTreeBuilder builder, AuthenticationState authenticationState) { var content = NotAuthorized ?? _defaultNotAuthorizedContent; RenderContentInDefaultLayout(builder, content(authenticationState)); }
protected override async Task OnInitializedAsync() { AuthenticationState = await AuthenticationStateTask; RecipeTagTypes = (await UserService.GetRecipeTagTypes()).ToList(); }
private bool TryAuthenticate(ISession session, AuthenticationState authenticationState, ICollection <string> allowedAuthenticationMethods, ref SshAuthenticationException authenticationException) { if (allowedAuthenticationMethods.Count == 0) { authenticationException = new SshAuthenticationException("No authentication methods defined on SSH server."); return(false); } // we want to try authentication methods in the order in which they were // passed in the ctor, not the order in which the SSH server returns // the allowed authentication methods var matchingAuthenticationMethods = authenticationState.SupportedAuthenticationMethods.Where(a => allowedAuthenticationMethods.Contains(a.Name)).ToList(); if (matchingAuthenticationMethods.Count == 0) { authenticationException = new SshAuthenticationException(string.Format("No suitable authentication method found to complete authentication ({0}).", string.Join(",", allowedAuthenticationMethods.ToArray()))); return(false); } foreach (var authenticationMethod in GetOrderedAuthenticationMethods(authenticationState, matchingAuthenticationMethods)) { if (authenticationState.FailedAuthenticationMethods.Contains(authenticationMethod)) { continue; } // when the authentication method was previously executed, then skip the authentication // method as long as there's another authentication method to try; this is done to avoid // a stack overflow for servers that do not update the list of allowed authentication // methods after a partial success if (!authenticationState.ExecutedAuthenticationMethods.Contains(authenticationMethod)) { // update state to reflect previosuly executed authentication methods authenticationState.ExecutedAuthenticationMethods.Add(authenticationMethod); } var authenticationResult = authenticationMethod.Authenticate(session); switch (authenticationResult) { case AuthenticationResult.PartialSuccess: if (TryAuthenticate(session, authenticationState, authenticationMethod.AllowedAuthentications, ref authenticationException)) { authenticationResult = AuthenticationResult.Success; } break; case AuthenticationResult.Failure: authenticationState.FailedAuthenticationMethods.Add(authenticationMethod); authenticationException = new SshAuthenticationException(string.Format("Permission denied ({0}).", authenticationMethod.Name)); break; case AuthenticationResult.Success: authenticationException = null; break; } if (authenticationResult == AuthenticationResult.Success) { return(true); } } return(false); }
private static IEnumerable <IAuthenticationMethod> GetOrderedAuthenticationMethods(AuthenticationState authenticationState, IEnumerable <IAuthenticationMethod> matchingAuthenticationMethods) { var skippedAuthenticationMethods = new List <IAuthenticationMethod>(); foreach (var authenticationMethod in matchingAuthenticationMethods) { if (authenticationState.ExecutedAuthenticationMethods.Contains(authenticationMethod)) { skippedAuthenticationMethods.Add(authenticationMethod); continue; } yield return(authenticationMethod); } foreach (var authenticationMethod in skippedAuthenticationMethods) { yield return(authenticationMethod); } }
private static bool TryAuthenticate(ISession session, AuthenticationState authenticationState, ICollection<string> allowedAuthenticationMethods, ref SshAuthenticationException authenticationException) { if (allowedAuthenticationMethods.Count == 0) { authenticationException = new SshAuthenticationException("No authentication methods defined on SSH server."); return false; } // we want to try authentication methods in the order in which they were // passed in the ctor, not the order in which the SSH server returns // the allowed authentication methods var matchingAuthenticationMethods = authenticationState.SupportedAuthenticationMethods.Where(a => allowedAuthenticationMethods.Contains(a.Name)).ToList(); if (matchingAuthenticationMethods.Count == 0) { authenticationException = new SshAuthenticationException(string.Format("No suitable authentication method found to complete authentication ({0}).", string.Join(",", allowedAuthenticationMethods.ToArray()))); return false; } foreach (var authenticationMethod in GetOrderedAuthenticationMethods(authenticationState, matchingAuthenticationMethods)) { if (authenticationState.FailedAuthenticationMethods.Contains(authenticationMethod)) continue; // when the authentication method was previously executed, then skip the authentication // method as long as there's another authentication method to try; this is done to avoid // a stack overflow for servers that do not update the list of allowed authentication // methods after a partial success if (!authenticationState.ExecutedAuthenticationMethods.Contains(authenticationMethod)) { // update state to reflect previosuly executed authentication methods authenticationState.ExecutedAuthenticationMethods.Add(authenticationMethod); } var authenticationResult = authenticationMethod.Authenticate(session); switch (authenticationResult) { case AuthenticationResult.PartialSuccess: if (TryAuthenticate(session, authenticationState, authenticationMethod.AllowedAuthentications, ref authenticationException)) { authenticationResult = AuthenticationResult.Success; } break; case AuthenticationResult.Failure: authenticationState.FailedAuthenticationMethods.Add(authenticationMethod); authenticationException = new SshAuthenticationException(string.Format("Permission denied ({0}).", authenticationMethod.Name)); break; case AuthenticationResult.Success: authenticationException = null; break; } if (authenticationResult == AuthenticationResult.Success) return true; } return false; }
public void SetAuthentication(string UserId, string Password) { if (!Validation.IsValidMobileNumber(UserId)) throw new Exception("UserId must be a mobile number"); this.authenticationState = AuthenticationState.NotAuthenticated; string ResponseString = String.Empty; // get cookie and content from login page ResponseString = httpClient.GetString(this.PrimaryHost + "Login"); // post authentication keys Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("rssData", ""); data.Add("username", UserId); data.Add("password", Password); data.Add("token", ""); data.Add("hidDetails", ""); data.Add("fbid", ""); data.Add("userMobile1", ""); data.Add("userPwd1", ""); ResponseString = httpClient.GetStringPost(this.PrimaryHost + "re-login", data); // Identify status by redirect location if (!httpClient.IsRedirect) throw new Exception("Unknow Error on attempt login"); /* -- Number not registered http://www.160by2.com/LoginReg -- invalid password (forget password) http://www.160by2.com/LoginForgot -- Success * Email Verification page (we can skip this) http://www.160by2.com/PostLoginEmailVerification.action?id=74EDB163CA495F47EB0A44718F4D1EB4.8514 */ if (httpClient.RedirectLocation.IndexOf("LoginReg") != -1) throw new Exception("Authentication failed!\n\nNo such user found"); if (httpClient.RedirectLocation.IndexOf("LoginForgot") != -1) throw new Exception("Authentication failed!\n\nInvalid password"); //if (httpClient.RedirectLocation.IndexOf("ebrdg.action") == -1) // throw new Exception("Authentication failed!\n\nUnknow issue on authentication"); Regex regex = new Regex(@"id=([a-zA-Z0-9\.]+)"); Match m = regex.Match(httpClient.RedirectLocation); this.Token = m.Groups[1].Value; this.authenticationState = AuthenticationState.Authenticated; }
public static T GetClaim <T>(AuthenticationState state, string key) { if (state == null) { return(default);
public AuthStateProvider(HttpClient httpClient, ILocalStorageService localStorage) { _httpClient = httpClient; _localStorage = localStorage; _anonymous = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); }
protected override async Task OnInitializedAsync() { AuState = await authenticationStateProvider.GetAuthenticationStateAsync(); Log.LogInformation($"MainNav.AuthenticationStateProvider.User (OnInitializedAsync) ={AuState.User.Identity.Name}"); }
/// <summary> /// Set Authentication to use service /// </summary> /// <param name="UserId">Mobile Number</param> /// <param name="Password">Password</param> public void SetAuthentication(string UserId, string Password) { if (!Validation.IsValidMobileNumber(UserId)) throw new Exception("UserId must be a mobile number"); this.authenticationState = AuthenticationState.NotAuthenticated; string ResponseString = String.Empty; this.FreeWay2SmsHost = this.PrimaryHost; // get free server ResponseString = httpClient.GetString(this.PrimaryHost); if (httpClient.IsRedirect) { FreeWay2SmsHost = httpClient.RedirectLocation; if (!FreeWay2SmsHost.EndsWith("/")) FreeWay2SmsHost += "/"; } // get cookie and content from login page ResponseString = httpClient.GetString(FreeWay2SmsHost + "content/index.html"); // post authentication keys Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("username", UserId); data.Add("password", Password); ResponseString = httpClient.GetStringPost(FreeWay2SmsHost + "content/Login1.action", data); // Identify status by redirect location if (!httpClient.IsRedirect) throw new Exception("Unknow Error on attempt login"); /* -- input wrong (No User Id passed or username is not mobile number) http://site21.way2sms.com/entry.action?id=n3ps&ec=0001&username= -- invalid password http://site21.way2sms.com/wpwd.action?id=56tb&username=9530111056&ec=0004 -- no user found http://site21.way2sms.com/nruser.action?id=s2tq&username=9530111057 -- Success http://site21.way2sms.com/ebrdg.action;jsessionid=FC0243B583CA6B5F8A2B5ACF10925E88.w806?id=FC0243B583CA6B5F8A2B5ACF10925E88.w806 http://site21.way2sms.com/ebrdg.action;jsessionid=C6D681BF5FB3D760630B11FE264162AA.w805?id=C6D681BF5FB3D760630B11FE264162AA.w805 */ if (httpClient.RedirectLocation.IndexOf("entry.action") != -1) throw new Exception("Authentication failed!\n\nMake sure mobile number and password was typed correctly"); if (httpClient.RedirectLocation.IndexOf("nruser.action") != -1) throw new Exception("Authentication failed!\n\nNo such user found"); if (httpClient.RedirectLocation.IndexOf("wpwd.action") != -1) throw new Exception("Authentication failed!\n\nInvalid password"); if (httpClient.RedirectLocation.IndexOf("ebrdg.action") == -1) throw new Exception("Authentication failed!\n\nUnknow issue on authentication"); Regex regex = new Regex(@"jsessionid=([a-zA-Z0-9\.]+)"); Match m = regex.Match(httpClient.RedirectLocation); this.Token = m.Groups[1].Value; this.authenticationState = AuthenticationState.Authenticated; }
public static string Select(AuthenticationState authState, string type) { var claims = authState.User.Claims.ToList(); return(claims?.FirstOrDefault(x => x.Type.Equals(type, StringComparison.OrdinalIgnoreCase))?.Value); }
/// <summary> /// Typically used from a Web App or WebAPI controller, this method retrieves an access token /// for a downstream API using; /// 1) the token cache (for Web Apps and Web APis) if a token exists in the cache /// 2) or the <a href='https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow'>on-behalf-of flow</a> /// in Web APIs, for the user account that is ascertained from claims are provided in the <see cref="HttpContext.User"/> /// instance of the current HttpContext. /// </summary> /// <param name="scopes">Scopes to request for the downstream API to call.</param> /// <param name="tenant">Enables overriding of the tenant/account for the same identity. This is useful in the /// cases where a given account is guest in other tenants, and you want to acquire tokens for a specific tenant, like where the user is a guest in.</param> /// <param name="userFlow">Azure AD B2C user flow to target.</param> /// <param name="user">Optional claims principal representing the user. If not provided, will use the signed-in /// user (in a web app), or the user for which the token was received (in a Web API) /// cases where a given account is guest in other tenants, and you want to acquire tokens for a specific tenant, like where the user is a guest in.</param> /// <returns>An access token to call the downstream API and populated with this downstream API's scopes.</returns> /// <remarks>Calling this method from a web API supposes that you have previously called, /// in a method called by JwtBearerOptions.Events.OnTokenValidated, the HttpContextExtensions.StoreTokenUsedToCallWebAPI method /// passing the validated token (as a JwtSecurityToken). Calling it from a Web App supposes that /// you have previously called AddAccountToCacheFromAuthorizationCodeAsync from a method called by /// OpenIdConnectOptions.Events.OnAuthorizationCodeReceived.</remarks> public async Task <string> GetAccessTokenForUserAsync( IEnumerable <string> scopes, string?tenant = null, string?userFlow = null, ClaimsPrincipal?user = null) { if (user == null && _httpContextAccessor.HttpContext != null) { user = _httpContextAccessor.HttpContext.User; } if (user == null) { try { AuthenticationStateProvider?authenticationStateProvider = _serviceProvider.GetService(typeof(AuthenticationStateProvider)) as AuthenticationStateProvider; if (authenticationStateProvider != null) { // AuthenticationState provider is only available in Blazor AuthenticationState state = await authenticationStateProvider.GetAuthenticationStateAsync().ConfigureAwait(false); user = state.User; } } catch { } } if (scopes == null) { throw new ArgumentNullException(nameof(scopes)); } // Use MSAL to get the right token to call the API _application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false); string accessToken; try { accessToken = await GetAccessTokenOnBehalfOfUserFromCacheAsync( _application, user, scopes, tenant, userFlow) .ConfigureAwait(false); } catch (MsalUiRequiredException ex) { // GetAccessTokenForUserAsync is an abstraction that can be called from a Web App or a Web API _logger.LogInformation(ex.Message); // to get a token for a Web API on behalf of the user, but not necessarily with the on behalf of OAuth2.0 // flow as this one only applies to Web APIs. JwtSecurityToken?validatedToken = CurrentHttpContext.GetTokenUsedToCallWebAPI(); // Case of Web APIs: we need to do an on-behalf-of flow if (validatedToken != null) { // In the case the token is a JWE (encrypted token), we use the decrypted token. string tokenUsedToCallTheWebApi = validatedToken.InnerToken == null ? validatedToken.RawData : validatedToken.InnerToken.RawData; var result = await _application .AcquireTokenOnBehalfOf(scopes.Except(_scopesRequestedByMsal), new UserAssertion(tokenUsedToCallTheWebApi)) .WithSendX5C(_microsoftIdentityOptions.SendX5C) .ExecuteAsync() .ConfigureAwait(false); accessToken = result.AccessToken; } // Case of the Web App: we let the MsalUiRequiredException be caught by the // AuthorizeForScopesAttribute exception filter so that the user can consent, do 2FA, etc ... else { throw new MicrosoftIdentityWebChallengeUserException(ex, scopes.ToArray()); } } return(accessToken); }
public ValidateEmailMfaCodeAgainstCurrentUserCommandResult( Guid userId, AuthenticationState authenticationStatus) : base(userId, authenticationStatus) { }
/// <summary> /// Begins an asynchronous API authentication request. /// </summary> /// <param name="callback">The asynchronous callback for the web request</param> /// <returns>An XDocument containing the result of the request.</returns> public IAsyncResult BeginAuthenticate(AsyncCallback callback) { Request = (HttpWebRequest)System.Net.WebRequest.Create( Properties.Resources.AuthenticationUrl); Request.Method = "POST"; Request.ContentType = "application/xml"; PropertyInfo headerInfo = Request.GetType().GetProperty("UserAgent"); if (headerInfo != null) { headerInfo.SetValue(Request, "MyAquinasMobileAPI", null); } else { Request.Headers[HttpRequestHeader.UserAgent] = "MyAquinasMobileAPI"; } Request.Accept = "application/xml"; //Had to add this to stop the server returning JSON AuthenticationState state = new AuthenticationState(callback, Request); return Request.BeginGetRequestStream(AuthenticateWriteAndSend, state); }
void Client_Disconnected(object sender, EventArgs e) { Stop(); State = AuthenticationState.Fail; }
public ValidateDeviceMfaAgainstCurrentUserCommandResult( Guid userId, AuthenticationState authenticationStatus) : base(userId, authenticationStatus) { }
async Task <HttpResponse> HandleNtlmRequest( TestContext ctx, HttpOperation operation, HttpConnection connection, HttpRequest request, RequestFlags effectiveFlags, CancellationToken cancellationToken) { var me = $"{ME}.{nameof (HandleNtlmRequest)}"; ctx.LogDebug(3, $"{me}: {connection.RemoteEndPoint}"); AuthenticationState state; var response = AuthManager.HandleAuthentication(ctx, connection, request, out state); ctx.LogDebug(3, $"{me}: {connection.RemoteEndPoint} - {state} {response}"); if (state == AuthenticationState.Unauthenticated) { ctx.Assert(currentAuthState, Is.EqualTo(AuthenticationState.None), "first request"); currentAuthState = AuthenticationState.Unauthenticated; } else if (TestRunner.EffectiveType == HttpInstrumentationTestType.NtlmInstrumentation) { if (state == AuthenticationState.Challenge) { ctx.LogDebug(3, $"{me}: {connection.RemoteEndPoint} {RemoteEndPoint}"); challengeEndPoint = connection.RemoteEndPoint; } else { ctx.Assert(connection.RemoteEndPoint, Is.EqualTo(challengeEndPoint), "must reuse connection"); } } if (TestRunner.EffectiveType == HttpInstrumentationTestType.ParallelNtlm) { var parallelOperation = TestRunner.StartParallelNtlm( ctx, this, state, cancellationToken); if (parallelOperation != null) { await parallelOperation.WaitForCompletion().ConfigureAwait(false); } } var keepAlive = !CloseConnection && (effectiveFlags & (RequestFlags.KeepAlive | RequestFlags.CloseConnection)) == RequestFlags.KeepAlive; if (response != null) { response.Redirect = operation.RegisterRedirect(ctx, this, request.Path); return(response); } cancellationToken.ThrowIfCancellationRequested(); HttpInstrumentationContent content; switch (TestRunner.EffectiveType) { case HttpInstrumentationTestType.NtlmWhileQueued: content = new HttpInstrumentationContent(TestRunner, currentRequest); return(new HttpResponse(HttpStatusCode.OK, content)); case HttpInstrumentationTestType.NtlmWhileQueued2: content = new HttpInstrumentationContent(TestRunner, currentRequest); return(new HttpResponse(HttpStatusCode.OK, content) { CloseConnection = true }); } var ret = await Target.HandleRequest(ctx, operation, connection, request, effectiveFlags, cancellationToken); ctx.LogDebug(3, $"{me} target done: {Target} {ret}"); ret.KeepAlive = false; return(ret); }