/// <summary> /// 设置授权认证数 /// </summary> /// <param name="value">实体序列化JsonConvert.SerializeObject(data)</param> /// <param name="valueType"></param> public async void SetsAuthenticationAsync(string value, AuthorizationStorageType valueType) { var claims = new List <Claim>() { new Claim(valueType.ToString(), value) }; Task <AuthenticateResult> authenticateInfo = AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, authenticationScheme); if (!authenticateInfo.IsFaulted && authenticateInfo.Result.Principal != null) { claims = authenticateInfo.Result.Principal.Claims.ToList(); int idx = claims.FindIndex(c => { return(c.Type.Equals(valueType.ToString())); }); if (idx >= 0) { claims.RemoveAt(idx); } claims.Add(new Claim(valueType.ToString(), value)); } ClaimsIdentity identity = new ClaimsIdentity(claims); var userPrincipal = new ClaimsPrincipal(identity); await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, authenticationScheme, userPrincipal, new Microsoft.AspNetCore.Authentication.AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(24), IsPersistent = false, AllowRefresh = true }); }
/// <summary> /// 获取授权数据 /// </summary> /// <param name="valueType"></param> /// <returns></returns> public string GetAuthClainValue(AuthorizationStorageType valueType) { string value = string.Empty; try { Task <AuthenticateResult> authenticateInfo = AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, authenticationScheme); if (authenticateInfo.IsFaulted || authenticateInfo.Result.Principal == null) { return(value); } IEnumerable <Claim> claims = authenticateInfo.Result.Principal.Claims; foreach (Claim claim in claims) { if (claim.Type.Equals(valueType.ToString())) { value = claim.Value; break; } } } catch (Exception) { } return(value); }
public async Task <IActionResult> LoginCallback(string returnUrl) { IActionResult result; AuthenticateResult asyncVariable0 = await AuthenticationHttpContextExtensions.AuthenticateAsync(this.HttpContext, "QQConnect"); AuthenticateResult authenticateResult = asyncVariable0; asyncVariable0 = null; if (!authenticateResult.Succeeded || !authenticateResult.Principal.Claims.Any <Claim>()) { result = this.RedirectToRoute("Login"); } else { ExternalAuthenticationParameters asyncVariable3 = new ExternalAuthenticationParameters { ProviderSystemName = "ExternalAuth.QQConnect" }; ExternalAuthenticationParameters asyncVariable1 = asyncVariable3; string asyncVariable2 = await AuthenticationHttpContextExtensions.GetTokenAsync(this.HttpContext, "QQConnect", "access_token"); asyncVariable1.AccessToken = asyncVariable2; asyncVariable3.Email = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Email)?.Value; asyncVariable3.ExternalIdentifier = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value; asyncVariable3.ExternalDisplayIdentifier = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Name)?.Value; asyncVariable3.Claims = authenticateResult.Principal.Claims.Select(claim => new ExternalAuthenticationClaim(claim.Type, claim.Value)).ToList(); ExternalAuthenticationParameters parameters = asyncVariable3; asyncVariable1 = null; asyncVariable2 = null; asyncVariable3 = null; result = this._externalAuthenticationService.Authenticate(parameters, returnUrl); } return(result); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var result = AuthenticationHttpContextExtensions.AuthenticateAsync(System.Web.HttpContextHelper.Current, "Cookies"); if (result.Result.Succeeded) { request.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.Result.Properties.GetTokenValue("api_token")); } return(await base.SendAsync(request, cancellationToken).ConfigureAwait(false)); }
public IActionResult LoggedInUser() { var ticket = AuthenticationHttpContextExtensions.AuthenticateAsync(_context.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme).GetAwaiter().GetResult(); //var identity = ticket != null && ticket.Principal != null ? ticket.Ticket.Principal : null; //ClaimsPrincipal principal = _context.HttpContext.User; A2ZClientCredentials cred = new A2ZClientCredentials(); //cred.UserName = principal.Claims.Where(x => x.Type == "Name" ).FirstOrDefault().Value; cred.UserName = ticket.Principal.Identity.Name; return(View(cred)); }
public async Task <IActionResult> Index() { var localAddresses = new string[] { "127.0.0.1", "::1", HttpContext.Connection.LocalIpAddress.ToString() }; if (!localAddresses.Contains(HttpContext.Connection.RemoteIpAddress.ToString())) { return(NotFound()); } var model = new DiagnosticsViewModel(await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext)); return(View(model)); }
private async Task RefreshTokensAync() { var authorizatinServerInformation = await DiscoveryClient.GetAsync("http://localhost:26421"); var client = new TokenClient(authorizatinServerInformation.TokenEndpoint, "socialnetwork_code", "secret"); var refreshToken = await AuthenticationHttpContextExtensions.GetTokenAsync(this.HttpContext, "refresh_token"); var tokenResponse = await client.RequestRefreshTokenAsync(refreshToken); var identityToken = await AuthenticationHttpContextExtensions.GetTokenAsync(this.HttpContext, "id_token"); var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn); var tokens = new[] { new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = tokenResponse.IdentityToken }, new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = tokenResponse.AccessToken }, new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = tokenResponse.RefreshToken }, new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) } }; //var authenticationInformation =HttpContext.Authentication.GetAuthenticateInfoAsync(CookieAuthenticationDefaults.AuthenticationScheme); var authenticationInformation = await AuthenticationHttpContextExtensions.AuthenticateAsync(this.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme); authenticationInformation.Properties.StoreTokens(tokens); await AuthenticationHttpContextExtensions.SignInAsync(this.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, authenticationInformation.Principal, authenticationInformation.Properties); }
/// <summary>ユーザ情報を取得する</summary> private async Task GetUserInfo() { // セッションステートレス対応 if (MyHttpContext.Current.Session == null) { // SessionがOFFの場合 } else { // 取得を試みる。 this.UserInfo = UserInfoHandle.GetUserInformation <MyUserInfo>(); // nullチェック if (this.UserInfo == null) { AuthenticateResult authenticateInfo = await AuthenticationHttpContextExtensions.AuthenticateAsync( MyHttpContext.Current, CookieAuthenticationDefaults.AuthenticationScheme); //await MyHttpContext.Current.Authentication.GetAuthenticateInfoAsync( // CookieAuthenticationDefaults.AuthenticationScheme); // 古い //System.Threading.Thread.CurrentPrincipal.Identity.Name; // .NET Framework string userName = authenticateInfo.Principal?.Identity?.Name; // null 条件演算子 if (string.IsNullOrEmpty(userName)) { // 未認証状態 this.UserInfo = new MyUserInfo("未認証", (new GetClientIpAddress()).GetAddress()); } else { // 認証状態 this.UserInfo = new MyUserInfo(userName, (new GetClientIpAddress()).GetAddress()); // 必要に応じて認証チケットのユーザ名からユーザ情報を復元する。 // ★ 必要であれば、他の業務共通引継ぎ情報などをロードする。 // ・・・ // 復元したユーザ情報をセット UserInfoHandle.SetUserInformation(this.UserInfo); } } } }
public static IApplicationBuilder UseJwtTokenMiddleware( this IApplicationBuilder app, string schema = "Bearer") { return(UseExtensions.Use(app, (Func <HttpContext, Func <Task>, Task>)(async(ctx, next) => { IIdentity identity = ctx.User.Identity; if ((identity != null ? (!identity.IsAuthenticated ? 1 : 0) : 1) != 0) { AuthenticateResult authenticateResult = await AuthenticationHttpContextExtensions.AuthenticateAsync(ctx, schema); if (authenticateResult.Succeeded && authenticateResult.Principal != null) { ctx.User = authenticateResult.Principal; } } await next(); }))); }
public async Task <UserDto> RenewTokensAsync() { // get the metadata var discoveryClient = await DiscoveryClient.GetAsync(Parties.AuthorityUrl); // create a new token client to get new tokens var tokenClient = new TokenClient(discoveryClient.TokenEndpoint, "SPA_APP", "password"); // get the saved refresh token var currentRefreshToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken); // refresh the tokens var tokenResult = await tokenClient.RequestRefreshTokenAsync(currentRefreshToken); if (!tokenResult.IsError) { // get auth info var authenticateInfo = await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext); // create a new value for expires_at, and save it var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn); authenticateInfo.Properties.UpdateTokenValue("expires_at", expiresAt.ToString("o", CultureInfo.InvariantCulture)); authenticateInfo.Properties.UpdateTokenValue(OpenIdConnectParameterNames.AccessToken, tokenResult.AccessToken); authenticateInfo.Properties.UpdateTokenValue(OpenIdConnectParameterNames.RefreshToken, tokenResult.RefreshToken); // we're signing in again with the new values. await HttpContext.SignInAsync("Cookies", authenticateInfo.Principal, authenticateInfo.Properties); // return the new access token return(new UserDto { Token = tokenResult.AccessToken, TokenRenewalTime = expiresAt.ToUniversalTime().Ticks }); } else { throw new Exception("Problem encountered while refreshing tokens.", tokenResult.Exception); } }
public async Task <IActionResult> Exchange(OpenIdConnectRequest request) { if (request.IsPasswordGrantType()) { var user = await _userManager.FindByEmailAsync(request.Username) ?? await _userManager.FindByNameAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Please check that your email and password is correct" })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in" })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in" })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user account has been suspended" })); } // Ensure the user is enabled. if (!user.IsEnabled) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user account is disabled" })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Please check that your email and password is correct" })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } // Create a new authentication ticket. var ticket = await CreateTicketAsync(request, user); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } else if (request.IsRefreshTokenGrantType()) { // Retrieve the claims principal stored in the refresh token. var info = await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext); //var info = await HttpContext.Authentication.GetAuthenticateInfoAsync( // OpenIdConnectServerDefaults.AuthenticationScheme); // Retrieve the user profile corresponding to the refresh token. // Note: if you want to automatically invalidate the refresh token // when the user password/roles change, use the following line instead: // var user = _signInManager.ValidateSecurityStampAsync(info.Principal); var user = await _userManager.GetUserAsync(info.Principal); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The refresh token is no longer valid" })); } // Ensure the user is still allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user is no longer allowed to sign in" })); } // Create a new authentication ticket, but reuse the properties stored // in the refresh token, including the scopes originally granted. var ticket = await CreateTicketAsync(request, user, info.Properties); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported" })); }
public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { AuthenticateResult result = await AuthenticationHttpContextExtensions.AuthenticateAsync(this.HttpContext, "Cookies"); LoginViewModel signInModel = new LoginViewModel { ReturnUrl = returnUrl, FormMessage = "İşleminiz gerçekleştirilirken sorun oluştu." }; AuthenticateResult obj = result; if (obj == null || !obj.Succeeded) { return(this.View("SignIn", (object)signInModel)); } ClaimsPrincipal principal = result.Principal; if (principal == null) { return(this.View("SignIn", (object)signInModel)); } List <Claim> source = principal.Claims.ToList(); Claim claim = source.FirstOrDefault((Claim x) => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"); if (claim == null) { signInModel.FormMessage = "Kullanıcı bilgilerinize erişelemedi. Yetkilim uygulamasına erişim verdiğinize emin olup tekrar deneyin."; return(this.View("SignIn", (object)signInModel)); } string externalProvider = claim.Issuer; Claim emailClaim = null; if (externalProvider == "Facebook") { emailClaim = source.FirstOrDefault((Claim x) => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"); if (emailClaim == null) { signInModel.FormMessage = "E-Posta bilgilerinize erişelemedi. Yetkilim uygulamasının e-posta adresinize erişimine izin verdiğinize emin olup tekrar deneyin."; return(this.View("SignIn", (object)signInModel)); } } Claim nameClaim = source.FirstOrDefault((Claim x) => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"); string externalUserId = claim.Value; try { Result <UserDTO> result2 = await _userService.GetExternalUserAsync(externalProvider, externalUserId); int ıd; if (!result2.IsSuccess) { if (!(result2.ResultCode == "NOT_REGISTERED")) { signInModel.FormMessage = result2.FormMessage; return(this.View("SignIn", (object)signInModel)); } UserDTO model = new UserDTO { Name = nameClaim?.Value, Email = emailClaim?.Value }; Result <UserDTO> result3 = await _userService.AddExternalUserAsync(externalProvider, externalUserId, model); if (!result3.IsSuccess) { signInModel.FormMessage = result3.FormMessage; return(this.View("SignIn", (object)signInModel)); } ıd = result3.Data.Id; } else { ıd = result2.Data.Id; } List <Claim> claims = new List <Claim> { new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", ıd.ToString()), nameClaim, new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Member") }; ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(result.Ticket.Principal.Identity); claimsPrincipal.AddIdentity(new ClaimsIdentity(claims, "ClaimIdentity")); AuthenticationProperties val = new AuthenticationProperties(); val.IsPersistent = (true); await AuthenticationHttpContextExtensions.SignInAsync(this.HttpContext, "Cookies", claimsPrincipal, val); } catch (Exception ex) { LoggerExtensions.LogError(_logger, ex, "Facebook Post Error", Array.Empty <object>()); return(this.View("SignIn", (object)signInModel)); } return(this.LocalRedirect(returnUrl ?? "/")); }
internal async Task <bool> AuthorizeJwtAsync(HttpContext context) { return((await AuthenticationHttpContextExtensions.AuthenticateAsync( context, JwtBearerDefaults.AuthenticationScheme)).Succeeded); }