protected virtual ClaimsPrincipal InvokeHandler(SecurityTokenHandlerCollection handlers, string tokenString) { SecurityTokenHandler handler = null; if (handlers.Count == 1) { handler = handlers.First(); } else { foreach (var h in handlers) { if (((IHttpSecurityTokenHandler)h).CanReadToken(tokenString)) { handler = h; break; } } } if (handler != null) { var token = ((IHttpSecurityTokenHandler)handler).ReadToken(tokenString); var principal = new ClaimsPrincipal(handler.ValidateToken(token)); return(principal); } throw new InvalidOperationException("No handler found"); }
public OpenIdConnectClientTests() { defaultSettings = Options.Create(new OpenIDConnectSettings { RedirectUrl = DefaultSignInRedirectUrl, SignOutRedirectUrl = DefaultSignOutRedirectUrl, Issuer = "issuer", AuthdUrl = "auth", AuthorizeUrl = "AuthorizeUrl", ClientId = "clientid", EndSessionUrl = "Endsesison", JWK = "jjjjjjfhfjjfjfjfjfhfjkhdfkhdfkjhskfhsldkjhfskdljfhsdlkfhsdflksdhsdlkfh", Exponent = "AQAB", }); tokenHandler = A.Fake <SecurityTokenHandler>(); configurationManager = A.Fake <IConfigurationManager <OpenIdConnectConfiguration> >(); A.CallTo(() => configurationManager.GetConfigurationAsync(CancellationToken.None)).Returns( new OpenIdConnectConfiguration { AuthorizationEndpoint = "auth", EndSessionEndpoint = "end", Issuer = "issuer", }); }
public JwtTokenService(SecurityTokenHandler tokenHandler, SecurityTokenDescriptor tokenDescriptor, IOptions <AppSettingsOptions> appSettings, IOptions <JwtConfigOptions> jwtConfig) { _tokenHandler = tokenHandler; _tokenDescriptor = tokenDescriptor; _appSettings = appSettings.Value; _jwtConfig = jwtConfig.Value; }
public JwtTokenServiceTests() { // This token is from jwt.io, the format: // token = base64urlEncoding(header) + '.' + base64urlEncoding(payload) + '.' + base64urlEncoding(signature) string exampleJwtToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; var securityToken = new JwtSecurityToken(exampleJwtToken); _tokenHandler = Substitute.For <SecurityTokenHandler>(); _tokenHandler .CreateToken(Arg.Any <SecurityTokenDescriptor>()) .Returns(securityToken); _tokenHandler .WriteToken(securityToken) .Returns("the jwt token"); _jwtSettings = new JwtSettings() { Password = "******", ExpiresDays = 10 }; _refreshTokenRepository = Substitute.For <IUserRefreshTokenRepository>(); _service = new JwtTokenService(_jwtSettings, _tokenHandler, _refreshTokenRepository); }
public static Player GenerateUIDForPlayerLogin(string param) { try { Player player = ObjectWrapper.DeserializeRequest <Player>(param); lock (LobbyServerObjects.RequestedLoginPlayers) { Player previousRequestedPlayer = LobbyServerObjects.RequestedLoginPlayers.Find((x) => x.ID == player.ID); if (previousRequestedPlayer == null) { //If there is no player registered on the login server, register a new one with a new security token LobbyServerObjects.RequestedLoginPlayers.Add(player); previousRequestedPlayer = player; } //If there is already a player but somehow he couldn't get in, re-roll another token for him previousRequestedPlayer.SecurityToken = SecurityTokenHandler.GenerateSecurityToken(); Console.WriteLine($"- Security Token Created for {previousRequestedPlayer.Nickname} - {previousRequestedPlayer.SecurityToken.Token} - {previousRequestedPlayer.SecurityToken.DateTime.TimeOfDay.ToString().Split('.')[0]} - {previousRequestedPlayer.SecurityToken.UnifiedSecurityToken}"); //Timebomb thread to remove the player on the list after 2 minutes in order to optimize the searches new Thread(() => DeleteRequestedLoginPlayer(previousRequestedPlayer)).Start(); return(previousRequestedPlayer); } } catch (Exception ex) { throw ex; } }
public JwtTokenProvider( JwtSettings jwtSettings, SecurityTokenHandler tokenHandler) { _jwtSettings = jwtSettings; _tokenHandler = tokenHandler; }
public AuthControllerTests() { authClient = A.Fake <IOpenIdConnectClient>(); log = A.Fake <ILogger <AuthController> >(); defaultVersionedFiles = A.Fake <IVersionedFiles>(); defaultConfiguration = A.Fake <IConfiguration>(); var requestServices = A.Fake <IServiceProvider>(); defaultAuthService = A.Fake <IAuthenticationService>(); session = new MockHttpSession(); baseUrlService = A.Fake <IBaseUrlService>(); defaultUrlHelper = A.Fake <IUrlHelper>(); A.CallTo(() => defaultAuthService.SignInAsync(A <HttpContext> .Ignored, A <string> .Ignored, A <ClaimsPrincipal> .Ignored, A <AuthenticationProperties> .Ignored)).Returns(Task.CompletedTask); A.CallTo(() => requestServices.GetService(typeof(IAuthenticationService))).Returns(defaultAuthService); A.CallTo(() => baseUrlService.GetBaseUrl(A <HttpRequest> .Ignored, A <IUrlHelper> .Ignored)) .Returns(baseAddress); defaultContext = new DefaultHttpContext { RequestServices = requestServices, Session = session, Request = { Headers = { new KeyValuePair <string, StringValues>("Referer", refererUrl) } }, }; defaultsettings = Options.Create(new AuthSettings { Audience = "audience", ClientSecret = "clientSecret123456", Issuer = "issuer", DefaultRedirectUrl = "test", AuthDssEndpoint = "test/{url}", }); defaultSettings = Options.Create(new OpenIDConnectSettings { RedirectUrl = "test/", SignOutRedirectUrl = "test/", Issuer = "issuer", AuthdUrl = "auth", AuthorizeUrl = "AuthorizeUrl", ClientId = "clientid", EndSessionUrl = "Endsesison", JWK = "jjjjjjfhfjjfjfjfjfhfjkhdfkhdfkjhskfhsldkjhfskdljfhsdlkfhsdflksdhsdlkfh", Exponent = "AQAB", }); tokenHandler = A.Fake <SecurityTokenHandler>(); configurationManager = A.Fake <IConfigurationManager <OpenIdConnectConfiguration> >(); A.CallTo(() => configurationManager.GetConfigurationAsync(CancellationToken.None)).Returns( new OpenIdConnectConfiguration { AuthorizationEndpoint = "auth", EndSessionEndpoint = "end", Issuer = "issuer", }); _urlHelper = A.Fake <IUrlHelper>(); }
public Account Authenticate(string username, string password) { Account account = new Account(); SecurityToken token = null; SecurityTokenHandler tokenHandler = null; byte[] key = null; SecurityTokenDescriptor tokenDescriptor = null; account = _topContext.Accounts.FirstOrDefault(x => x.Username == username); if (account == null || VerifyHash(password, Convert.FromBase64String(account.Salt), Convert.FromBase64String(account.Password)) == false) { return(null); } tokenHandler = new JwtSecurityTokenHandler(); key = Encoding.ASCII.GetBytes(_appSettings.Secret); tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, account.Id.ToString()), new Claim(ClaimTypes.Role, account.Role) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; token = tokenHandler.CreateToken(tokenDescriptor); account.Token = tokenHandler.WriteToken(token); return(account.WithoutPassword()); }
protected virtual ClaimsPrincipal InvokeHandler(SecurityTokenHandlerCollection handlers, string tokenString) { SecurityTokenHandler handler = null; if (handlers.Count == 1) { handler = handlers.First(); } else { foreach (var h in handlers) { if (h.CanReadToken(tokenString)) { handler = h; break; } } } if (handler != null) { Tracing.Information("Invoking token handler: " + handler.GetType().FullName); var token = handler.ReadToken(tokenString); var principal = new ClaimsPrincipal(handler.ValidateToken(token)); return(principal); } throw new InvalidOperationException("No handler found"); }
private ValueTask <bool> CanReadTokenAsync(SecurityTokenHandler handler, XmlReader reader) { if (handler is IAsyncSecurityTokenHandler asyncHandler) { return(asyncHandler.CanReadTokenAsync(reader)); } return(new ValueTask <bool>(handler.CanReadToken(reader))); }
public CookiesManager(IHttpContextAccessor httpContextAccessor, SecurityTokenHandler securityTokenHandler, AuthenticationConfiguration authenticationConfiguration) { this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); this.securityTokenHandler = securityTokenHandler ?? throw new ArgumentNullException(nameof(securityTokenHandler)); this.authenticationConfiguration = authenticationConfiguration ?? throw new ArgumentNullException(nameof(authenticationConfiguration)); }
protected virtual XmlElement GetTokenElement(SecurityToken token, SecurityTokenHandler handler) { var document = new XmlDocument(); using (var writer = document.CreateNavigator().AppendChild()) handler.WriteToken(writer, token); return(document.FirstChild as XmlElement); }
/// <summary> /// Gets an appropriate SecurityTokenHandler for issuing a security token. /// </summary> /// <param name="requestedTokenType">The requested TokenType.</param> /// <returns>The SecurityTokenHandler to be used for creating the issued security token.</returns> protected virtual SecurityTokenHandler GetSecurityTokenHandler(string requestedTokenType) { string tokenType = string.IsNullOrEmpty(requestedTokenType) ? _securityTokenServiceConfiguration.DefaultTokenType : requestedTokenType; SecurityTokenHandler securityTokenHandler = _securityTokenServiceConfiguration.SecurityTokenHandlers[tokenType]; return(securityTokenHandler); }
public JwtTokenService( JwtSettings jwtSettings, SecurityTokenHandler tokenHandler, IUserRefreshTokenRepository refreshTokenRepository) { _jwtSettings = jwtSettings; _tokenHandler = tokenHandler; _refreshTokenRepository = refreshTokenRepository; }
public VideoWebTokenHandler( IOptions <ServicesConfiguration> _servicesConfiguration, IMemoryCache _memoryCache ) { Secret = _servicesConfiguration.Value.InternalEventSecret; this.memoryCache = _memoryCache; tokenHandler = new JwtSecurityTokenHandler(); }
public static string BuildWaSignInMessage(SecurityToken securityToken, SecurityTokenHandler tokenHandler, string tokenType) { using (var memoryStream = new MemoryStream()) { using (var writer = XmlDictionaryWriter.CreateTextWriter(memoryStream, Encoding.UTF8, false)) { // <RequestSecurityTokenResponse> writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestSecurityTokenResponse, WsTrustConstants_1_3.Namespace); // <Lifetime> writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.Lifetime, WsTrustConstants.Namespaces.WsTrust1_3); writer.WriteElementString(WsUtility.PreferredPrefix, WsUtility.Elements.Created, WsUtility.Namespace, Default.IssueInstantString); writer.WriteElementString(WsUtility.PreferredPrefix, WsUtility.Elements.Expires, WsUtility.Namespace, Default.ExpiresString); // </Lifetime> writer.WriteEndElement(); // <AppliesTo> writer.WriteStartElement(WsPolicy.PreferredPrefix, WsPolicy.Elements.AppliesTo, WsPolicy.Namespace); // <EndpointReference> writer.WriteStartElement(WsAddressing.PreferredPrefix, WsAddressing.Elements.EndpointReference, WsAddressing.Namespace); writer.WriteElementString(WsAddressing.PreferredPrefix, WsAddressing.Elements.Address, WsAddressing.Namespace, Default.Audience); // </EndpointReference> writer.WriteEndElement(); // </AppliesTo> writer.WriteEndElement(); // <RequestedSecurityToken>token</RequestedSecurityToken> writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestedSecurityToken, WsTrustConstants_1_3.Namespace); tokenHandler.WriteToken(writer, securityToken); writer.WriteEndElement(); // <TokenType>tokenType</TokenType> writer.WriteElementString(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.TokenType, WsTrustConstants_1_3.Namespace, tokenType); //<RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</RequestType> writer.WriteElementString(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestType, WsTrustConstants_1_3.Namespace, WsTrustConstants_1_3.Actions.Issue); //<KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</KeyType> writer.WriteElementString(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.KeyType, WsTrustConstants_1_3.Namespace, "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey"); // </RequestSecurityTokenResponse> writer.WriteEndElement(); writer.Flush(); var rstr = Encoding.UTF8.GetString(memoryStream.ToArray()); return("wa=wsignin1.0&wresult=" + Uri.EscapeDataString(rstr)); } } }
public ApplicationSignInManager(UserManager <ApplicationUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory <ApplicationUser> claimsFactory, IOptions <IdentityOptions> optionsAccessor, ILogger <SignInManager <ApplicationUser> > logger, Microsoft.AspNetCore.Authentication.IAuthenticationSchemeProvider schemes) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes) { _securityTokenHandler = new JwtSecurityTokenHandler(); }
private static SamlSecurityTokenHandler GetSamlHandler() { SecurityTokenHandler handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[typeof(SamlSecurityToken)]; if (handler == null) { throw new Exception("No handler found for token type: SamlSecurityToken"); } return(handler as SamlSecurityTokenHandler); }
public void AddClientCertificate(SecurityTokenHandler handler) { AddMapping(new AuthenticationOptionMapping { TokenHandler = new SecurityTokenHandlerCollection { handler }, Options = AuthenticationOptions.ForClientCertificate() }); }
public JwtTokenService( JwtSettings jwtSettings, SecurityTokenHandler tokenHandler, IUserRefreshTokenRepository refreshTokenRepository, TokenValidationParameters tokenValidationParameters) { _jwtSettings = jwtSettings; _tokenHandler = tokenHandler; _refreshTokenRepository = refreshTokenRepository; _tokenValidationParameters = tokenValidationParameters; }
public AuthenticateController(IOptions <JWTSettings> jwtOptions, SignInManager <IdentityUser> signInManager, UserManager <IdentityUser> userManager, IOptions <Settings> options) { _signInManager = signInManager; _userManager = userManager; _securityTokenHandler = new JwtSecurityTokenHandler(); _jwtOptions = jwtOptions.Value; _settings = options.Value; }
public UserController( IUserRepository userRepository, IMapper mapper, IOptions <AppSettings> appSettings, SecurityTokenHandler tokenHandler) { _userRepository = userRepository; _mapper = mapper; _appSettings = appSettings.Value; _tokenHandler = tokenHandler; }
protected virtual SecurityTokenHandler GetSecurityTokenHandler() { var authPlugin = PluginManager.GetSingleton <SamlOAuthClient>(); //var config = System.IdentityModel.Services.Configuration..FederationConfiguration..; SecurityTokenHandler handler = null; var securityRequirements = new SamlSecurityTokenRequirement(); var securityTokenHandlerConfig = new SecurityTokenHandlerConfiguration(); switch (authPlugin.IdpBindingType) { case SamlBinding.SAML11_POST: handler = new SamlSecurityTokenHandler(securityRequirements) { Configuration = securityTokenHandlerConfig }; break; case SamlBinding.SAML20_POST: handler = new SubjectConfirmationDataSaml2SecurityTokenHandler(securityRequirements, authPlugin.SubjectRecipientValidationMode) { Configuration = securityTokenHandlerConfig }; break; } if (handler == null) { throw new InvalidOperationException( string.Format("No suitable token handler was loaded for the SAML binding type : {0}", tokenProcessorConfiguration.IdpBindingType)); } handler.Configuration.IssuerNameRegistry = new CodeBasedIssuerNameRegistry(tokenProcessorConfiguration.TrustedIssuerThumbprint.Split(',')); handler.Configuration.CertificateValidationMode = tokenProcessorConfiguration.CertificateValidationMode; if (typeof(SamlSecurityTokenHandler).IsAssignableFrom(handler.GetType())) { ((SamlSecurityTokenHandler)handler).CertificateValidator = GetCertificateValidator(handler.Configuration.CertificateValidationMode); } if (typeof(Saml2SecurityTokenHandler).IsAssignableFrom(handler.GetType())) { ((Saml2SecurityTokenHandler)handler).CertificateValidator = GetCertificateValidator(handler.Configuration.CertificateValidationMode); } handler.Configuration.AudienceRestriction.AudienceMode = System.IdentityModel.Selectors.AudienceUriMode.Never; return(handler); }
public AzureB2CAuthClient(IOptions <OpenIDConnectSettings> settings, SecurityTokenHandler securityTokenHandler, IConfigurationManager <OpenIdConnectConfiguration> configurationManager) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } this.settings = settings.Value; this.configurationManager = configurationManager; tokenHandler = securityTokenHandler; }
private SecurityToken CreateToken(SecurityTokenHandler handler, ClaimsIdentity identity, SigningCredentials signingCredentials = null, EncryptingCredentials encryptingCredentials = null) { var token = handler.CreateToken(new SecurityTokenDescriptor { TokenIssuerName = "Dmitrii Chernov", Subject = identity, SigningCredentials = signingCredentials, EncryptingCredentials = encryptingCredentials }); return token; }
public static void DeleteRequestedLoginPlayer(Player Player) { Thread.Sleep(1000 * 60 * NetworkObjectParameters.SecurityTokenExpirationInMinutes); if (!SecurityTokenHandler.IsTokenDateValid(Player.SecurityToken)) { lock (LobbyServerObjects.RequestedLoginPlayers) { LobbyServerObjects.RequestedLoginPlayers.Remove(Player); } } }
/// <summary> /// Copy constructor. /// </summary> /// <param name="federatedAsyncState">The input FederatedAsyncState instance.</param> /// <exception cref="ArgumentNullException">The input 'FederatedAsyncState' is null.</exception> public FederatedAsyncState(FederatedAsyncState federatedAsyncState) { if (null == federatedAsyncState) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("FederatedAsyncState"); } _request = federatedAsyncState.Request; _claimsPrincipal = federatedAsyncState.ClaimsPrincipal; _securityTokenHandler = federatedAsyncState.SecurityTokenHandler; _result = federatedAsyncState.Result; }
public BootstrapContext(SecurityToken token, SecurityTokenHandler tokenHandler) { if (token == null) { throw new ArgumentNullException("token"); } if (tokenHandler == null) { throw new ArgumentNullException("tokenHandler"); } this._token = token; this._tokenHandler = tokenHandler; }
/// <summary> /// Creates a security token for the specified claims identity using the given token handler, /// and returns it serialized as a string. /// </summary> /// <param name="identity">Claims identity to create a security token from.</param> /// <param name="tokenHandler">Specific security token handler to use.</param> /// <returns>A string with the serialized security token.</returns> protected string GetSecurityToken(ClaimsIdentity identity, SecurityTokenHandler tokenHandler) { var tokenDescriptor = new SecurityTokenDescriptor { Subject = identity, NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddMinutes(config.ExpiresMin), SigningCredentials = config.SigningCredentials }; var authToken = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(authToken)); }
static SecurityToken CreateToken(SecurityTokenHandler tokenHandler) { var tokenDescriptor = new SecurityTokenDescriptor { Expires = DateTime.UtcNow + TimeSpan.FromDays(1), Audience = Default.Audience, SigningCredentials = Default.AsymmetricSigningCredentials, Issuer = Default.Issuer, Subject = Default.SamlClaimsIdentity }; return(tokenHandler.CreateToken(tokenDescriptor)); }
public void AddClientCertificate(SecurityTokenHandler handler) { AddMapping(new AuthenticationOptionMapping { TokenHandler = new SecurityTokenHandlerCollection { handler }, Options = AuthenticationOptions.ForClientCertificate() }); }