public void Initiazlize() { CfCacheIndex.Initialize(); CfPerfCache.Initialize(); var cIdentity = new ClaimsIdentity(new List<Claim>() { new Claim("http://climbfind.com/claims/userid",jsk.ToString()) }); var ids = new ClaimsIdentityCollection(new List<ClaimsIdentity>() { cIdentity }); CfIdentity.Inject(new ClaimsPrincipal(ids)); }
private static void MockUserPrincipal(HttpContextBase httpContext, string userName) { var claimsIdentity = new ClaimsIdentity(AuthenticationTypes.Federation, ClaimTypes.Name, ClaimTypes.Role); claimsIdentity.Claims.Add(new Claim(ClaimTypes.Name, userName)); var claimsPrincipal = new ClaimsPrincipal(new[] { claimsIdentity }); httpContext.User = (IPrincipal)claimsPrincipal; FormsAuthentication.SetAuthCookie(userName, true); }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { if (null == claimSet) return principal.Identity as IClaimsIdentity; ClaimsIdentity identity = new ClaimsIdentity(); identity.Claims.AddRange(claimSet); return identity; }
private ClaimsIdentity CreateClaimsIdentity(UserClaimsData userClaimsData) { var claimsIdentity = new ClaimsIdentity(); // Issue custom claims claimsIdentity.Claims.Add(new Claim(ClaimTypes.Name, userClaimsData.Username)); claimsIdentity.Claims.AddRange(userClaimsData.Claims); return claimsIdentity; }
public override ClaimsIdentityCollection ValidateToken(SecurityToken token) { var userName = ((UserNameSecurityToken)token).UserName; IClaimsIdentity identity = new ClaimsIdentity( new[] { new Claim(ClaimTypes.Name, userName) }, AuthenticationMethods.Password ); if (Configuration.SaveBootstrapTokens) identity.BootstrapToken = RetainPassword ? token : new UserNameSecurityToken(userName, null); return new ClaimsIdentityCollection(new[] { identity }); }
private IClaimsPrincipal CreateClientIdentity(IClaimsIdentity id) { // hard coded for demo purposes var claims = new List<Claim> { new Claim(ClaimTypes.Name, id.Name), new Claim(ClaimTypes.Role, "Users"), new Claim(ClaimTypes.Role, "Geek"), new Claim(ClaimTypes.Email, id.Name + "@thinktecture.com") }; var claimsIdentity = new ClaimsIdentity(claims, "Federation"); return ClaimsPrincipal.CreateFromIdentity(claimsIdentity); }
private static RequestSecurityTokenResponse RequestTokenInMemory(RequestSecurityToken rst) { var signingCert = X509Certificates.GetCertificateFromStore("CN=STS", StoreLocation.LocalMachine); var encryptingCert = X509Certificates.GetCertificateFromStore("CN=Service", StoreLocation.LocalMachine); var config = new InMemoryStsConfiguration(signingCert); var sts = new InMemorySts(config, encryptingCert); var id = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Name, "dominick") }); return sts.Issue(ClaimsPrincipal.CreateFromIdentity(id), rst); }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { if (null == principal) { throw new ArgumentNullException("principal"); } var outputIdentity = new ClaimsIdentity(); var roles = new RolePrincipal(principal.Identity); outputIdentity.Claims.Add(new Claim(ClaimTypes.Name, principal.Identity.Name)); outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, roles.GetRoles().First())); return outputIdentity; }
/// <summary> /// Returns the claims to be issued in the token. /// </summary> /// <param name="principal">The caller's principal.</param> /// <param name="request">The incoming request security token, can be used to obtain addtional information.</param> /// <param name="scope">The scope information corresponding to this request.</param> /// <returns>The outgoing claims identity to be included in the issued token.</returns> protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { // Create the claims identity. var claimsIdentity = new ClaimsIdentity(); // Get the security id for the user. var userProvider = this._container.Resolve<IUserProvider>(); var securityId = userProvider.ReadSecurityIdByLogin(principal.Identity.Name); // Load the claims. var claimsProvider = this._container.Resolve<IClaimsProvider>(); claimsIdentity.Claims.AddRange(claimsProvider.GetClaims(securityId)); // Return the claims to the caller. return claimsIdentity; }
//public static void IssueSessionToken(string uniqueId, UserData data) //{ // var principal = CreateUserPrincipal(uniqueId, data); // var sessionToken = new Microsoft.IdentityModel.Tokens.SessionSecurityToken(principal); // Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); //} private static IClaimsPrincipal CreateUserPrincipal(string uniqueId, UserData data) { var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, uniqueId), }; claims.Add(new Claim(ClaimTypes.Role, data.Registerd ? "Registerd" : "NotRegisterd")); if (!string.IsNullOrEmpty(data.Name)) claims.Add(new Claim(ClaimTypes.Name, data.Name)); if (!string.IsNullOrEmpty(data.Email)) claims.Add(new Claim(ClaimTypes.Email, data.Email)); var id = new ClaimsIdentity(claims); return ClaimsPrincipal.CreateFromIdentity(id); }
public static string GetAuthenticatedUserToken(ClaimsIdentity identity) { var provider = identity.Claims.Where( c => c.ClaimType.Equals( "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider")).Select( c => c.Value).FirstOrDefault(); var nameidentity = identity.Claims.Where( c => c.ClaimType.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")). Select(c => c.Value).FirstOrDefault(); if (provider == null || nameidentity == null) return null; return provider.ToLowerInvariant() + ":" + nameidentity; }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { var outputIdentity = new ClaimsIdentity(); if (null == principal) { throw new InvalidRequestException("The caller's principal is null."); } switch (principal.Identity.Name) { // In a production environment, all the information that will be added // as claims should be read from the authenticated Windows Principal. // The following lines are hardcoded because windows integrated // authentication is disabled. case Tailspin.Users.FullName: outputIdentity.Claims.AddRange(new List<Claim> { new Claim(ClaimTypes.Name, Tailspin.Users.FullName), new Claim(ClaimTypes.GivenName, "Robert"), new Claim(ClaimTypes.Surname, "Roe"), new Claim(ClaimTypes.Role, Tailspin.Roles.TenantAdministrator) }); break; default: if (!principal.Identity.Name.Equals(this.CustomUserName, System.StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidOperationException(string.Format("Cannot get claims for {0} - not authorized", principal.Identity.Name)); } var tenantName = principal.Identity.Name.Split('\\')[0]; outputIdentity.Claims.AddRange(new List<Claim> { new Claim(ClaimTypes.Name, principal.Identity.Name), new Claim(ClaimTypes.GivenName, tenantName + " Jr."), new Claim(ClaimTypes.Surname, "John"), new Claim(ClaimTypes.Role, Tailspin.Roles.SurveyAdministrator), new Claim(Tailspin.ClaimTypes.Tenant, tenantName) }); break; } return outputIdentity; }
internal static string[] GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity, string uniqueClaimTypeIdentifier) { var claims = claimsIdentity.GetClaims(); // The application developer might not want to use our default behavior // and instead might want us to use a claim he knows is unique within // the security realm of his application. (Perhaps he has crafted this // claim himself.) if (!String.IsNullOrEmpty(uniqueClaimTypeIdentifier)) { Claim matchingClaim = claims.SingleOrDefault(claim => String.Equals(uniqueClaimTypeIdentifier, claim.ClaimType, StringComparison.Ordinal)); if (matchingClaim == null || String.IsNullOrEmpty(matchingClaim.Value)) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebPageResources.ClaimUidExtractor_ClaimNotPresent, uniqueClaimTypeIdentifier)); } return new string[] { uniqueClaimTypeIdentifier, matchingClaim.Value }; } // By default, we look for 'nameIdentifier' and 'identityProvider' claims. // For a correctly configured ACS consumer, this tuple will uniquely // identify a user of the application. We assume that a well-behaved // identity provider will never assign the same name identifier to multiple // users within its security realm, and we assume that ACS has been // configured so that each identity provider has a unique 'identityProvider' // claim. Claim nameIdentifierClaim = claims.SingleOrDefault(claim => String.Equals(NameIdentifierClaimType, claim.ClaimType, StringComparison.Ordinal)); Claim identityProviderClaim = claims.SingleOrDefault(claim => String.Equals(IdentityProviderClaimType, claim.ClaimType, StringComparison.Ordinal)); if (nameIdentifierClaim == null || String.IsNullOrEmpty(nameIdentifierClaim.Value) || identityProviderClaim == null || String.IsNullOrEmpty(identityProviderClaim.Value)) { throw new InvalidOperationException(WebPageResources.ClaimUidExtractor_DefaultClaimsNotPresent); } return new string[] { NameIdentifierClaimType, nameIdentifierClaim.Value, IdentityProviderClaimType, identityProviderClaim.Value }; }
/// <summary> /// This method returns the claims to be issued in the token. /// </summary> /// <param name="principal">The caller's principal.</param> /// <param name="request">The incoming RST, can be used to obtain addtional information.</param> /// <param name="scope">The scope information corresponding to this request.</param> /// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception> /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns> protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { if (null == principal) { throw new ArgumentNullException("principal"); } ClaimsIdentity outputIdentity = new ClaimsIdentity(); // Issue custom claims. // TODO: Change the claims below to issue custom claims required by your application. // Update the application's configuration file too to reflect new claims requirement. outputIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name ?? "Demo user")); outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, "Manager")); return outputIdentity; }
public static string CreateSaml2Token(string name) { var id = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }, "SAML"); var descriptor = new SecurityTokenDescriptor { Subject = id, AppliesToAddress = "https://test", TokenIssuerName = "http://issuer", SigningCredentials = GetSamlSigningCredential(), }; var handler = new Saml2SecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); var token = handler.CreateToken(descriptor); return token.ToTokenXmlString(); }
public static string CreateSaml11Token(string name) { var id = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }); var descriptor = new SecurityTokenDescriptor { Subject = id, AppliesToAddress = Constants.Realm, TokenIssuerName = Constants.Issuer, SigningCredentials = GetSamlSigningCredential() }; var handler = new Saml11SecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); var token = handler.CreateToken(descriptor); return token.ToTokenXmlString(); }
/// <summary> /// Validates the token. /// </summary> /// <param name="token">The token.</param> /// <returns>A collection of ClaimsIdentity that represents the identity in the security token.</returns> public override ClaimsIdentityCollection ValidateToken(SecurityToken token) { if (token == null) { throw new ArgumentNullException("token"); } var samlToken = token as SamlSecurityToken; if (samlToken == null) { throw new ArgumentException("token"); } if (samlToken.Assertion == null) { throw new ArgumentException("token"); } var assertion = samlToken.Assertion as Saml11Assertion; this.ValidateConditions(samlToken.Assertion.Conditions, false); // extract claims from token var identity = new ClaimsIdentity("ClientSaml"); ProcessStatement(assertion.Statements, identity, "Client"); // call authentication and filtering logic IClaimsIdentity newIdentity; try { if (ValidateUser(identity, out newIdentity)) { return new ClaimsIdentityCollection(new IClaimsIdentity[] { newIdentity }); } else { throw new SecurityTokenValidationException("Authentication failed"); } } catch (Exception ex) { throw new SecurityTokenValidationException("Security token validation failed", ex); } }
private static void CallService() { var identity = new ClaimsIdentity( new List<Claim> { new Claim(WSIdentityConstants.ClaimTypes.Name, "Bob"), new Claim(_passwordClaimType, "Bob"), new Claim(_customerIdClaimType, "42") }); var token = ClientSaml11SecurityTokenHandlerBase.CreateToken(identity); Console.WriteLine("\nMIXED MODE::::"); CallMixedMode(token); Console.WriteLine("\nMESSAGE MODE::::"); CallMessage(token); }
// sample implementation - do not use for production ;) protected override bool ValidateUser(ClaimsIdentity id, out IClaimsIdentity newIdentity) { newIdentity = null; var usernameClaim = id.Claims.First(c => c.ClaimType == WSIdentityConstants.ClaimTypes.Name); var passwordClaim = id.Claims.First(c => c.ClaimType == _passwordClaimType); var customerIdClaim = id.Claims.First(c => c.ClaimType == _customerIdClaimType); if (usernameClaim.Value == passwordClaim.Value) { newIdentity = new ClaimsIdentity(new Claim[] { usernameClaim, customerIdClaim }, "ClientSaml"); return true; } return false; }
public Microsoft.IdentityModel.Claims.IClaimsIdentity GetOutputClaimsIdentity(Microsoft.IdentityModel.Claims.IClaimsPrincipal principal, Microsoft.IdentityModel.Protocols.WSTrust.RequestSecurityToken request, Microsoft.IdentityModel.SecurityTokenService.Scope scope) { if (principal == null) throw new ArgumentNullException("principal"); string username = principal.Identity.Name; var staffUSI = staffInformationProvider.ResolveStaffUSI(authenticationProvider, username); // Get information necessary to create the app-specific claims var userClaimsInfo = dashboardUserClaimsInformationProvider.GetClaimsInformation(username, staffUSI); // No user information found? if (userClaimsInfo == null) { throw new StaffSchoolClassAssociationException(NoUserInformationErrorMessage) { Name = username, StaffUSI = staffUSI }; } var claims = new List<Claim>(); // Initialize "Name" claims claims.Add(new Claim(EdFiClaimTypes.FullName, userClaimsInfo.FullName)); claims.Add(new Claim(ClaimTypes.GivenName, userClaimsInfo.FirstName)); claims.Add(new Claim(ClaimTypes.Surname, userClaimsInfo.LastName)); claims.Add(new Claim(CustomDashboardClaimType.LocalEducationAgencyCode, this.httpRequestProvider.GetValue("lea"))); if (!string.IsNullOrEmpty(userClaimsInfo.Email)) claims.Add(new Claim(ClaimTypes.Email, userClaimsInfo.Email)); // Add the StaffUSI claim claims.Add(new Claim(EdFiClaimTypes.StaffUSI, staffUSI.ToString())); var claimsIdentity = new ClaimsIdentity(); // Issue custom claims claimsIdentity.Claims.Add(new Claim(ClaimTypes.Name, username)); claimsIdentity.Claims.AddRange(claims); return claimsIdentity; }
/// <summary> /// SendToConversation() API for Skill. /// </summary> /// <remarks> /// This method allows you to send an activity to the end of a conversation. /// /// This is slightly different from ReplyToActivity(). /// * SendToConversation(conversationId) - will append the activity to the end /// of the conversation according to the timestamp or semantics of the channel. /// * ReplyToActivity(conversationId,ActivityId) - adds the activity as a reply /// to another activity, if the channel supports it. If the channel does not /// support nested replies, ReplyToActivity falls back to SendToConversation. /// /// Use ReplyToActivity when replying to a specific activity in the /// conversation. /// /// Use SendToConversation in all other cases. /// </remarks> /// <param name="claimsIdentity">claimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.</param> /// <param name='conversationId'>conversationId.</param> /// <param name='activity'>Activity to send.</param> /// <param name='cancellationToken'>The cancellation token.</param> /// <returns>task for a resource response.</returns> protected override async Task <ResourceResponse> OnSendToConversationAsync(ClaimsIdentity claimsIdentity, string conversationId, Activity activity, CancellationToken cancellationToken = default) { return(await ProcessActivityAsync(claimsIdentity, conversationId, null, activity, cancellationToken).ConfigureAwait(false)); }
public AuthorizationModule() { Get["/connect/authorize", runAsync : true] = async(parameters, cancellationToken) => { this.CreateNewCsrfToken(); this.RequiresMSOwinAuthentication(); // Note: when a fatal error occurs during the request processing, an OpenID Connect response // is prematurely forged and added to the ASP.NET context by OpenIdConnectServerHandler. // You can safely remove this part and let ASOS automatically handle the unrecoverable errors // by switching ApplicationCanDisplayErrors to false in Startup.cs. var response = OwinContext.GetOpenIdConnectResponse(); if (response != null) { return(View["Error.cshtml", response]); } // Extract the authorization request from the OWIN environment. var request = OwinContext.GetOpenIdConnectRequest(); if (request == null) { return(View["Error.cshtml", new OpenIdConnectMessage { Error = "invalid_request", ErrorDescription = "An internal error has occurred" }]); } // Note: ASOS automatically ensures that an application corresponds to the client_id specified // in the authorization request by calling IOpenIdConnectServerProvider.ValidateAuthorizationRequest. // In theory, this null check shouldn't be needed, but a race condition could occur if you // manually removed the application details from the database after the initial check made by ASOS. var application = await GetApplicationAsync(request.ClientId, cancellationToken); if (application == null) { return(View["Error.cshtml", new OpenIdConnectMessage { Error = "invalid_client", ErrorDescription = "Details concerning the calling client application cannot be found in the database" }]); } // Note: in a real world application, you'd probably // prefer creating a specific view model. return(View["Authorize.cshtml", new { Application = application, Request = request }]); }; Post["/connect/authorize/accept", runAsync : true] = async(parameters, cancellationToken) => { this.RequiresMSOwinAuthentication(); this.ValidateCsrfToken(); var response = OwinContext.GetOpenIdConnectResponse(); if (response != null) { return(View["Error.cshtml", response]); } var request = OwinContext.GetOpenIdConnectRequest(); if (request == null) { return(View["Error.cshtml", new OpenIdConnectMessage { Error = "invalid_request", ErrorDescription = "An internal error has occurred" }]); } // Create a new ClaimsIdentity containing the claims that // will be used to create an id_token, a token or a code. var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationType); foreach (var claim in OwinContext.Authentication.User.Claims) { // Allow ClaimTypes.Name to be added in the id_token. // ClaimTypes.NameIdentifier is automatically added, even if its // destination is not defined or doesn't include "id_token". // The other claims won't be visible for the client application. if (claim.Type == ClaimTypes.Name) { claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); } identity.AddClaim(claim); } var application = await GetApplicationAsync(request.ClientId, CancellationToken.None); if (application == null) { return(View["Error.cshtml", new OpenIdConnectMessage { Error = "invalid_client", ErrorDescription = "Details concerning the calling client application cannot be found in the database" }]); } // Create a new ClaimsIdentity containing the claims associated with the application. // Note: setting identity.Actor is not mandatory but can be useful to access // the whole delegation chain from the resource server (see ResourceModule.cs). identity.Actor = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationType); identity.Actor.AddClaim(ClaimTypes.NameIdentifier, application.ApplicationID); identity.Actor.AddClaim(ClaimTypes.Name, application.DisplayName, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); // Create a new authentication ticket holding the user identity. var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); // Set the list of scopes granted to the client application. // Note: this sample always grants the "openid", "email" and "profile" scopes // when they are requested by the client application: a real world application // would probably display a form allowing to select the scopes to grant. ticket.SetScopes(new[] { /* openid: */ OpenIdConnectConstants.Scopes.OpenId, /* email: */ OpenIdConnectConstants.Scopes.Email, /* profile: */ OpenIdConnectConstants.Scopes.Profile, /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess }.Intersect(request.GetScopes())); // Set the resources servers the access token should be issued for. ticket.SetResources("resource_server"); // This call will ask ASOS to serialize the specified identity to build appropriate tokens. // Note: you should always make sure the identities you return contain ClaimTypes.NameIdentifier claim. // In this sample, the identity always contains the name identifier returned by the external provider. OwinContext.Authentication.SignIn(ticket.Properties, ticket.Identity); return(HttpStatusCode.OK); }; Post["/connect/authorize/deny"] = parameters => { this.RequiresMSOwinAuthentication(); this.ValidateCsrfToken(); var response = OwinContext.GetOpenIdConnectResponse(); if (response != null) { return(View["Error.cshtml", response]); } // Extract the authorization request from the cache, the query string or the request form. var request = OwinContext.GetOpenIdConnectRequest(); if (request == null) { return(View["Error.cshtml", new OpenIdConnectMessage { Error = "invalid_request", ErrorDescription = "An internal error has occurred" }]); } // Notify ASOS that the authorization grant has been denied by the resource owner. // Note: OpenIdConnectServerHandler will automatically take care of redirecting // the user agent to the client application using the appropriate response_mode. OwinContext.Authentication.Forbid(OpenIdConnectServerDefaults.AuthenticationType); return(HttpStatusCode.Forbidden); }; Get["/connect/logout", runAsync : true] = async(parameters, cancellationToken) => { var response = OwinContext.GetOpenIdConnectResponse(); if (response != null) { return(View["Error.cshtml", response]); } // When invoked, the logout endpoint might receive an unauthenticated request if the server cookie has expired. // When the client application sends an id_token_hint parameter, the corresponding identity can be retrieved // using AuthenticateAsync or using User when the authorization server is declared as AuthenticationMode.Active. var identity = await OwinContext.Authentication.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationType); // Extract the logout request from the OWIN environment. var request = OwinContext.GetOpenIdConnectRequest(); if (request == null) { return(View["Error.cshtml", new OpenIdConnectMessage { Error = "invalid_request", ErrorDescription = "An internal error has occurred" }]); } return(View["Logout.cshtml", Tuple.Create(request, identity)]); }; Post["/connect/logout"] = parameters => { this.ValidateCsrfToken(); var response = OwinContext.GetOpenIdConnectResponse(); if (response != null) { return(View["Error.cshtml", response]); } // Ask the cookies middleware to delete the local cookie created // when the user agent is redirected from the external identity provider // after a successful authentication flow (e.g Google or Facebook) and // redirect the user agent to the post_logout_redirect_uri specified by the client application. OwinContext.Authentication.SignOut("ServerCookie", OpenIdConnectServerDefaults.AuthenticationType); return(HttpStatusCode.OK); }; }
private AuthorizationFilterContext GetAuthorizationContext( bool anonymous = false, Action <IServiceCollection> registerServices = null) { var basicPrincipal = new ClaimsPrincipal( new ClaimsIdentity( new Claim[] { new Claim("Permission", "CanViewPage"), new Claim(ClaimTypes.Role, "Administrator"), new Claim(ClaimTypes.Role, "User"), new Claim(ClaimTypes.NameIdentifier, "John") }, "Basic")); var validUser = basicPrincipal; var bearerIdentity = new ClaimsIdentity( new Claim[] { new Claim("Permission", "CupBearer"), new Claim(ClaimTypes.Role, "Token"), new Claim(ClaimTypes.NameIdentifier, "John Bear") }, "Bearer"); var bearerPrincipal = new ClaimsPrincipal(bearerIdentity); validUser.AddIdentity(bearerIdentity); // ServiceProvider var serviceCollection = new ServiceCollection(); var auth = new Mock <IAuthenticationService>(); serviceCollection.AddOptions(); serviceCollection.AddLogging(); serviceCollection.AddSingleton(auth.Object); serviceCollection.AddAuthorization(); registerServices?.Invoke(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); // HttpContext var httpContext = new Mock <HttpContext>(); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Bearer")).ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(bearerPrincipal, "Bearer"))); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Basic")).ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(basicPrincipal, "Basic"))); auth.Setup(c => c.AuthenticateAsync(httpContext.Object, "Fails")).ReturnsAsync(AuthenticateResult.Fail("Fails")); httpContext.SetupProperty(c => c.User); if (!anonymous) { httpContext.Object.User = validUser; } httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider); var contextItems = new Dictionary <object, object>(); httpContext.SetupGet(c => c.Items).Returns(contextItems); httpContext.SetupGet(c => c.Features).Returns(Mock.Of <IFeatureCollection>()); // AuthorizationFilterContext var actionContext = new ActionContext( httpContext: httpContext.Object, routeData: new RouteData(), actionDescriptor: new ActionDescriptor()); var authorizationContext = new AuthorizationFilterContext( actionContext, Enumerable.Empty <IFilterMetadata>().ToList() ); return(authorizationContext); }
/// <summary> /// Searches the 'Authorization' header for a 'Bearer' token. /// </summary> /// <returns></returns> protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { string token = null; try { // Give application opportunity to find from a different location, adjust, or reject token var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options); // event can set the token await Events.MessageReceived(messageReceivedContext); if (messageReceivedContext.Result != null) { return messageReceivedContext.Result; } // If application retrieved token from somewhere else, use that. token = messageReceivedContext.Token; if (string.IsNullOrEmpty(token)) { string authorization = Request.Headers["Authorization"]; // If no authorization header found, nothing to process further if (string.IsNullOrEmpty(authorization)) { return AuthenticateResult.NoResult(); } if (authorization.StartsWith("FakeBearer ", StringComparison.OrdinalIgnoreCase)) { token = authorization.Substring("FakeBearer ".Length).Trim(); } // If no token found, no further work possible if (string.IsNullOrEmpty(token)) { return AuthenticateResult.NoResult(); } } Dictionary<string, dynamic> tokenDecoded = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(token); ClaimsIdentity id = new ClaimsIdentity("Identity.Application", "name", "role"); foreach (var td in tokenDecoded) { if (td.Key == "sub") { id.AddClaim(new Claim("sub", td.Value.ToString())); if (!tokenDecoded.Any(c => c.Key == "name")) { id.AddClaim(new Claim("name", td.Value.ToString())); } } else { if (td.Value is string) { id.AddClaim(new Claim(td.Key, td.Value)); } else if (td.Value is IEnumerable) { foreach (string subValue in td.Value) { id.AddClaim(new Claim(td.Key, subValue)); } } else { throw new Exception("Unknown type"); } } } ClaimsPrincipal principal = new ClaimsPrincipal(id); var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options) { Principal = principal }; await Events.TokenValidated(tokenValidatedContext); if (tokenValidatedContext.Result != null) { return tokenValidatedContext.Result; } if (Options.SaveToken) { tokenValidatedContext.Properties.StoreTokens(new[] { new AuthenticationToken { Name = "access_token", Value = token } }); } tokenValidatedContext.Success(); return tokenValidatedContext.Result; } catch (Exception ex) { var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options) { Exception = ex }; await Events.AuthenticationFailed(authenticationFailedContext); if (authenticationFailedContext.Result != null) { return authenticationFailedContext.Result; } throw; } }
public ActionResult addCartDetailsToDataBase(string ProductName, string VendorName) { ClaimsIdentity claimsIdentity = User.Identity as ClaimsIdentity; if (claimsIdentity != null) { var userIdClaim = claimsIdentity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier); if (userIdClaim != null) { var userIdValue = userIdClaim.Value; Customer c = db.Customers.FirstOrDefault(i => i.ID == userIdValue); db.Entry(c).Collection(o => o.Orders).Load(); if (c.Orders.Count > 0) { foreach (var o in c.Orders) { if (o.Isbuy == false) { Product product = db.Products.Where(p => p.Name == ProductName).FirstOrDefault(); Vendor Vendor = db.Vendors.Where(v => v.ComponyName == VendorName).FirstOrDefault(); VendorProduct vendorProduct = db.VendorProducts.FirstOrDefault(vp => vp.Product.ID == product.ID && vp.Vendor.ID == Vendor.ID); OrderDetails od = new OrderDetails { VendorProduct = vendorProduct, Price = vendorProduct.Price, Quantity = 0, }; o.OrderDetails.Add(od); db.SaveChanges(); break; } else { Order order = new Order { Isbuy = false, TotalPrice = 0, Customer = c, OrderDetails = new List <OrderDetails>() }; Product product = db.Products.Where(p => p.Name == ProductName).FirstOrDefault(); Vendor Vendor = db.Vendors.Where(v => v.ComponyName == VendorName).FirstOrDefault(); VendorProduct vendorProduct = db.VendorProducts.FirstOrDefault(vp => vp.Product.ID == product.ID && vp.Vendor.ID == Vendor.ID); OrderDetails od = new OrderDetails { VendorProduct = vendorProduct, Price = vendorProduct.Price, Quantity = 0, }; order.OrderDetails.Add(od); db.Orders.Add(order); db.SaveChanges(); break; } } } else { Order order = new Order { Isbuy = false, TotalPrice = 0, Customer = c, OrderDetails = new List <OrderDetails>() }; Product product = db.Products.Where(p => p.Name == ProductName).FirstOrDefault(); Vendor Vendor = db.Vendors.Where(v => v.ComponyName == VendorName).FirstOrDefault(); VendorProduct vendorProduct = db.VendorProducts.FirstOrDefault(vp => vp.Product.ID == product.ID && vp.Vendor.ID == Vendor.ID); OrderDetails od = new OrderDetails { VendorProduct = vendorProduct, Price = vendorProduct.Price, Quantity = 0, }; order.OrderDetails.Add(od); db.Orders.Add(order); db.SaveChanges(); } return(View()); } else { return(Redirect("/Account/Login")); } } else { return(Redirect("/Account/Register")); } }
public async Task CloudAdapterContinueConversation() { // Arrange var claimsIdentity = new ClaimsIdentity(); var authenticateRequestResult = new AuthenticateRequestResult { ClaimsIdentity = claimsIdentity, ConnectorFactory = new TestConnectorFactory(), Audience = "audience", CallerId = "callerId" }; var userTokenClient = new TestUserTokenClient("appId"); var cloudEnvironmentMock = new Mock <BotFrameworkAuthentication>(); cloudEnvironmentMock.Setup(ce => ce.AuthenticateRequestAsync(It.IsAny <Activity>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authenticateRequestResult)); cloudEnvironmentMock.Setup(ce => ce.CreateConnectorFactory(It.IsAny <ClaimsIdentity>())).Returns(new TestConnectorFactory()); cloudEnvironmentMock.Setup(ce => ce.CreateUserTokenClientAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <UserTokenClient>(userTokenClient)); var bot = new ConnectorFactoryBot(); var expectedServiceUrl = "http://serviceUrl"; var conversationAccount = new ConversationAccount { Id = "conversation Id" }; var continuationActivity = new Activity { Type = ActivityTypes.Event, ServiceUrl = expectedServiceUrl, Conversation = conversationAccount }; var conversationReference = new ConversationReference { ServiceUrl = expectedServiceUrl, Conversation = conversationAccount }; var actualServiceUrl1 = string.Empty; var actualServiceUrl2 = string.Empty; var actualServiceUrl3 = string.Empty; var actualServiceUrl4 = string.Empty; var actualServiceUrl5 = string.Empty; var actualServiceUrl6 = string.Empty; BotCallbackHandler callback1 = (t, c) => { actualServiceUrl1 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback2 = (t, c) => { actualServiceUrl2 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback3 = (t, c) => { actualServiceUrl3 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback4 = (t, c) => { actualServiceUrl4 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback5 = (t, c) => { actualServiceUrl5 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; BotCallbackHandler callback6 = (t, c) => { actualServiceUrl6 = t.Activity.ServiceUrl; return(Task.CompletedTask); }; // Act var adapter = new CloudAdapter(cloudEnvironmentMock.Object); await adapter.ContinueConversationAsync("botAppId", continuationActivity, callback1, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, continuationActivity, callback2, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, continuationActivity, "audience", callback3, CancellationToken.None); await adapter.ContinueConversationAsync("botAppId", conversationReference, callback4, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, conversationReference, callback5, CancellationToken.None); await adapter.ContinueConversationAsync(claimsIdentity, conversationReference, "audience", callback6, CancellationToken.None); // Assert Assert.Equal(expectedServiceUrl, actualServiceUrl1); Assert.Equal(expectedServiceUrl, actualServiceUrl2); Assert.Equal(expectedServiceUrl, actualServiceUrl3); Assert.Equal(expectedServiceUrl, actualServiceUrl4); Assert.Equal(expectedServiceUrl, actualServiceUrl5); Assert.Equal(expectedServiceUrl, actualServiceUrl6); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { /* * services.Configure<CookiePolicyOptions>(options => * { * // This lambda determines whether user consent for non-essential cookies is needed for a given request. * options.CheckConsentNeeded = context => true; * options.MinimumSameSitePolicy = SameSiteMode.None; * }); */ services.AddResponseCaching(); services.AddControllersWithViews((mvcOptions) => { // mvcOptions.EnableEndpointRouting = false; }); services.AddAuthorization(options => { options.AddPolicy("RequireUpdateRights", policy => policy.RequireClaim("Permission", "CanUpdate")); }); services.Configure <GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal); services.AddResponseCompression(options => { options.MimeTypes = new[] { // Default "text/plain", "text/css", "application/javascript", // "text/html", "application/xml", "text/xml", "application/json", "text/json", // Custom "image/svg+xml" }; }); services.AddHttpContextAccessor(); services.AddScoped <IHostAddrService, HostAddrService>(); services.AddSingleton <IPathService, PathService>(); services.AddSignalR((options) => { options.EnableDetailedErrors = true; options.KeepAliveInterval = TimeSpan.FromSeconds(120); }); services.AddHostedService <WarmUpService>(); services.AddHostedService <QuotesService>(); #region Local Functions ClaimsPrincipal getCurrentUser(IServiceProvider sp) { /* * // this is how to get the real authenticated user * var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>(); * var user = httpContextAccessor?.HttpContext?.User; * return user?? new ClaimsPrincipal(new ClaimsIdentity(null, Enumerable.Empty<Claim>())); */ // the demo uses artificially created user ClaimsPrincipal basicPrincipal = new ClaimsPrincipal( new ClaimsIdentity( new Claim[] { new Claim("Permission", "CanUpdate"), new Claim(ClaimTypes.Role, "Admins"), new Claim(ClaimTypes.Role, "Users"), new Claim(ClaimTypes.Name, "DUMMY_USER"), new Claim(ClaimTypes.NameIdentifier, "DUMMY_USER Basic") }, "Basic")); ClaimsPrincipal validUser = basicPrincipal; ClaimsIdentity bearerIdentity = new ClaimsIdentity( new Claim[] { new Claim("Permission", "CupBearer"), new Claim(ClaimTypes.Role, "Token"), new Claim(ClaimTypes.Name, "DUMMY_USER"), new Claim(ClaimTypes.NameIdentifier, "DUMMY_USER Bear") }, "Bearer"); validUser.AddIdentity(bearerIdentity); return(validUser); }; #endregion // P.S.- IServerAddressesFeature is Useless with IIS Integration! services.AddSingleton <IServerAddressesFeature>((sp) => _serverAddressesFeature); services.AddThumbnailService(); services.AddSingleton <ICodeGenConfig, CodeGenConfig>(); services.AddSingleton <ISerializer, Serializer>(); services.AddFolderBrowser((options) => { options.GetUser = getCurrentUser; }); services.AddRIAppDemoService((options) => { options.GetUser = getCurrentUser; options.ConnectionString = Configuration[$"ConnectionStrings:DBConnectionStringADW"]; }); }
public async Task <IActionResult> CheckLogin(string username, string password, string code) { SysLog logEntity = new SysLog(); logEntity.ModuleName = "ē³»ē»ē»å½"; logEntity.Type = DbLogType.Login.ToString(); try { if (WebHelper.GetSession(ConstParameters.VerifyCodeKeyName).IsEmpty() || Md5Hash.Md5(code.ToLower(), 16) != WebHelper.GetSession(ConstParameters.VerifyCodeKeyName).ToString()) { throw new Exception("éŖčÆē éčÆÆļ¼čÆ·éę°č¾å „"); } var userEntity = _SysUserService.CheckLogin(username, password); if (userEntity != null) { //ē»å½å·²éå var identity = new ClaimsIdentity(SysManageAuthAttribute.SysManageAuthScheme); // ęå®čŗ«ä»½č®¤čÆē±»å List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.Sid, userEntity.Id), // ēØę·Id new Claim(ClaimTypes.Name, userEntity.Account), // ēØę·č“¦å· new Claim(ClaimTypes.GivenName, userEntity.RealName), new Claim(ClaimTypes.PrimarySid, userEntity.OrganizeId), new Claim(ClaimTypes.PrimaryGroupSid, userEntity.DepartmentId), new Claim(ClaimTypes.Role, userEntity.RoleId ?? ""), new Claim(ClaimTypes.Dns, Net.Ip ?? "") }; var isSystem = false; if (userEntity.Account == "admin") { isSystem = true; } identity.AddClaims(claims); identity.AddClaim(new Claim(ClaimTypes.IsPersistent, isSystem.ToString())); var principal = new ClaimsPrincipal(identity); //čæęę¶é“20åé //var authProperty = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(20) }; await HttpContext.SignInAsync(SysManageAuthAttribute.SysManageAuthScheme, principal); logEntity.Account = userEntity.Account; logEntity.NickName = userEntity.RealName; logEntity.Result = true; logEntity.Description = "ē»å½ęå"; _ISysLogService.WriteSysLog(logEntity); } return(Content(new AjaxResult { state = ResultType.success.ToString(), message = "ē»å½ęåć" }.ToJson())); } catch (Exception ex) { logEntity.Account = username; logEntity.NickName = username; logEntity.Result = false; logEntity.Description = "ē»å½å¤±č“„ļ¼" + ex.Message; _ISysLogService.WriteSysLog(logEntity); return(Content(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson())); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); #region Username / Password Required if (string.IsNullOrWhiteSpace(context.UserName)) { context.SetError("Username", "The Username is Required"); return; } if (string.IsNullOrWhiteSpace(context.Password)) { context.SetError("Password", "The Password is Required"); return; } #endregion try { appUser user = Auth.UserLogin(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The Username or Password is incorrect."); return; } if (!user.isApproved) { context.SetError("invalid_grant", "User is not approved"); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", "user")); AuthenticationProperties props = new AuthenticationProperties(new Dictionary <string, string>() { { "account_id", user.UserId.Value.ToString() }, { "username", user.username }, { "roles", string.Join(", ", user.roles) }, { "name", string.IsNullOrEmpty(user.nombre) ? "" : user.nombre }, { "lastlogin", user.lastlogin }, { "picture", string.IsNullOrEmpty(user.picture) ? "" : user.picture } }); AuthenticationTicket ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } catch (Exception ex) { switch (ex.Message) { case "Invalid Password": case "User not found": context.SetError("invalid_grant", "The Username or Password is incorrect."); return; case "User locked out": context.SetError("invalid_grant", "The User is Locked Out"); return; default: context.SetError("invalid_grant", "Error while validating user"); return; } } }
/// <summary> /// ę·»å åŗēØēØåŗ声ę /// </summary> protected virtual async Task AddApplicationClaims(ProfileDataRequestContext context, ClaimsIdentity identity) { var application = await GetApplication(context); if (application == null) { return; } identity.AddClaim(new Claim(Util.Security.Claims.ClaimTypes.ApplicationId, application.Id)); identity.AddClaim(new Claim(Util.Security.Claims.ClaimTypes.ApplicationCode, application.Code)); identity.AddClaim(new Claim(Util.Security.Claims.ClaimTypes.ApplicationName, application.Name)); }
private string GetClaimValue(ClaimsIdentity identity, string claimsType) => identity.FindFirst(claimsType)?.Value;
public static void UseOAuthAuthorizationServer(this IAppBuilder app, AdminHostSecurityConfiguration config) { TicketDataFormat tokenFormat = null; if (config.TokenDataProtectorCertificate != null) { tokenFormat = new TicketDataFormat(new X509CertificateTicketDataProtector(config.TokenDataProtectorCertificate)); } app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AccessTokenFormat = tokenFormat, RefreshTokenFormat = tokenFormat, AllowInsecureHttp = !config.RequireSsl, AccessTokenExpireTimeSpan = config.TokenExpiration, AuthorizeEndpointPath = new PathString(Constants.AuthorizePath), Provider = new OAuthAuthorizationServerProvider { OnValidateClientRedirectUri = ctx => { if (ctx.ClientId == Constants.IdAdmMgrClientId) { var path = ctx.Request.PathBase.ToString(); if (String.IsNullOrWhiteSpace(path)) { path = "/"; } var callbackUrl = new Uri(ctx.Request.Uri, path); var url = callbackUrl.AbsoluteUri; if (url.EndsWith("/")) { url = url.Substring(0, url.Length - 1); } url += Constants.CallbackFragment; ctx.Validated(url); } else { ctx.Rejected(); } return(Task.FromResult(0)); }, OnAuthorizeEndpoint = ctx => { var owin = ctx.OwinContext; var result = owin.Authentication.AuthenticateAsync(config.HostAuthenticationType).Result; if (result != null) { Logger.InfoFormat("User is authenticated from {0}", config.HostAuthenticationType); // we only want name and role claims var expected = new[] { config.NameClaimType, config.RoleClaimType }; var claims = result.Identity.Claims.Where(x => expected.Contains(x.Type)); var id = new ClaimsIdentity(claims, Constants.BearerAuthenticationType, config.NameClaimType, config.RoleClaimType); owin.Authentication.SignIn(id); } else { Logger.InfoFormat("User is authenticated from {0}; issuing challenge", config.HostAuthenticationType); owin.Authentication.Challenge(); }; ctx.RequestCompleted(); return(Task.FromResult(0)); } } }); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AccessTokenFormat = tokenFormat, AuthenticationType = config.BearerAuthenticationType, AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive }); }
protected override async Task <AuthenticationTicket> CreateTicketAsync( [NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { // See https://opendocs.alipay.com/apis/api_2/alipay.user.info.share for details. var sortedParams = new SortedDictionary <string, string>() { ["app_id"] = Options.ClientId, ["auth_token"] = tokens.AccessToken, ["charset"] = "utf-8", ["format"] = "JSON", ["method"] = "alipay.user.info.share", ["sign_type"] = "RSA2", ["timestamp"] = Clock.UtcNow.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), ["version"] = "1.0", }; sortedParams.Add("sign", GetRSA2Signature(sortedParams)); string address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, sortedParams !); using var response = await Backchannel.GetAsync(address, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync(Context.RequestAborted)); throw new HttpRequestException("An error occurred while retrieving user information."); } using var stream = await response.Content.ReadAsStreamAsync(Context.RequestAborted); using var document = JsonDocument.Parse(stream); var rootElement = document.RootElement; if (!rootElement.TryGetProperty("alipay_user_info_share_response", out JsonElement mainElement)) { string errorCode = rootElement.GetProperty("error_response").GetProperty("code").GetString() !; throw new Exception($"An error (Code:{errorCode}) occurred while retrieving user information."); } if (!ValidateReturnCode(mainElement, out string code)) { throw new Exception($"An error (Code:{code}) occurred while retrieving user information."); } identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, mainElement.GetString("user_id") !, ClaimValueTypes.String, Options.ClaimsIssuer)); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, mainElement); context.RunClaimActions(); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal !, context.Properties, Scheme.Name)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); //if (user == null) //{ // context.SetError("invalid_grant", "The user name or password is incorrect."); // return; //} //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, // OAuthDefaults.AuthenticationType); //ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, // CookieAuthenticationDefaults.AuthenticationType); //AuthenticationProperties properties = CreateProperties(user.UserName); //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); //context.Validated(ticket); //context.Request.Context.Authentication.SignIn(cookiesIdentity); var identity = new ClaimsIdentity(context.Options.AuthenticationType); context.OwinContext.Response.Headers.Set("Access-Control-Allow-Origin", "*"); using (var db = new EcommEntities()) { if (db != null) { int user_type = 0; string err = "Provided username and password is incorrect"; string code = "1"; string userid = ""; string pushid = ""; userid = context.UserName; if (context.UserName.Contains("-pushid")) { userid = context.UserName.Substring(0, context.UserName.LastIndexOf("-pushid")); pushid = context.UserName.Substring(context.UserName.LastIndexOf("-pushid") + 7); } var user = db.user_details.ToList(); user_type = (int)user.Where(a => a.email.Trim().ToLower() == userid.Trim().ToLower()).Select(a => a.user_type).Single(); try { //userid = context.UserName; if (user != null) { if (user_type == 20000) { if (!string.IsNullOrEmpty(user.Where(u => (string.Equals(u.email.Trim(), userid.Trim(), StringComparison.OrdinalIgnoreCase)) && u.password == context.Password).FirstOrDefault().email)) { var login1 = db.user_details.Where(a => a.email.Trim().ToLower() == userid.Trim().ToLower()); //foreach (user_details uf in login1) //{ // uf.user_status = 1; // //uf.Push_id = pushid; //} //db.SaveChanges(); identity.AddClaim(new Claim(ClaimTypes.Role, userid)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "userdisplayname", userid }, { "role", "admin" } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); context.Validated(identity); } } else if (user_type != 20000) { if (!string.IsNullOrEmpty(user.Where(u => (string.Equals(u.email.Trim(), userid.Trim(), StringComparison.OrdinalIgnoreCase)) && u.password == context.Password && u.user_status == 1).FirstOrDefault().email)) { var login1 = db.user_details.Where(a => a.email.Trim().ToLower() == userid.Trim().ToLower()); //foreach (User_Info uf in login1) //{ // uf.User_status = 1; // if (pushid != null && pushid != "") // uf.Push_id = pushid; //} //db.SaveChanges(); identity.AddClaim(new Claim(ClaimTypes.Role, userid)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "userdisplayname", userid }, { "role", "admin" } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); context.Validated(identity); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); context.Rejected(); } } } } catch (System.Exception e) { context.SetError(code, err); //return e;//Response.status(Response.Status.UNAUTHORIZED).build(); } } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); context.Rejected(); } } }
public ClaimsIdentity CreateIdentity(List <string> scopes, IEnumerable <Claim> claims) { var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); foreach (var claim in claims) { switch (claim.Type) { case ClaimTypes.NameIdentifier: { identity.AddClaim(claim); identity.AddClaim(OpenIdConnectConstants.Claims.Subject, claim.Value); break; } case ClaimTypes.Name: { AddClaim(claim, identity); break; } case OpenIdConnectConstants.Claims.Email: { if (scopes.Contains(OpenIdConnectConstants.Scopes.Email)) { AddClaim(claim, identity); } break; } case OpenIdConnectConstants.Claims.GivenName: { if (scopes.Contains(OpenIdConnectConstants.Scopes.Profile)) { AddClaim(claim, identity); } break; } case OpenIdConnectConstants.Claims.FamilyName: { if (scopes.Contains(OpenIdConnectConstants.Scopes.Profile)) { AddClaim(claim, identity); } break; } case OpenIdConnectConstantsExt.Claims.Country: { if (scopes.Contains(OpenIdConnectConstants.Scopes.Address)) { AddClaim(claim, identity); } break; } case OpenIdConnectConstantsExt.Claims.Documents: { if (scopes.Contains(OpenIdConnectConstants.Scopes.Profile)) { AddClaim(claim, identity); } break; } case OpenIdConnectConstantsExt.Claims.SignType: { AddClaim(claim, identity); break; } } } return(identity); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { AuthenticationProperties properties = null; var query = Request.Query; var error = query["error"]; if (!StringValues.IsNullOrEmpty(error)) { var failureMessage = new StringBuilder(); failureMessage.Append(error); var errorDescription = query["error_description"]; if (!StringValues.IsNullOrEmpty(errorDescription)) { failureMessage.Append(";Description=").Append(errorDescription); } var errorUri = query["error_uri"]; if (!StringValues.IsNullOrEmpty(errorUri)) { failureMessage.Append(";Uri=").Append(errorUri); } return(HandleRequestResult.Fail(failureMessage.ToString())); } var code = query["code"]; var state = query["state"]; properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(HandleRequestResult.Fail("The oauth state was missing or invalid.")); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties)) { return(HandleRequestResult.Fail("Correlation failed.")); } if (StringValues.IsNullOrEmpty(code)) { return(HandleRequestResult.Fail("Code was not found.")); } var tokens = await ExchangeCodeAsync(code, BuildRedirectUri(Options.CallbackPath)); if (tokens.Error != null) { return(HandleRequestResult.Fail(tokens.Error)); } if (string.IsNullOrEmpty(tokens.AccessToken)) { return(HandleRequestResult.Fail("Failed to retrieve access token.")); } var identity = new ClaimsIdentity(ClaimsIssuer); if (Options.SaveTokens) { var authTokens = new List <AuthenticationToken>(); authTokens.Add(new AuthenticationToken { Name = "access_token", Value = tokens.AccessToken }); if (!string.IsNullOrEmpty(tokens.RefreshToken)) { authTokens.Add(new AuthenticationToken { Name = "refresh_token", Value = tokens.RefreshToken }); } if (!string.IsNullOrEmpty(tokens.TokenType)) { authTokens.Add(new AuthenticationToken { Name = "token_type", Value = tokens.TokenType }); } if (!string.IsNullOrEmpty(tokens.ExpiresIn)) { int value; if (int.TryParse(tokens.ExpiresIn, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) { // https://www.w3.org/TR/xmlschema-2/#dateTime // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx var expiresAt = Clock.UtcNow + TimeSpan.FromSeconds(value); authTokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) }); } } properties.StoreTokens(authTokens); } var ticket = await CreateTicketAsync(identity, properties, tokens); if (ticket != null) { return(HandleRequestResult.Success(ticket)); } else { return(HandleRequestResult.Fail("Failed to retrieve user information from remote server.")); } }
public async Task CloudAdapterCreateConversation() { // Arrange var claimsIdentity = new ClaimsIdentity(); var authenticateRequestResult = new AuthenticateRequestResult { ClaimsIdentity = claimsIdentity, ConnectorFactory = new TestConnectorFactory(), Audience = "audience", CallerId = "callerId" }; var userTokenClient = new TestUserTokenClient("appId"); var conversationResourceResponse = new ConversationResourceResponse(); var createResponse = new HttpOperationResponse <ConversationResourceResponse> { Body = conversationResourceResponse }; // note Moq doesn't support extension methods used in the implementation so we are actually mocking the underlying CreateConversationWithHttpMessagesAsync method var conversationsMock = new Mock <IConversations>(); conversationsMock.Setup(cm => cm.CreateConversationWithHttpMessagesAsync(It.IsAny <ConversationParameters>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(createResponse)); var connectorMock = new Mock <IConnectorClient>(); connectorMock.SetupGet(m => m.Conversations).Returns(conversationsMock.Object); var expectedServiceUrl = "http://serviceUrl"; var expectedAudience = "audience"; var connectorFactoryMock = new Mock <ConnectorFactory>(); connectorFactoryMock.Setup(cf => cf.CreateAsync(It.Is <string>(serviceUrl => serviceUrl == expectedServiceUrl), It.Is <string>(audience => audience == expectedAudience), It.IsAny <CancellationToken>())).Returns(Task.FromResult(connectorMock.Object)); var cloudEnvironmentMock = new Mock <BotFrameworkAuthentication>(); cloudEnvironmentMock.Setup(ce => ce.AuthenticateRequestAsync(It.IsAny <Activity>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(authenticateRequestResult)); cloudEnvironmentMock.Setup(ce => ce.CreateConnectorFactory(It.IsAny <ClaimsIdentity>())).Returns(connectorFactoryMock.Object); cloudEnvironmentMock.Setup(ce => ce.CreateUserTokenClientAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <UserTokenClient>(userTokenClient)); var expectedChannelId = "expected-channel-id"; var actualChannelId = string.Empty; BotCallbackHandler callback1 = (t, c) => { actualChannelId = t.Activity.ChannelId; return(Task.CompletedTask); }; var conversationParameters = new ConversationParameters { IsGroup = false, Bot = new ChannelAccount { }, Members = new ChannelAccount[] { }, TenantId = "tenantId", }; // Act var adapter = new CloudAdapter(cloudEnvironmentMock.Object); await adapter.CreateConversationAsync("botAppId", expectedChannelId, expectedServiceUrl, expectedAudience, conversationParameters, callback1, CancellationToken.None); // Assert Assert.Equal(expectedChannelId, actualChannelId); }
public ActionResult <LoginModel> LoginPost(decimal CPF, string Pass, #pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) #pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) { User user = _context.User.Where(x => x.CPF.Equals(CPF)).FirstOrDefault(); LoginModel loginModel = new LoginModel(); if (user == null) { return(NotFound("User not found with this CPF!")); } try { var passCript = HashMd5Generator.Generate(Pass); if (user.Password != passCript) { return(BadRequest("Passoword is invalid!")); } bool validCredentials = false; validCredentials = (user != null); if (validCredentials) { ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(user.CPF.ToString(), "Login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(JwtRegisteredClaimNames.UniqueName, user.CPF.ToString()) } ); DateTime creationDate = DateTime.Now; DateTime expirationDate = creationDate + 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 = creationDate, Expires = expirationDate }); var token = handler.WriteToken(securityToken); loginModel.authenticated = true; loginModel.created = creationDate.ToString("yyyy-MM-dd HH:mm:ss"); loginModel.expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"); loginModel.accessToken = token; loginModel.message = "OK"; return(Ok(loginModel)); } else { loginModel.authenticated = false; loginModel.message = "Failed to authenticate!"; return(BadRequest(loginModel)); } } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
protected ADreamClaimIdentity(ClaimsIdentity other) : base(other) { }
protected override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) { var options = this.Options; var tvps = options.TokenValidationParameters; var signingKey = tvps.IssuerSigningKey; var handler = new JwtSecurityTokenHandler(); var newTokenExpiration = DateTime.Now.Add(options.ExpireTimeSpan); var identity = new ClaimsIdentity(user.Identity); // ę·»å IdentityServeréč¦ē声ęļ¼å¦ęäøęÆēØäŗIdentityServerļ¼åę éę·»å 仄äø声ę // sub åÆäøę čÆļ¼ēØäŗIdentityServerļ¼ // åę¶å®ä¹åŗčÆ„å ·ęå ·ęåÆäøę čÆļ¼ClaimTypes.NameIdentifier // 仄äøē®ē§°ä½äŗIdentityModel.JwtClaimTypes var subject = "sub"; // JwtClaimTypes.Subject var identityProvider = "idp"; // JwtClaimTypes.IdentityProvider //var issuedAt = "iat"; // JwtClaimTypes.IssuedAt var authenticationTime = "auth_time"; // JwtClaimTypes.AuthenticationTime var lang = OAuthSignInAuthenticationDefaults.Lang; if (!user.HasClaim(h => h.Type == subject)) { identity.AddClaim(new Claim(subject, identity.FindFirst(f => f.Type == ClaimTypes.NameIdentifier).Value)); } if (!user.HasClaim(h => h.Type == identityProvider)) { identity.AddClaim(new Claim(identityProvider, "local")); } if (!user.HasClaim(h => h.Type == authenticationTime)) { identity.AddClaim(new Claim(authenticationTime, DateTime.Now.ToInt() + "")); } if (!user.HasClaim(h => h.Type == lang)) { identity.AddClaim(new Claim(lang, CultureInfo.CurrentCulture.ToString())); } //identity.AddClaim(new Claim(issuedAt, DateTime.Now.ToInt() + "")); // JwtSecurityTokenHandlerēęētokenčŖåø¦iatļ¼ę仄äøēØ var securityToken = handler.CreateToken(new SecurityTokenDescriptor() { SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256), Subject = identity, Expires = newTokenExpiration, Issuer = tvps.ValidateIssuer ? tvps.ValidIssuer : null, Audience = tvps.ValidateAudience ? tvps.ValidAudience : null, }); var tokenValue = handler.WriteToken(securityToken); var encodedToken = "Bearer " + tokenValue; var jwtToken = new JwtToken { Token = encodedToken, Expires = newTokenExpiration, UserInfo = new UserInfo { Avatar = user.FindFirstValue(OAuthSignInAuthenticationDefaults.Avatar), Sex = user.FindFirstValue(OAuthSignInAuthenticationDefaults.Gender)?.ToInt(), Name = user.FindFirstValue(OAuthSignInAuthenticationDefaults.UniqueName), DisplayName = user.FindFirstValue(OAuthSignInAuthenticationDefaults.GivenName), ID = user.FindFirstValue(OAuthSignInAuthenticationDefaults.Sub) } }; Context.Features[typeof(JwtToken)] = jwtToken; properties.Items[nameof(JwtToken)] = encodedToken; Response.Cookies.Append(options.TokenKey, encodedToken); var returnUrlKey = options.ReturnUrlKey; if (properties.Items.TryGetValue(returnUrlKey, out var returnUrl)) { Response.Cookies.Append(returnUrlKey, returnUrl); } return(Task.CompletedTask); }
public static string GetClaimOrDefault(this ClaimsIdentity self, string claimType) { return(self.Claims.GetClaimOrDefault(claimType)); }
public AbpLoginResult(TUser user, ClaimsIdentity identity) : this(AbpLoginResultType.Success) { User = user; Identity = identity; }
/// <summary> /// Returns all claims for a given user /// </summary> /// <param name="user"></param> /// <returns></returns> public Task <IList <Claim> > GetClaimsAsync(TUser user) { ClaimsIdentity identity = userClaimsRepo.FindByUserId(user.Id); return(Task.FromResult <IList <Claim> >(identity.Claims.ToList())); }
/// <summary> /// Verify a user login and generate the corresponded cookies /// </summary> /// <param name="roster">username</param> /// <param name="password">password</param> /// <returns></returns> public async Task <ActionResult> Login(string roster, string password) { if (ModelState.IsValid) { if (!string.IsNullOrEmpty(roster) && !string.IsNullOrEmpty(password)) { //Especial user if (roster == "0000" && password == "admin") { //Generate the cookies and save the user data var claims = new List <Claim> { new Claim(ClaimTypes.Name, roster), new Claim("FullName", "Administrator"), }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5), IsPersistent = false }; return(RedirectToAction("Index", "Admin")); } else { //Verify if the user exist in the database teacher = db.Teachers.FirstOrDefault(p => p.Roaster == roster && p.Password == _encrypt(password)); if (teacher != null) { string role = "Teacher"; //Assign a role if (teacher.GetHours() == 10) { role = "Cordinator"; } //Generate the cookies to authentication and save the tecaher information var claims = new List <Claim> { new Claim(ClaimTypes.Name, teacher.Roaster), new Claim("ID", teacher.ID.ToString()), new Claim("FullName", teacher.Names + " " + teacher.MiddleName), new Claim(ClaimTypes.Role, role) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5), IsPersistent = false }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(RedirectToAction("Index", "Profile")); } else { return(RedirectToAction("Index", "Home", new { message = "This user doesn't exist" })); } } } else { return(RedirectToAction("Index", "Home", new { message = "Fill all the fields" })); } } return(RedirectToAction("Index", "Home")); }
private void SetupAuthentication(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => { o.Cookie.Name = ".IndieVisible.Identity.Application"; o.LoginPath = new PathString("/login"); o.AccessDeniedPath = new PathString("/home/access-denied"); }) .AddFacebook(o => { o.AppId = Configuration["Authentication:Facebook:AppId"]; o.AppSecret = Configuration["Authentication:Facebook:AppSecret"]; o.Fields.Add("picture"); o.Events = new OAuthEvents { OnCreatingTicket = context => { ClaimsIdentity identity = (ClaimsIdentity)context.Principal.Identity; string profileImg = context.User.GetProperty("picture").GetProperty("data").GetProperty("url").GetString(); identity.AddClaim(new Claim("urn:facebook:picture", profileImg)); return(Task.CompletedTask); } }; }) .AddGoogle(googleOptions => { googleOptions.ClientId = Configuration["Authentication:Google:ClientId"]; googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"]; googleOptions.Events = new OAuthEvents { OnCreatingTicket = context => { ClaimsIdentity identity = (ClaimsIdentity)context.Principal.Identity; string profileImg = context.User.GetProperty("picture").GetString(); identity.AddClaim(new Claim("urn:google:picture", profileImg)); return(Task.FromResult(0)); } }; }) .AddMicrosoftAccount(microsoftOptions => { microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"]; microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"]; microsoftOptions.SaveTokens = true; microsoftOptions.Events = new OAuthEvents { OnCreatingTicket = context => { ClaimsIdentity identity = (ClaimsIdentity)context.Principal.Identity; identity.AddClaim(new Claim("urn:microsoft:accesstoken", context.TokenResponse.AccessToken)); return(Task.FromResult(0)); } }; }) .AddGithub(githubOptions => { githubOptions.ClientId = Configuration["Authentication:Github:ClientId"]; githubOptions.ClientSecret = Configuration["Authentication:Github:ClientSecret"]; }); }
public void Configure(IApplicationBuilder app) { // Add a new middleware validating the encrypted // access tokens issued by the OIDC server. app.UseOAuthValidation(); // Add a new middleware issuing tokens. app.UseOpenIdConnectServer(options => { options.TokenEndpointPath = "/connect/token"; // Override OnValidateTokenRequest to skip client authentication. options.Provider.OnValidateTokenRequest = context => { // Reject the token requests that don't use // grant_type=password or grant_type=refresh_token. if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType()) { context.Reject( error: OpenIdConnectConstants.Errors.UnsupportedGrantType, description: "Only grant_type=password and refresh_token " + "requests are accepted by this return Task.FromResult(0); } // Since there's only one application and since it's a public client // (i.e a client that cannot keep its credentials private), // call Skip() to inform the server the request should be // accepted without enforcing client authentication. context.Skip(); return Task.FromResult(0); }; // Override OnHandleTokenRequest to support // grant_type=password token requests. options.Provider.OnHandleTokenRequest = context => { // Only handle grant_type=password token requests and let the // OpenID Connect server middleware handle the other grant types. if (context.Request.IsPasswordGrantType()) { // Do your credentials validation here. // Note: you can call Reject() with a message // to indicate that authentication failed. var identity = new ClaimsIdentity(context.Options.AuthenticationScheme); identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]"); // By default, claims are not serialized // in the access and identity tokens. // Use the overload taking a "destinations" // parameter to make sure your claims // are correctly inserted in the appropriate tokens. identity.AddClaim("urn:customclaim", "value", OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), context.Options.AuthenticationScheme); // Call SetScopes with the list of scopes you want to grant // (specify offline_access to issue a refresh token). ticket.SetScopes("profile", "offline_access"); context.Validate(ticket); } return Task.FromResult(0); }; }); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { switch (context.ClientId) { case QuickspatchWebClient: { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); var franchisseService = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IFranchiseeTenantService)) as IFranchiseeTenantService; FranchiseeTenant franchisee = null; if (franchisseService != null) { franchisee = franchisseService.CheckFranchiseeWithNameAndLicenseKey(context.UserName, context.Password); if (franchisee == null) { context.Rejected(); return; } } if (franchisee == null) { context.Rejected(); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimsDeclaration.IdClaim, franchisee.Id.ToString())); identity.AddClaim(new Claim(ClaimsDeclaration.QuickspatchClientType, ((int)QuickspatchClientType.WebClient).ToString())); // create metadata to pass on to refresh token provider var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", context.ClientId } }); //var diagnosticService = new DiagnosticService(); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); //bool b = context.Validated(ticket); //diagnosticService.Debug(string.Format("Validated ticket with user{0}:{1}", context.UserName, b)); return; } case QuickspatchMobileClient: { var franchiseeConfigurationService = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IFranchiseeConfigurationService)) as IFranchiseeConfigurationService; var webApiConsumeUserService = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IWebApiConsumeUserService)) as IWebApiConsumeUserService; if (franchiseeConfigurationService != null && webApiConsumeUserService != null) { var franchisee = franchiseeConfigurationService.FirstOrDefault(); var franchiseeData = new FranchisseNameAndLicenseDto() { LicenseKey = franchisee.LicenseKey, FranchiseeName = franchisee.Name }; var objTokenStore = webApiConsumeUserService.GetToken(franchiseeData); if (objTokenStore != null) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); var userService = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserService)) as IUserService; User user = null; //verify is expire or not if (userService != null) { user = userService.GetUserByUserNameAndPass(context.UserName, context.Password); if (user == null) { context.Rejected(); return; } } if (user == null) { context.Rejected(); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimsDeclaration.IdClaim, user.Id.ToString())); identity.AddClaim(new Claim(ClaimsDeclaration.QuickspatchClientType, ((int)QuickspatchClientType.MobileClient).ToString())); // create metadata to pass on to refresh token provider var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", context.ClientId } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); return; } else { context.Response.StatusCode = 99; context.SetError("Invalid license"); //context.Rejected(); return; } } return; } default: return; } }
public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser> manager, ClaimsIdentity ext = null) { // Observe que o authenticationType precisa ser o mesmo que foi definido em CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); var claims = new List <Claim>(); if (!string.IsNullOrEmpty(CurrentClientId)) { claims.Add(new Claim("AspNet.Identity.ClientId", CurrentClientId)); } // Adicione novos Claims aqui // // Adicionando Claims externos capturados no login if (ext != null) { await SetExternalProperties(userIdentity, ext); } // Gerenciamento de Claims para informaƧoes do usuario //claims.Add(new Claim("AdmRoles", "True")); userIdentity.AddClaims(claims); return(userIdentity); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { string redirectUri = string.Empty; if (error != null) { return(BadRequest(Uri.EscapeDataString(error)));//Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } //var redirectUriValidationResult = ValidateClientAndRedirectUri(this.Request, ref redirectUri); //if (!string.IsNullOrWhiteSpace(redirectUriValidationResult)) //{ // return BadRequest(redirectUriValidationResult); //} ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } return(Ok()); }
public static void SignOutAllAndSignIn(this IAuthenticationManager authenticationManager, ClaimsIdentity identity, bool rememberMe = false) { authenticationManager.SignOutAll(); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = rememberMe }, identity); }
public void HandlerCreateRoundtripSingleClaimTypes() { var signinKey = SymmetricKeyGenerator.Create(32); var identity = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Name, "dominick"), new Claim(ClaimTypes.Email, "*****@*****.**"), }, "Custom"); var descriptor = new SecurityTokenDescriptor { Subject = identity, SigningCredentials = new HmacSigningCredentials(signinKey), TokenIssuerName = "dominick", Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(8)), AppliesToAddress = "http://foo.com" }; var handler = new JsonWebTokenHandler(); var token = handler.CreateToken(descriptor); var tokenString = handler.WriteToken(token); Trace.WriteLine(tokenString); // token should not be empty Assert.IsTrue(!string.IsNullOrWhiteSpace(tokenString)); // token with signature needs to be 3 parts var parts = tokenString.Split('.'); Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts"); // signature must be 256 bits var sig = Base64Url.Decode(parts[2]); Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits"); var jwtToken = handler.ReadToken(tokenString); var config = new SecurityTokenHandlerConfiguration(); var registry = new WebTokenIssuerNameRegistry(); registry.AddTrustedIssuer("dominick", "dominick"); config.IssuerNameRegistry = registry; var issuerResolver = new WebTokenIssuerTokenResolver(); issuerResolver.AddSigningKey("dominick", Convert.ToBase64String(signinKey)); config.IssuerTokenResolver = issuerResolver; config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://foo.com")); handler.Configuration = config; var identity2 = handler.ValidateToken(jwtToken).First(); Assert.IsTrue(identity.Claims.Count() == 2); //Assert.IsTrue(identity.Claims.First().Issuer == "dominick"); }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { var callerIdentity = (IClaimsIdentity)principal.Identity; // Create new identity and copy content of the caller's identity into it (including the existing delegate chain) var result = new ClaimsIdentity(); CopyClaims(callerIdentity, result); // If there is an ActAs token in the RST, add and return the claims from it as the top-most identity // and put the caller's identity into the Delegate property of this identity. if (request.ActAs != null) { var actAsIdentity = new ClaimsIdentity(); var actAsSubject = request.ActAs.GetSubject()[0]; CopyClaims(actAsSubject, actAsIdentity); // Find the last delegate in the actAs identity var lastActingVia = actAsIdentity as IClaimsIdentity; while (lastActingVia.Actor != null) { lastActingVia = lastActingVia.Actor; } // Put the caller's identity as the last delegate to the ActAs identity lastActingVia.Actor = result; // Return the actAsIdentity instead of the caller's identity in this case result = actAsIdentity; } return result; }
public static ClaimsPrincipal Create() { var anonId = new ClaimsIdentity(); var anonPrincipal = new ClaimsPrincipal(new ClaimsIdentityCollection(new ClaimsIdentity[]{anonId})); return anonPrincipal; }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { if (null == principal) { throw new ArgumentNullException("principal"); } var outputIdentity = new ClaimsIdentity(); var userName = principal.Identity.Name; using (var db = new StsContext()) { var webUser = db.WebUsers.Single(w => w.Username == userName); foreach (var requestClaim in request.Claims) { var value = GetValueForClaimRequest(requestClaim, webUser); if (value != null) { outputIdentity.Claims.Add(new Claim(requestClaim.ClaimType, value)); } } if (outputIdentity.Claims.All(c => c.ClaimType != Security.ClaimTypes.Name)) { outputIdentity.Claims.Add(new Claim(Security.ClaimTypes.Name, webUser.Username)); } if (outputIdentity.Claims.All(c => c.ClaimType != Security.ClaimTypes.Role)) { outputIdentity.Claims.Add(new Claim(Security.ClaimTypes.Role, webUser.Role)); } } return outputIdentity; }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { if (null == principal) { throw new ArgumentNullException("principal"); } var outputIdentity = new ClaimsIdentity(); IEnumerable<Claim> outputClaims; if (this.scopeModel.UseClaimsPolicyEngine) { IClaimsPolicyEvaluator evaluator = new ClaimsPolicyEvaluator(PolicyStoreFactory.Instance); outputClaims = evaluator.Evaluate(new Uri(scope.AppliesToAddress), ((IClaimsIdentity)principal.Identity).Claims); } else { outputClaims = ((IClaimsIdentity)principal.Identity).Claims; } outputIdentity.Claims.AddRange(outputClaims); if (outputIdentity.Name == null && outputIdentity.Claims.SingleOrDefault(c => c.ClaimType == ClaimTypes.NameIdentifier) != null) outputIdentity.Claims.Add(new Claim(ClaimTypes.Name, outputIdentity.Claims.SingleOrDefault(c => c.ClaimType == ClaimTypes.NameIdentifier).Value)); return outputIdentity; }
public override ClaimsIdentityCollection ValidateToken(SecurityToken token) { CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.CustomUserNameSecurityTokenHandler.ValidateToken", "MyTraceSource", SourceLevels.Information); //StackTracer.TraceStack(ts); UserNameSecurityToken usernameToken = token as UserNameSecurityToken; if (usernameToken == null) { throw new ArgumentException("usernameToken", "The security token is not a valid username security token."); } // will throw if fails UsernameCredentialStore.AuthenticateUser(usernameToken.UserName, usernameToken.Password); ClaimsIdentityCollection identities = new ClaimsIdentityCollection(); IClaimsIdentity claimsIdentity = new ClaimsIdentity("CustomUserNameSecurityTokenHandler"); claimsIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, usernameToken.UserName)); identities.Add(claimsIdentity); return identities; }
private static void SetPrincipal() { var idPclaims = new List<Claim> { new Claim(ClaimTypes.Name, "Alice", ClaimValueTypes.String, "IdP"), new Claim(ClaimTypes.Email, "*****@*****.**", ClaimValueTypes.String, "IdP"), new Claim(ClaimTypes.Role, "Users", ClaimValueTypes.String, "IdP"), new Claim(ClaimTypes.Role, "Marketing", ClaimValueTypes.String, "IdP"), new Claim(ClaimTypes.Role, "Sales", ClaimValueTypes.String, "IdP"), new Claim("http://www.thinktecture.com/claims/location", "Heidelberg", ClaimValueTypes.String, "IdP") }; var authZclaims = new List<Claim> { new Claim(WSAuthorizationConstants.Action, "AddCustomer", ClaimValueTypes.String, "RSTS"), new Claim(WSAuthorizationConstants.Action, "ChangeCustomer", ClaimValueTypes.String, "RSTS") }; var idp = new ClaimsIdentity(idPclaims); var authZ = new ClaimsIdentity(authZclaims); var principal = new ClaimsPrincipal(new List<IClaimsIdentity> { idp, authZ }); Thread.CurrentPrincipal = principal; }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { var outputIdentity = new ClaimsIdentity(); if (null == principal) { throw new InvalidRequestException("The caller's principal is null."); } switch (principal.Identity.Name.ToUpperInvariant()) { // In a production environment, all the information that will be added // as claims should be read from the authenticated Windows Principal. // The following lines are hardcoded because windows integrated // authentication is disabled. case "ADATUM\\JOHNDOE": outputIdentity.Claims.AddRange(new List<Claim> { new Claim(System.IdentityModel.Claims.ClaimTypes.Name, "ADATUM\\johndoe"), new Claim(AllOrganizations.ClaimTypes.Group, Adatum.Groups.DomainUsers), new Claim(AllOrganizations.ClaimTypes.Group, Adatum.Groups.MarketingManagers) }); break; } return outputIdentity; }
/// <summary> /// This method returns the claims to be issued in the token. /// </summary> /// <param name="principal">The caller's principal.</param> /// <param name="request">The incoming RST, can be used to obtain addtional information.</param> /// <param name="scope">The scope information corresponding to this request.</param> /// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception> /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns> protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { if (null == principal) { throw new ArgumentNullException("principal"); } var outputIdentity = new ClaimsIdentity(); var attributes = (UserAttribute[])HttpContext.Current.Session["Attributes"]; foreach (var attribute in attributes) { if (attribute.Name == "Email") { outputIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Email, attribute.Value)); } else if (attribute.Name == "Group") { outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, attribute.Value)); } } outputIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name)); return outputIdentity; }
protected override Microsoft.IdentityModel.Claims.IClaimsIdentity GetOutputClaimsIdentity(Microsoft.IdentityModel.Claims.IClaimsPrincipal principal, Microsoft.IdentityModel.Protocols.WSTrust.RequestSecurityToken request, Scope scope) { if (null == principal) { throw new InvalidRequestException("The caller's principal is null."); } // Get the incoming IClaimsIdentity from IPrincipal IClaimsIdentity callerIdentity = (IClaimsIdentity)principal.Identity; // Create the output IClaimsIdentity IClaimsIdentity outputIdentity = new ClaimsIdentity(); // Create a name claim from the incoming identity. Claim nameClaim = new Claim(ClaimTypes.Name, callerIdentity.Name); // Create an 'Age' claim with a value of 25. In a real scenario, this may likely be looked up from a database. Claim ageClaim = new Claim("http://WindowsIdentityFoundationSamples/2008/05/AgeClaim", "25", ClaimValueTypes.Integer); // Add the name outputIdentity.Claims.Add(nameClaim); outputIdentity.Claims.Add(ageClaim); return outputIdentity; }