private void AddServices(IServiceCollection services) { services.AddMvc().WithRazorPagesRoot("/Pages").AddRazorPagesOptions(o => o.Conventions.AuthorizeFolder("/", MsftAuthorizationPolicyName).AllowAnonymousToPage("/Index")); services.AddApplicationInsightsTelemetry(Configuration.GetSection("ApplicationInsights").Bind); services.AddAuthentication() .AddGitHubOAuth(Configuration.GetSection("GitHubAuthentication"), GitHubScheme) .AddScheme <UserTokenOptions, GitHubUserTokenHandler>("github-token", o => { }) .AddCookie(IdentityConstants.ApplicationScheme, o => { o.ExpireTimeSpan = TimeSpan.FromDays(7); o.SlidingExpiration = true; o.Cookie.IsEssential = true; o.LoginPath = "/signin"; o.LogoutPath = "/signout"; o.ReturnUrlParameter = "r"; o.Events = new CookieAuthenticationEvents { OnValidatePrincipal = async ctx => { GitHubClaimResolver resolver = ctx.HttpContext.RequestServices.GetRequiredService <GitHubClaimResolver>(); ClaimsIdentity identity = ctx.Principal.Identities.FirstOrDefault(); identity?.AddClaims(await resolver.GetMembershipClaims(resolver.GetAccessToken(ctx.Principal))); } }; }) ; services.AddAzureTableTokenStore(o => Configuration.GetSection("AzureTableTokenStore").Bind(o)); services.AddAuthorization( options => { options.AddPolicy( MsftAuthorizationPolicyName, policy => { policy.RequireAuthenticatedUser(); if (!Env.IsDevelopment()) { policy.RequireRole("github:team:dotnet/dnceng", "github:team:dotnet/bots-high"); } }); }); services.AddScoped <SimpleSigninMiddleware>(); services.AddGitHubTokenProvider(); services.AddSingleton <IInstallationLookup, InMemoryCacheInstallationLookup>(); services.AddContextAwareAuthenticationScheme(o => { o.SelectScheme = p => p.StartsWithSegments("/api") ? "github-token" : IdentityConstants.ApplicationScheme; }); services.AddSingleton <GitHubJwtFactory>(); }
public ActionResult Submit(LoginViewModel model) { if (model.Email.Equals("*****@*****.**", StringComparison.OrdinalIgnoreCase) && model.Password.Equals("123")) { var claimIdentity = new ClaimsIdentity(ApplicationConstant.AUTHENTICATION_TYPE); claimIdentity.AddClaims(new List <Claim> { new Claim(ClaimTypes.Email, model.Email), new Claim(ClaimTypes.NameIdentifier, model.Email), new Claim(ClaimTypes.Name, model.Email) }); HttpContext.GetOwinContext().Authentication.SignIn(claimIdentity); } if (model.ReturnUrl.IsNotNullOrEmpty()) { return(Redirect(model.ReturnUrl)); } return(RedirectToAction("Index")); }
private async Task <ClaimsIdentity> GetUserClaims(ICollection <Claim> claims, IdentityUser user) { var userRoles = await _userManager.GetRolesAsync(user); claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id)); claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email)); claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, ToUnixEpochDate(DateTime.UtcNow).ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64)); foreach (var userRole in userRoles) { claims.Add(new Claim("role", userRole)); } var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(claims); return(identityClaims); }
public static string GetSelfIdentifiedUserToken( string username, string partyId, string userId) { List <Claim> claims = new List <Claim>(); string issuer = "www.altinn.no"; claims.Add(new Claim(ClaimTypes.NameIdentifier, userId.ToString(), ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.UserId, userId.ToString(), ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.UserName, username, ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.PartyID, partyId.ToString(), ClaimValueTypes.Integer32, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticateMethod, "Mock", ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticationLevel, "0", ClaimValueTypes.Integer32, issuer)); ClaimsIdentity identity = new ClaimsIdentity("mock"); identity.AddClaims(claims); ClaimsPrincipal principal = new ClaimsPrincipal(identity); string token = JwtTokenMock.GenerateToken(principal, new TimeSpan(1, 1, 1)); return(token); }
public static async Task <String> GerarJwt(String email, UserManager <IdentityUser> userManager, ConfiguracoesDeAutenticacao configuracoesDeAutenticacao) { var user = await userManager.FindByEmailAsync(email); var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(await userManager.GetClaimsAsync(user)); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(configuracoesDeAutenticacao.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = identityClaims, Issuer = configuracoesDeAutenticacao.Emissor, Audience = configuracoesDeAutenticacao.ValidoEm, Expires = DateTime.UtcNow.AddHours(configuracoesDeAutenticacao.ExpiracaoHoras), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; return(tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor))); }
public async Task <ClaimsIdentity> ObterClaimsUsuario(ICollection <Claim> claims, LocaAppUserModel user) { var userRoles = await _userManager.GetRolesAsync(user); claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id)); claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email)); claims.Add(new Claim("Tipo", user.Tipo.ToString())); //pega qual o tipo do usuario claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, ToUnixEpochDate(DateTime.UtcNow).ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64)); foreach (var userRole in userRoles) { claims.Add(new Claim("role", userRole)); } var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(claims); return(identityClaims); }
async Task <string> GetJWT(string username) { var user = await _userManager.FindByNameAsync(username); var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(await _userManager.GetClaimsAsync(user)); // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = identityClaims, Issuer = _appSettings.Emissor, Audience = _appSettings.ValidoEm, Expires = DateTime.UtcNow.AddHours(_appSettings.ExpiracaoHoras), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; return(tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor))); }
public async Task <ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { // Cast the principal identity to a Claims identity to access claims etc... var oldIdentity = (ClaimsIdentity)principal.Identity; // "Clone" the old identity to avoid nasty side effects. // NB: We take a chance to replace the claim type used to define the roles with our own. var newIdentity = new ClaimsIdentity( oldIdentity.Claims, oldIdentity.AuthenticationType, oldIdentity.NameClaimType, RoleClaimType); // Fetch the roles for the user and add the claims of the correct type so that roles can be recognized. var roles = await _roleProvider.GetUserRolesAsync(newIdentity); newIdentity.AddClaims(roles.Select(r => new Claim(RoleClaimType, r))); // Create and return a new claims principal return(new ClaimsPrincipal(newIdentity)); }
public async Task <IActionResult> Login(string userName, string returnUrl = null) { const string Issuer = "https://contoso.com"; var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, userName, ClaimValueTypes.String, Issuer)); var userIdentity = new ClaimsIdentity("Cookie"); userIdentity.AddClaims(claims); var userPrincipal = new ClaimsPrincipal(userIdentity); await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false }); return(RedirectToLocal(returnUrl)); }
public void TokenMock_VerifyEncryptedAndSignedToken() { // Arrange List <Claim> claims = new List <Claim>(); string pid = "19108000239"; string amr = "MinId-PIN"; claims.Add(new Claim("pid", pid)); claims.Add(new Claim("amr", amr)); ClaimsIdentity identity = new ClaimsIdentity(); identity.AddClaims(claims); ClaimsPrincipal externalPrincipal = new ClaimsPrincipal(identity); string externalToken = JwtTokenMock.GenerateEncryptedAndSignedToken(externalPrincipal, TimeSpan.FromMinutes(2)); ClaimsPrincipal claimsPrincipal = JwtTokenMock.ValidateEncryptedAndSignedToken(externalToken); Assert.Equal(externalPrincipal.Identity.Name, claimsPrincipal.Identity.Name); }
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken) { validatedToken = null; var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); //这里的用意应该是创建一个验证,返回到下一步中 if (securityToken == "abc") { var claims = new Claim[] { new Claim(ClaimTypes.Name, "abc"), new Claim(ClaimTypes.Role, "admin"), new Claim(ClaimsIdentity.DefaultRoleClaimType, "user") }; identity.AddClaims(claims); } var principal = new ClaimsPrincipal(identity); return(principal); }
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, treating windows // auth the same as any other external authentication mechanism var props = new AuthenticationProperties { RedirectUri = Url.Action("Callback"), Items = { { "returnUrl", returnUrl }, { "scheme", AccountOptions.WindowsAuthenticationSchemeName } } }; var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName); id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.FindFirst(ClaimTypes.PrimarySid).Value)); 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(IdentityServerConstants.ExternalCookieAuthenticationScheme, new ClaimsPrincipal(id), props); return(Redirect(props.RedirectUri)); } // 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 static string CreateJwtToken(AuthenticationTicket data, string issuer, SigningCredentials signingCredentials) { string audience = issuer; // As JWT doesn't have a mechanism of passing metadata about what claim should be the name/subject the JWT handler // users the default Name claim type. If the identity has another claim type as the name type we need to // switch it to the DefaultNameClaimType. var identity = new ClaimsIdentity(data.Identity); if (identity.NameClaimType != ClaimsIdentity.DefaultNameClaimType && !string.IsNullOrWhiteSpace(identity.Name)) { identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, identity.Name)); identity.RemoveClaim(identity.Claims.First(c => c.Type == identity.NameClaimType)); } // And now do the same for roles. List<Claim> roleClaims = identity.Claims.Where(c => c.Type == identity.RoleClaimType).ToList(); if (identity.RoleClaimType != ClaimsIdentity.DefaultRoleClaimType && roleClaims.Any()) { foreach (var roleClaim in roleClaims) { identity.RemoveClaim(roleClaim); identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, roleClaim.Value, roleClaim.ValueType, roleClaim.Issuer, roleClaim.OriginalIssuer)); } } identity.AddClaims(new[] { new Claim("iat", GetEpocTimeStamp()), new Claim("jti", Guid.NewGuid().ToString("N")) }); Lifetime lifetime = new Lifetime(null, null); if (data.Properties.IssuedUtc != null || data.Properties.ExpiresUtc != null) { lifetime = new Lifetime(data.Properties.IssuedUtc != null ? (DateTime?)((DateTimeOffset)data.Properties.IssuedUtc).UtcDateTime : null, data.Properties.ExpiresUtc != null ? (DateTime?)((DateTimeOffset)data.Properties.ExpiresUtc).UtcDateTime : null); } var handler = new JwtSecurityTokenHandler(); return handler.CreateToken(issuer, audience, identity, lifetime.Created, lifetime.Expires, signingCredentials).RawData; }
public async Task <string> GetJwt(string name = "", string pass = "") { string jwtStr = string.Empty; bool suc = false; AjaxResult result = new AjaxResult(); Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString()); await Task.Run(() => { result.msg = "***"; Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString()); suc = string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass); }); if (suc) { Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString()); result.msg = "用户名或密码不能为空"; result.isok = false; return(Newtonsoft.Json.JsonConvert.SerializeObject(result)); } PermissionRequirement _requirement = (PermissionRequirement)HttpContext.RequestServices.GetService(typeof(PermissionRequirement)); var userRoles = "Admin"; //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色 var claims = new List <Claim> { new Claim(ClaimTypes.Name, name), new Claim(JwtRegisteredClaimNames.Jti, "1"), //假设当前的用户ID=1 new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) }; claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s))); //用户标识 var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaims(claims); var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement); return(JsonConvert.SerializeObject(token)); }
public async Task <ActionResult> MicrosoftCallback(String returnUrl) { ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync(); AppUser user = await UserManager.FindAsync(loginInfo.Login); if (user == null) { user = new AppUser { Email = loginInfo.Email, UserName = loginInfo.DefaultUserName, City = Cities.LONDON, Country = Countries.UK }; IdentityResult result = await UserManager.CreateAsync(user); if (!result.Succeeded) { return(View("Error", result.Errors)); } else { result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login); if (!result.Succeeded) { return(View("Error", result.Errors)); } } } ClaimsIdentity claimsIdentity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); claimsIdentity.AddClaims(loginInfo.ExternalIdentity.Claims); AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, claimsIdentity); return(Redirect(returnUrl ?? "/")); }
public async Task <IActionResult> Refresh() { var userId = _aspNetUser.Id; var user = await _userManager.FindByIdAsync(userId); if (user == null) { NotifyError("refresh", "Usuário não encontrado."); return(Response()); } var roles = await _userManager.GetRolesAsync(user); var claims = await _userManager.GetClaimsAsync(user); ClaimsIdentity identity = user.GenerateClaimsIdentity(ClaimsIdentity.DefaultRoleClaimType, roles); identity.AddClaims(claims); DateTime dataCriacao = DateTime.Now; DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(_tokenConfigurations.Seconds); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = _tokenConfigurations.Issuer, Audience = _tokenConfigurations.Audience, SigningCredentials = _signingConfigurations.SigningCredentials, Subject = identity, NotBefore = dataCriacao, Expires = dataExpiracao }); var token = handler.WriteToken(securityToken); return(Response(new AuthenticationResultViewModel(true, dataCriacao, dataExpiracao, token))); }
public async Task <IActionResult> Login(LoginModel model) { if (model == null) { return(this.View()); } if (!this.ModelState.IsValid) { return(this.View(model)); } bool isValid = this._authenticationProvider.IsValidCredentials(model.UserName, model.Password); if (!isValid) { this.ModelState.AddModelError(nameof(model.Password), "Invalid username or password. Please try again."); return(this.View()); } ClaimsIdentity userIdentity = new ClaimsIdentity(KnownAuthenticationScheme.AdministrationScheme); userIdentity.AddClaims(new[] { new Claim(ClaimTypes.Name, model.UserName, ClaimValueTypes.String, "https://ifs") }); ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity); AuthenticationProperties authenticationOptions = new AuthenticationProperties { AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30), IsPersistent = false }; await this.HttpContext.SignInAsync(KnownAuthenticationScheme.AdministrationScheme, userPrincipal, authenticationOptions); string returnUrl = String.IsNullOrEmpty(model.ReturnUrl) ? this.Url.Action("Index", "Upload") : model.ReturnUrl; return(this.Redirect(returnUrl)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { var kimlikJson = JObject.Parse(await GetJson("Kimlik-Dogrula", tokens.AccessToken)); var userJson = JObject.Parse(await GetJson("Ad-Soyad", tokens.AccessToken))["kullaniciBilgileri"]; // Temel-Bilgileri Adres-Bilgileri Iletisim-Bilgileri var claims = new List <Claim>(); claims.Add(new Claim(JwtClaimTypes.Subject, userJson["kimlikNo"].ToString())); claims.Add(new Claim(JwtClaimTypes.Name, userJson["ad"].ToString() + " " + userJson["soyad"].ToString())); claims.Add(new Claim(JwtClaimTypes.GivenName, userJson["ad"].ToString())); claims.Add(new Claim(JwtClaimTypes.FamilyName, userJson["soyad"].ToString())); claims.Add(new Claim(EDevletDefaults.LoginMethodClaimName, kimlikJson["level"].ToString())); claims.Add(new Claim(EDevletDefaults.AccessTokenPropName, tokens.AccessToken)); properties.Items[EDevletDefaults.AccessTokenPropName] = tokens.AccessToken; var scope = properties.Items["scope"].Split(" "); if (scope.Contains("address")) { var adresJson = JObject.Parse(await GetJson("Adres-Bilgileri", tokens.AccessToken))["adresBilgileri"]; claims.Add(new Claim(JwtClaimTypes.Address, adresJson.ToString())); } if (scope.Contains("personal_info")) { var temelJson = JObject.Parse(await GetJson("Temel-Bilgileri", tokens.AccessToken))["kullaniciBilgileri"]; claims.Add(new Claim("marital_status", temelJson["medeniHal"].ToString())); claims.Add(new Claim("mother_name", temelJson["anneAd"].ToString())); claims.Add(new Claim("father_name", temelJson["babaAd"].ToString())); claims.Add(new Claim(JwtClaimTypes.BirthDate, temelJson["dogumTarihi"].ToString())); claims.Add(new Claim(JwtClaimTypes.Gender, temelJson["cinsiyet"].ToString())); } if (scope.Contains("communication_info")) { var iletisimJson = JObject.Parse(await GetJson("Iletisim-Bilgileri", tokens.AccessToken))["kullaniciBilgileri"]; claims.Add(new Claim(JwtClaimTypes.PhoneNumber, iletisimJson["cepTelefon"].ToString())); claims.Add(new Claim(JwtClaimTypes.Email, iletisimJson["eposta"].ToString())); } identity.AddClaims(claims); var principal = new ClaimsPrincipal(identity); return(new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.SignInScheme)); }
//[ProducesResponseType(200)] //[ProducesResponseType(401)] //[ProducesResponseType(500)] public async Task <IActionResult> Index([FromBody] LoginModel loginModel) { var user = await _userManager.FindByNameAsync(loginModel.UserName); if (user == null || !await _userManager.CheckPasswordAsync(user, loginModel.Password)) { return(Unauthorized()); } var login = await _registrationRepository.GetByEmailAysnc(user.Email); var roles = await _userManager.GetRolesAsync(user); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.PhoneNumber ?? "017XXXXXXXXX"), new Claim(JwtRegisteredClaimNames.Jti, login.Id.ToString()) }; var claimIdentity = new ClaimsIdentity(claims); claimIdentity.AddClaims(roles.Select(role => new Claim(ClaimTypes.Role, role))); var key = Convert.FromBase64String(_configuration["AppSettings:Key"]); var sighingkey = new SymmetricSecurityKey(key); var token = new JwtSecurityToken( issuer: "http://oec.com", audience: "http://oec.com", expires: DateTime.UtcNow.AddHours(12), claims: claimIdentity.Claims, signingCredentials: new SigningCredentials(sighingkey, SecurityAlgorithms.HmacSha256) ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo, me = new { user.Email, user.PhoneNumber, user.UserName, login.Id, login.FirstLastName } })); }
public async Task <AppPrincipal> CreatePrincipal(IKeyValueSettings settings, Messages messages, object parameter = null) { Identity = new ClaimsIdentity("OAuth2Bearer", System.Security.Claims.ClaimTypes.Upn, ClaimsIdentity.DefaultRoleClaimType); if (null == settings) { throw new ArgumentNullException(nameof(settings)); } if (null == messages) { throw new ArgumentNullException(nameof(messages)); } /// when we have no internet connectivity may be we have claims in cache. if (NetworkStatus.None == NetworkInformation.Status) { // In a scenario where the claims cached are always for one user like a UI, the identity is not used => so retrieving the claims in the cache is possible! var identity = new ClaimsIdentity(); cachedClaims = GetClaimsFromCache(identity); Identity.AddClaims(cachedClaims.Select(p => new Claim(p.ClaimType, p.Value))); messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Information, "Create the principal from the cache due to no network connectivity.")); } else { await BuildTheIdentity(settings, messages, parameter); } var authorization = BuildAuthorization(settings, messages); var user = BuildProfile(settings, messages); var principal = new AppPrincipal(authorization, Identity, null) { Profile = user }; ApplicationContext.SetPrincipal(principal); return(principal); }
/// <summary> /// The core authentication logic. /// </summary> /// <returns>The ticket data provided by the authentication logic.</returns> protected async override System.Threading.Tasks.Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = UnpackStateParameter(Request.Query); if (properties != null) { var logonUserIdentity = Options.Provider.GetLogonUserIdentity(Context); if (!logonUserIdentity.AuthenticationType.Equals((Options.CookieOptions?.AuthenticationType ?? "")) && logonUserIdentity.IsAuthenticated) { AddCookieBackIfExists(); ClaimsIdentity claimsIdentity = new ClaimsIdentity(logonUserIdentity.Claims, Options.SignInAsAuthenticationType); //name identifier // Microsoft.Owin.Security.AuthenticationManagerExtensions: ExternalLoginInfo GetExternalLoginInfo(AuthenticateResult result) claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, logonUserIdentity.User.Value, null, Options.AuthenticationType)); // Import custom claims. List <Claim> customClaims = Options.Provider.ImportClaims(logonUserIdentity); claimsIdentity.AddClaims(customClaims .Where(c => c.Type != ClaimTypes.NameIdentifier) .Select(c => new Claim(c.Type, c.Value, c.ValueType, Options.AuthenticationType))); var ticket = new AuthenticationTicket(claimsIdentity, properties); var context = new MixedAuthAuthenticatedContext( Context, claimsIdentity, properties, Options.AccessTokenFormat.Protect(ticket)); await Options.Provider.Authenticated(context); return(ticket); } } return(new AuthenticationTicket(null, properties)); }
public string GenerateEncodedToken(string userName, ClaimsIdentity identity) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userName), new Claim(JwtRegisteredClaimNames.Jti, _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Rol), identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Id) }; identity.AddClaims(claims); //// Create the JWT security token and encode it. //var jwt = new JwtSecurityToken( // issuer: _jwtOptions.Issuer, // audience: _jwtOptions.Audience, // claims: claims, // notBefore: _jwtOptions.NotBefore, // expires: _jwtOptions.Expiration, // signingCredentials: _jwtOptions.SigningCredentials); //var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = _jwtOptions.Issuer, Audience = _jwtOptions.Audience, NotBefore = _jwtOptions.NotBefore, SigningCredentials = _jwtOptions.SigningCredentials, Subject = identity, Expires = _jwtOptions.Expiration, }); var encodedJwt = handler.WriteToken(securityToken); return(encodedJwt); }
public async Task <IActionResult> Login(LoginModel model) { // Due to MVC model binding, model will never be null here if (!this.ModelState.IsValid) { this.SetHelpText(model); return(this.View(model)); } // Validate password bool isValid = this._authenticationProvider.IsValidPassphrase(model?.Passphrase); if (!isValid) { this.SetHelpText(model); this.ModelState.AddModelError(nameof(model.Passphrase), "Invalid passphrase. Please try again."); return(this.View(model)); } // Create log-in ClaimsIdentity userIdentity = new ClaimsIdentity(KnownAuthenticationScheme.PassphraseScheme); userIdentity.AddClaims(new[] { new Claim(ClaimTypes.Name, KnownPolicies.Upload, ClaimValueTypes.String, "https://ifs") }); ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity); AuthenticationProperties authenticationOptions = new AuthenticationProperties { AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30), IsPersistent = false }; await this.HttpContext.SignInAsync(KnownAuthenticationScheme.PassphraseScheme, userPrincipal, authenticationOptions); string returnUrl = String.IsNullOrEmpty(model?.ReturnUrl) ? this.Url.Action("Index", "Upload") : model.ReturnUrl; return(this.Redirect(returnUrl)); }
public ClaimsIdentity Build(string authenticationType, string userAccountName, AccountType accountType) { if (string.IsNullOrWhiteSpace(authenticationType)) { throw new ArgumentException("Authentication type cannot be null or empty.", nameof(authenticationType)); } if (string.IsNullOrWhiteSpace(userAccountName)) { throw new ArgumentException("User account name cannot be null or empty.", nameof(userAccountName)); } IUser user = userService.GetUser(userAccountName, accountType); if (user == null) { throw new AuthenticationException($"Invalid user '{userAccountName}'."); } if (user.IsDisabled) { throw new AuthenticationException($"User '{userAccountName}' is disabled."); } var claimsBuilder = new ClaimsBuilder(); claimsBuilder .SetId(user.Id) .SetName(user.Name) .SetAccountName(userAccountName); SetUserCustomPropertyClaims(user, claimsBuilder); SetUserOrganizationClaims(user, claimsBuilder); SetUserGroupClaims(user, claimsBuilder); SetUserRoleAndPermissionClaims(user, claimsBuilder); var identity = new ClaimsIdentity(authenticationType); identity.AddClaims(claimsBuilder.GetClaims()); return(identity); }
private async Task <IActionResult> ProcessWindowsLoginAsync(string returnUrl) { var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName); if (result?.Principal is WindowsPrincipal wp) { var props = new AuthenticationProperties() { RedirectUri = Url.Action("Callback"), 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)); 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( IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme, new ClaimsPrincipal(id), props); return(Redirect(props.RedirectUri)); } else { return(Challenge(AccountOptions.WindowsAuthenticationSchemeName)); } }
private async Task <string> GerarJwt(Usuario usuario) { // perfis var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, usuario.Id.ToString()), new Claim(ClaimTypes.Name, usuario.UserName), new Claim(ClaimTypes.GivenName, usuario.NomeCompleto), new Claim(ClaimTypes.Email, usuario.Email) }; var roles = await _userManager.GetRolesAsync(usuario); foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(claims); // token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.PalavraChave); var token = tokenHandler.CreateToken(new SecurityTokenDescriptor { Issuer = _appSettings.Emissor, Audience = _appSettings.ValidoEm, Subject = identityClaims, Expires = DateTime.UtcNow.AddHours(_appSettings.ExperacaoHoras), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }); var encodedToken = tokenHandler.WriteToken(token); // transformar token compativel com web return(encodedToken); }
public IResult Handle(LoginQuery query) { if (string.IsNullOrEmpty(query.User) || string.IsNullOrEmpty(query.Password)) AddNotification("User or Password", "User ou password está vazio"); if (Invalid) { return new ApiContract(false, "Erro, corrija os seguintes problemas:", Notifications); } var claims = new List<Claim>(); claims.Add(new Claim(JwtRegisteredClaimNames.Sub, query.User)); var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(claims); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = identityClaims, Issuer = _jwtSettings.Issuer, Audience = _jwtSettings.ValidAt, Expires = DateTime.UtcNow.AddHours(_jwtSettings.Expiration), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var data = new { authenticated = true, created = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"), expiration = tokenDescriptor.Expires.Value.ToString("yyyy-MM-dd HH:mm:ss"), accessToken = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)) }; return new ApiContract(true, "Token gerado com sucesso", data); }
public string GenerateJWT(LoginResponseModel user) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Email), new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(ClaimTypes.DateOfBirth, user.DateOfBirth.Value.ToShortDateString()), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), }; foreach (var role in user.Roles) { claims.Add(new Claim(ClaimTypes.Role, role.Name.ToString())); } var identityClaims = new ClaimsIdentity(); identityClaims.AddClaims(claims); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["TokenSettings:PrivateKey"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var expires = DateTime.UtcNow.AddHours(_config.GetValue <double>("TokenSettings:ExpirationHours")); var tokenHandler = new JwtSecurityTokenHandler(); var tokenObject = new SecurityTokenDescriptor { Subject = identityClaims, Expires = expires, SigningCredentials = credentials, Issuer = _config["TokenSettings:Issuer"], Audience = _config["TokenSettings:Audience"] }; var encodedJwt = tokenHandler.CreateToken(tokenObject); return(tokenHandler.WriteToken(encodedJwt)); }
[ValidateAntiForgeryToken]//该属性与视图中的Html.AntiForgeryToken辅助器方法联合工作,防止Cross-Site Request Forgery(CSRF,跨网站请求伪造) public async Task <ActionResult> Login(LoginModel deteils, string returnUrl) { //模型验证通过 if (ModelState.IsValid) { //根据用户名与密码获取操作对象 AppUser user = await UserManager.FindAsync(deteils.Name, deteils.Password); //对象为空 if (user == null) { ModelState.AddModelError("", "Invalid name or password."); } //对象存在 else { //创建Cookie,浏览器会在后继的请求中发送这个Cookie,表明他们是已认证的 //创建一个标识该用户的ClaimsIdentity对象,该实例是调用用户管理器的CreateIdentityAsync方法创建的 //传递一个用户对象和DefaultAuthenticationTypes枚举中的一个值 ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); //签出用户,这通常意味着使标识已认证用户的Cookie失效 AuthManager.SignOut(); //签入用户,这意味着要创建用来标识已认证请求的Cookie AuthManager.SignIn( new AuthenticationProperties //该类用来配置认证过程以及ClaimsIdentity对象 { IsPersistent = false //使认证Cookie在浏览器中是持久化的,意即用户在开始新会话时不必再次认证 }, ident ); return(Redirect(returnUrl)); } } ViewBag.returnUrl = returnUrl; return(View(deteils)); }
public static string Create(string userId, string username, string firstName, string lastName = "", string email = "N/A", string role = "", string langCode = "en-US", string tenantId = "") { var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.GivenName, firstName), new Claim(ClaimTypes.Surname, lastName), new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Locality, langCode), new Claim(type: "TenantIdentifier", value: tenantId) }; var identity = new ClaimsIdentity(); identity.AddClaims(claims); var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes("TRIDESETRIKeyWHICHneedsToBEthiSLong")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(identity), #if (DEBUG) Expires = DateTime.Now.AddYears(1), #else Expires = DateTime.Now.AddDays(1), #endif SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }