private async Task <AuthenticationTicket> CreateTicketAsync( OpenIdConnectRequest request, AppIdentityUser user, Microsoft.AspNetCore.Authentication.AuthenticationProperties properties = null) { // Create a new ClaimsPrincipal containing the claims that // will be used to create an id_token, a token or a code. var principal = await _signInManager.CreateUserPrincipalAsync(user); // Create a new authentication ticket holding the user identity. var ticket = new AuthenticationTicket(principal, properties, OpenIdConnectServerDefaults.AuthenticationScheme); if (!request.IsAuthorizationCodeGrantType() && !request.IsRefreshTokenGrantType()) { // Set the list of scopes granted to the client application. // Note: the offline_access scope must be granted // to allow OpenIddict to return a refresh token. ticket.SetScopes(new[] { OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.Email, OpenIdConnectConstants.Scopes.Profile, OpenIdConnectConstants.Scopes.OfflineAccess, OpenIddictConstants.Scopes.Roles }.Intersect(request.GetScopes())); } ticket.SetResources("resource_server"); // Note: by default, claims are NOT automatically included in the access and identity tokens. // To allow OpenIddict to serialize them, you must attach them a destination, that specifies // whether they should be included in access tokens, in identity tokens or in both. foreach (var claim in ticket.Principal.Claims) { // Never include the security stamp in the access and identity tokens, as it's a secret value. if (claim.Type == _identityOptions.Value.ClaimsIdentity.SecurityStampClaimType) { continue; } var destinations = new List <string> { OpenIdConnectConstants.Destinations.AccessToken }; // Only add the iterated claim to the id_token if the corresponding scope was granted to the client application. // The other claims will only be added to the access_token, which is encrypted when using the default format. if ((claim.Type == OpenIdConnectConstants.Claims.Name && ticket.HasScope(OpenIdConnectConstants.Scopes.Profile)) || (claim.Type == OpenIdConnectConstants.Claims.Email && ticket.HasScope(OpenIdConnectConstants.Scopes.Email)) || (claim.Type == OpenIdConnectConstants.Claims.Role && ticket.HasScope(OpenIddictConstants.Claims.Roles))) { destinations.Add(OpenIdConnectConstants.Destinations.IdentityToken); } claim.SetDestinations(destinations); } return(ticket); }
public Task SignInAsync(IHttpContextAccessor httpContextAccessor) { var claims = new List <Claim> { new Claim(ClaimTypes.Hash, Guid.NewGuid().ToString()) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddDays(100) //IssuedUtc = <DateTimeOffset>, // The time at which the authentication ticket was issued. //RedirectUri = <string> }; return(httpContextAccessor.HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties)); }
public async Task <IActionResult> ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. //var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); //var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); //return Challenge(properties, provider); /////////////////////////////////////////////// if (AccountOptions.WindowsAuthenticationSchemeName == provider) { // windows authentication needs special handling return(await ProcessWindowsLoginAsync(returnUrl)); } else { // start challenge and roundtrip the return URL and var props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties() { RedirectUri = Url.Action("ExternalLoginCallback"), Items = { { "returnUrl", returnUrl }, { "scheme", provider }, } }; return(Challenge(props, provider)); } }
public async Task SigninWeb(Login result, UserViewModel resultobj) { try { if (result != null) { //TODO: we have to change "resultobj.rolename" instead of "Admin" for role, waiting for full data information var claims = new[] { new Claim("name", result.UserName) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(Config.SessionTimeout), IsPersistent = true, RedirectUri = "/login" }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); //TODO: we have to change "resultobj" instead of "result" for logged user information, waiting for full data information HttpContext.Session.Set("UserDetails", resultobj); } } catch (Exception ex) { throw ex; } }
public void SignIn(AuthViewModel account) { var permission = JsonConvert.SerializeObject(account.Permissions); var claims = new List <Claim> { new Claim("AccountId", account.Id.ToString()), new Claim(ClaimTypes.Name, account.FullName), new Claim(ClaimTypes.Role, account.RoleId.ToString()), new Claim("Username", account.Username), // Or Use ClaimTypes.NameIdentifier new Claim("Fullname", account.FullName), new Claim("Picture", account.Picture), new Claim("permissions", permission), }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1) }; _contextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); }
public ActionResult ValidateAuthToken(string access_token) { if (string.IsNullOrEmpty(access_token)) { return(BadRequest("Invalid token")); } IPrincipal principal = _manager.ValidateAuthenticationToken(access_token, _certificateFilePath); if (principal != null) { var tokens = new List <AuthenticationToken>() { new AuthenticationToken() { Name = "access_token", Value = access_token } }; var prop = new Microsoft.AspNetCore.Authentication.AuthenticationProperties(); prop.IsPersistent = true; prop.StoreTokens(tokens); HttpContext.SignInAsync(principal as ClaimsPrincipal, prop); } return(RedirectToAction("Profile", "User")); }
public IActionResult account_login() { var userName = HttpContext.User.Identity.Name; var properties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties(); properties.RedirectUri = $"http://localhost:5002/login_callback"; return(Challenge(properties, "Haravan")); }
public IActionResult request_grant() { var userName = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; var properties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties();; properties.SetParameter("grant_service", true); properties.RedirectUri = $"http://localhost:5002/request_grant_callback"; return(Challenge(properties, "Haravan")); }
public async Task <IActionResult> ExternalLoginCallback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } // lookup our user and external provider info var(user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = await AutoProvisionUserAsync(provider, providerUserId, claims); } // this allows us to collect any additonal claims or properties // for the specific prtotocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List <Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user // we must issue the cookie maually, and can't use the SignInManager because // it doesn't expose an API to issue additional claims from the login workflow var principal = await _signInManager.CreateUserPrincipalAsync(user); additionalLocalClaims.AddRange(principal.Claims); var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id.ToString(); await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id.ToString(), name)); await HttpContext.SignInAsync(user.Id.ToString(), name, provider, localSignInProps, additionalLocalClaims.ToArray()); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); // validate return URL and redirect back to authorization endpoint or a local page var returnUrl = result.Properties.Items["returnUrl"]; if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } return(Redirect("~/")); }
/// <summary> /// The Context passed when a Challenge causes a redirect to authorize endpoint in the WeixinOAuth middleware. /// </summary> /// <param name="context">The HTTP request context.</param> /// <param name="options">The <see cref="WeixinOAuthOptions"/>.</param> /// <param name="properties">The authentication properties of the challenge.</param> /// <param name="redirectUri">The initial redirect URI.</param> public WeixinOAuthRedirectToAuthorizationContext( HttpContext context, AuthenticationScheme scheme, WeixinOAuthOptions options, Microsoft.AspNetCore.Authentication.AuthenticationProperties properties, string redirectUri) : base(context, scheme, options) { Properties = properties; RedirectUri = redirectUri; }
protected override async Task <AuthenticationTicket> CreateTicketAsync( ClaimsIdentity identity, Microsoft.AspNetCore.Authentication.AuthenticationProperties properties, OAuthTokenResponse tokens) { var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "access_token", tokens.AccessToken); Dictionary <string, string> queryString = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { ["application_key"] = Options.PublicKey, ["format"] = "json", ["__online"] = "false" }; if (Options.Fields.Count != 0) { queryString.Add("fields", string.Join(",", Options.Fields)); } queryString.Add("sig", GetSignature(tokens.AccessToken, queryString)); address = QueryHelpers.AddQueryString(address, queryString); var response = await Backchannel.GetAsync(address, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("Произошла ошибка при получении профиля пользователя: удаленный сервер " + "вернул {Status} ответ со следующей информацией: {Headers} {Body}.", response.StatusCode, response.Headers.ToString(), await response.Content.ReadAsStringAsync()); throw new HttpRequestException("Произошла ошибка при получении профиля пользователя."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var user = (JObject)payload; //identity.AddOptionalClaim(ClaimTypes.NameIdentifier, user.Value<string>("uid"), Options.ClaimsIssuer) // .AddOptionalClaim(ClaimTypes.Name, user.Value<string>("name"), Options.ClaimsIssuer) // .AddOptionalClaim(ClaimTypes.GivenName, user.Value<string>("first_name"), Options.ClaimsIssuer) // .AddOptionalClaim(ClaimTypes.Surname, user.Value<string>("last_name"), Options.ClaimsIssuer) // .AddOptionalClaim(ClaimTypes.Email, user.Value<string>("email"), Options.ClaimsIssuer); var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, user); context.RunClaimActions(); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
public async Task <IActionResult> ExternalLogin(string provider, string returnUrl) { returnUrl = Url.Action("ExternalLoginCallback", new { returnUrl = returnUrl }); // windows authentication is modeled as external in the asp.net core authentication manager, so we need special handling if (AccountOptions.WindowsAuthenticationSchemes.Contains(provider)) { // but they don't support the redirect uri, so this URL is re-triggered when we call challenge if (HttpContext.User is WindowsPrincipal wp) { var props = new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties(); props.Items.Add("scheme", AccountOptions.WindowsAuthenticationProviderName); var id = new ClaimsIdentity(provider); id.AddClaim(new Claim(JwtClaimTypes.Subject, HttpContext.User.Identity.Name)); id.AddClaim(new Claim(JwtClaimTypes.Name, HttpContext.User.Identity.Name)); // add the groups as claims -- be careful if the number of groups is too large if (AccountOptions.IncludeWindowsGroups) { var wi = wp.Identity as WindowsIdentity; var groups = wi.Groups.Translate(typeof(NTAccount)); var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value)); id.AddClaims(roles); } await HttpContext.SignInAsync(id.GetSubjectId(), new ClaimsPrincipal(id)); if (string.IsNullOrWhiteSpace(returnUrl)) { returnUrl = "/ManageHome"; } return(Redirect(returnUrl)); } else { // this triggers all of the windows auth schemes we're supporting so the browser can use what it supports return(new ChallengeResult(AccountOptions.WindowsAuthenticationSchemes)); } } else { // start challenge and roundtrip the return URL var props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { RedirectUri = returnUrl, Items = { { "scheme", provider } } }; return(new ChallengeResult(provider, props)); } }
public AuthenticationProperties ConfigureExternalAuthenticationProperties(string provider, string redirectUrl, string userId = null) { var properties = new AuthenticationProperties { RedirectUri = redirectUrl }; properties.Items[LoginProviderKey] = provider; if (userId != null) { properties.Items[XsrfKey] = userId; } return(properties); }
protected override async Task <AuthenticationTicket> CreateTicketAsync( ClaimsIdentity identity, Microsoft.AspNetCore.Authentication.AuthenticationProperties properties, OAuthTokenResponse tokens) { var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "access_token", tokens.AccessToken); if (Options.Fields.Count != 0) { address = QueryHelpers.AddQueryString(address, "fields", string.Join(",", Options.Fields)); } var response = await Backchannel.GetAsync(address, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("Произошла ошибка при получении профиля пользователя: удаленный сервер " + "вернул {Status} ответ со следующей информацией: {Headers} {Body}.", response.StatusCode, response.Headers.ToString(), await response.Content.ReadAsStringAsync()); throw new HttpRequestException("Произошла ошибка при получении профиля пользователя."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var user = (JObject)payload["response"][0]; foreach (var scope in Options.Scope) { var scope_value = tokens.Response.Value <string>(scope); if (!string.IsNullOrEmpty(scope_value)) { user.Add(scope, scope_value); } } identity.AddOptionalClaim(ClaimTypes.NameIdentifier, user.Value <string>("uid"), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.GivenName, user.Value <string>("first_name"), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Surname, user.Value <string>("last_name"), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Email, user.Value <string>("email"), Options.ClaimsIssuer); var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, user); context.RunClaimActions(); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true //var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true); var testUser = _testUserStore.FindByUsername(Input.UserName); if (testUser == null) { ModelState.AddModelError(nameof(Input.UserName), "user not exists"); } var result = _testUserStore.ValidateCredentials(Input.UserName, Input.Password); if (result) { _logger.LogInformation("User logged in."); var props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties() { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) }; await HttpContext.SignInAsync(testUser.SubjectId, props); return(LocalRedirect(returnUrl)); //return Redirect(returnUrl); } //if (result.RequiresTwoFactor) //{ // return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }); //} //if (result.IsLockedOut) //{ // _logger.LogWarning("User account locked out."); // return RedirectToPage("./Lockout"); //} else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(Page()); } } // If we got this far, something failed, redisplay form return(Page()); }
private async Task <IActionResult> ProcessWindowsLoginAsync(string returnUrl) { // see if windows auth has already been requested and succeeded var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName); if (result?.Principal is WindowsPrincipal wp) { // we will issue the external cookie and then redirect the // user back to the external callback, in essence, tresting windows // auth the same as any other external authentication mechanism var props = new AuthenticationProperties() { RedirectUri = Url.Action("ExternalLoginCallback"), Items = { { "returnUrl", returnUrl }, { "scheme", AccountOptions.WindowsAuthenticationSchemeName }, } }; var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName); id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name)); id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name)); // add the groups as claims -- be careful if the number of groups is too large if (AccountOptions.IncludeWindowsGroups) { var wi = wp.Identity as WindowsIdentity; var groups = wi.Groups.Translate(typeof(NTAccount)); var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value)); id.AddClaims(roles); } await HttpContext.SignInAsync( IdentityConstants.ExternalScheme, new ClaimsPrincipal(id), props); return(Redirect(props.RedirectUri)); } else { // trigger windows auth // since windows auth don't support the redirect uri, // this URL is re-triggered when we call challenge return(Challenge(AccountOptions.WindowsAuthenticationSchemeName)); } }
public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); var systemProperties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { IsPersistent = properties.IsPersistent, RedirectUri = properties.RedirectUri, AllowRefresh = properties.AllowRefresh, ExpiresUtc = properties.ExpiresUtc, IssuedUtc = properties.IssuedUtc }; return(Challenge(systemProperties, provider)); }
private AuthenticationProperties GenerateAuthenticationProperties(AuthenticateResult info) { //if the external provider issued an id_token, we'll keep it for signout AuthenticationProperties props = null; var id_token = info.Properties.GetTokenValue("id_token"); if (id_token != null) { props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties(); props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } return(props); }
public static async Task PerformSignInAsync(User user, HttpContext httpContext) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Name) }; var props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddYears(1) }; var id = new ClaimsIdentity(claims, PopForumsAuthorizationDefaults.AuthenticationScheme); await httpContext.SignInAsync(PopForumsAuthorizationDefaults.AuthenticationScheme, new ClaimsPrincipal(id), props); }
private async Task SignInAsync(Chef user) { var claims = new List <Claim> { new Claim("UserName", user.ChefUserName), new Claim("FullName", user.FirstName + " " + user.LastName), new Claim("Type", user.Type.ToString()), new Claim(ClaimTypes.Role, user.Type.ToString()), }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); }
public IActionResult ExternalLogin(string provider, string returnUrl) { if (returnUrl != null) { returnUrl = UrlEncoder.Default.Encode(returnUrl); } returnUrl = "/account/externallogincallback?returnUrl=" + returnUrl; // start challenge and roundtrip the return URL var props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { RedirectUri = returnUrl, Items = { { "scheme", provider } } }; return(new ChallengeResult(provider, props)); }
public async Task SignIn(Registration user, bool isPersistent = false) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var claims = new List <Claim>(); if (!string.IsNullOrEmpty(user.MemberName)) { claims.Add(new Claim(ClaimTypes.Name, user.MemberName, ClaimValueTypes.String, "ACIG")); } if (!string.IsNullOrEmpty(user.MemberMobileNumber)) { claims.Add(new Claim(ClaimTypes.MobilePhone, user.MemberMobileNumber, ClaimValueTypes.String, "ACIG")); } if (!string.IsNullOrEmpty(user.Iqama_NationalID)) { claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Iqama_NationalID, ClaimValueTypes.String, "ACIG")); } foreach (var roles in Enum.GetNames(typeof(RegistrationRole))) { claims.Add(new Claim(ClaimTypes.Role, roles)); } var CustomerIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var CustomerPrincipal = new ClaimsPrincipal(CustomerIdentity); //set value indicating whether session is persisted and the time at which the authentication was issued var authenticationProperties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { IsPersistent = isPersistent, IssuedUtc = DateTime.UtcNow }; //sign in await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, CustomerPrincipal, authenticationProperties); //cache authenticated customer _cachedUser = user; }
public async Task <IActionResult> Login(LoginInputModel model) { if (ModelState.IsValid) { // validate username/password against in-memory store if (_users.ValidateCredentials(model.Username, model.Password)) { AuthenticationProperties props = null; // only set explicit expiration here if persistent. // otherwise we reply upon expiration configured in cookie middleware. if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; } ; // issue authentication cookie with subject ID and username var user = _users.FindByUsername(model.Username); await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username)); await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props); // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint or a local page if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } return(Redirect("~/")); } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials")); ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await _account.BuildLoginViewModelAsync(model); return(View(vm)); }
protected async Task <AuthenticationTicket> CreateTicketAsync(ApplicationUser applicationUser, IEnumerable <string> resources, IEnumerable <string> scopes, Microsoft.AspNetCore.Authentication.AuthenticationProperties properties = null) { ClaimsPrincipal principal = await signInManager.CreateUserPrincipalAsync(applicationUser); (principal.Identity as ClaimsIdentity).AddClaim("given_name", applicationUser.UserName, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); if (properties == null) { properties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties(); } AuthenticationTicket ticket = new AuthenticationTicket(principal, properties, OpenIdConnectServerDefaults.AuthenticationScheme); ticket.SetResources(resources); ticket.SetScopes(scopes); return(ticket); }
protected override string BuildChallengeUrl(Microsoft.AspNetCore.Authentication.AuthenticationProperties properties, string redirectUri) { var scope = FormatScope(); var state = Options.StateDataFormat.Protect(properties); var queryBuilder = new QueryBuilder() { { "client_id", Options.ClientId }, { "scope", scope }, { "response_type", "code" }, { "redirect_uri", redirectUri }, { "state", state }, { "show_dialog", Options.ShowDialog ? "true" : "false" } }; return(Options.AuthorizationEndpoint + queryBuilder.ToString()); }
public async Task <IActionResult> LinkLogin(string provider) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action(nameof(LinkLoginCallback)); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); var systemProperties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { IsPersistent = properties.IsPersistent, RedirectUri = properties.RedirectUri, AllowRefresh = properties.AllowRefresh, ExpiresUtc = properties.ExpiresUtc, IssuedUtc = properties.IssuedUtc }; return(new ChallengeResult(provider, systemProperties)); }
public async Task <IActionResult> Authorize(OpenIdConnectRequest request) { Debug.Assert(request.IsAuthorizationRequest(), "The OpenIddict binder for ASP.NET Core MVC is not registered. " + "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called."); if (!User.Identity.IsAuthenticated) { // If the client application request promptless authentication, // return an error indicating that the user is not logged in. if (request.HasPrompt(OpenIdConnectConstants.Prompts.None)) { var properties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties(new Dictionary <string, string> { [OpenIdConnectConstants.Properties.Error] = OpenIdConnectConstants.Errors.LoginRequired, [OpenIdConnectConstants.Properties.ErrorDescription] = "The user is not logged in." }); // Ask OpenIddict to return a login_required error to the client application. return(Forbid(properties, OpenIdConnectServerDefaults.AuthenticationScheme)); } return(Challenge()); } // Retrieve the profile of the logged in user. var user = await _userManager.GetUserAsync(User); if (user == null) { return(View("Error", new ErrorViewModel { Error = OpenIdConnectConstants.Errors.ServerError, ErrorDescription = "An internal error has occurred" })); } // Create a new authentication ticket. var ticket = await CreateTicketAsync(request, user); // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens. return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); }
public async Task <IActionResult> LoginAsync([NotNull] string userName, [NotNull] string password, string returnUrl = null) { ViewData["returnUrl"] = returnUrl; UserInfo userInfo = this._userInfoService.GetByUserName(userName); if (userInfo == null || userInfo.Password != password) { return(View()); } Microsoft.AspNetCore.Authentication.AuthenticationProperties props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1)) }; await base.HttpContext.SignInAsync(new IdentityServerUser(userInfo.Id.ToString()) { DisplayName = userInfo.UserName, AuthenticationTime = DateTime.Now }, props); return(Redirect(returnUrl)); }
public async Task <IActionResult> Login(LoginViewModel loginViewModel) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(loginViewModel.Username); if (user == null) { ModelState.AddModelError(nameof(loginViewModel.Username), "用户名不存在"); } else { if (await _userManager.CheckPasswordAsync(user, loginViewModel.Password)) { AuthenticationProperties proper = null; if (loginViewModel.RememberMe) { proper = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30)), IsPersistent = true }; } //var iuser = new IdentityServer4.IdentityServerUser(user.SubjectId) //{ // DisplayName = user.Username //}; //await HttpContext.SignInAsync(iuser, proper); await _signinManager.SignInAsync(user, proper); if (_identityServerInteraction.IsValidReturnUrl(loginViewModel.ReturnUrl)) { return(Redirect(loginViewModel.ReturnUrl)); } } ModelState.AddModelError(nameof(loginViewModel.Password), "密码错误"); } } return(View()); }
public IActionResult Login(LoginViewModel loginViewModel, string returnurl) { if (ModelState.IsValid) { var user = da.ValidateLogin(loginViewModel.UserName, loginViewModel.Password); if (user != null) { List <Claim> id = new List <Claim>(); id.Add(new Claim(ClaimTypes.Name, loginViewModel.UserName)); id.Add(new Claim(ClaimTypes.NameIdentifier, user.email)); id.Add(new Claim(ClaimTypes.Email, user.email)); id.Add(new Claim(ClaimTypes.IsPersistent, loginViewModel.RememberMe.ToString())); id.Add(new Claim(ClaimTypes.Actor, loginViewModel.UserName)); // cuman demo, default role adalah user dan reguler. var roles = new string[] { "user", "reguler" }; foreach (var r in roles) { id.Add(new Claim(ClaimTypes.Role, r)); } ClaimsIdentity ids = new ClaimsIdentity(id, CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.NameIdentifier, ClaimTypes.Role); ids.AddClaim(new Claim(ClaimTypes.Actor, loginViewModel.UserName)); var principal = new ClaimsPrincipal(ids); var props = new Microsoft.AspNetCore.Authentication.AuthenticationProperties { IsPersistent = loginViewModel.RememberMe }; if (returnurl != null || !string.IsNullOrEmpty(returnurl)) { props.RedirectUri = returnurl; } var s = SignIn(principal, CookieAuthenticationDefaults.AuthenticationScheme); s.Properties = props; return(s); } } return(View(loginViewModel)); }