public ActionResult Register() { if (Request.IsAuthenticated) { using (var client = new HttpClient()) { BootstrapContext bc = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext; JWTSecurityToken jwt = bc.SecurityToken as JWTSecurityToken; string rawToken = jwt.RawData; string api = ConfigurationManager.AppSettings["fa:APIEndPoint"]; client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + rawToken); var productDetailUrl = new Uri(api + "customer/5"); var model = client .GetAsync(productDetailUrl) .Result .Content.ReadAsAsync <Customer>().Result; //ViewBag.role = model.Email; return(View()); } } else { ViewBag.MetaDataScript = ConfigurationManager.AppSettings["fa:LoginProviders"]; return(View("~/Views/Account/Login.cshtml")); } }
public void Pop_Ok() { var obj = new BootstrapContext(viewContext, null, null, null); var obj1 = new Class1(); var obj2 = new Class2(); var obj3 = new Class1(); obj.Push(obj1); obj.Push(obj2); obj.Push(obj3); // this throws error try { obj.PopIfEqual(obj2); Assert.True(false, "Should not got there :("); } catch (ArgumentException) { // It,s Ok } // obj3 is still at last positon obj.PopIfEqual(obj3); // and now can POP obj2 obj.PopIfEqual(obj2); // and obj1 is last one obj.PopIfEqual(obj1); // nothing more Assert.Null(obj.PeekNearest <object>()); }
public void Pop_Ok() { var obj = new BootstrapContext(viewContext, null, null, null); var obj1 = new Class1(); var obj2 = new Class2(); var obj3 = new Class1(); obj.Push(obj1); obj.Push(obj2); obj.Push(obj3); // this throws error try { obj.PopIfEqual(obj2); Assert.True(false, "Should not got there :("); } catch (ArgumentException) { // It,s Ok } // obj3 is still at last positon obj.PopIfEqual(obj3); // and now can POP obj2 obj.PopIfEqual(obj2); // and obj1 is last one obj.PopIfEqual(obj1); // nothing more Assert.Null(obj.PeekNearest<object>()); }
// RA-Lifecycle /////////////////////////////////////////////////// //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void start(javax.resource.spi.BootstrapContext ctx) throws javax.resource.spi.ResourceAdapterInternalException public virtual void start(BootstrapContext ctx) { try { Type.GetType(ORG_CAMUNDA_BPM_ENGINE_PROCESS_ENGINE); } catch (Exception) { log.info("ProcessEngine classes not found in shared libraries. Not initializing camunda Platform JobExecutor Resource Adapter."); return; } // initialize the ExecutorService (CommonJ or JCA, depending on configuration) if (isUseCommonJWorkManager.Value) { if (!string.ReferenceEquals(commonJWorkManagerName, null) & commonJWorkManagerName.Length > 0) { executorServiceWrapper.ExecutorService = new CommonJWorkManagerExecutorService(this, commonJWorkManagerName); } else { throw new Exception("Resource Adapter configuration property 'isUseCommonJWorkManager' is set to true but 'commonJWorkManagerName' is not provided."); } } else { executorServiceWrapper.ExecutorService = new JcaWorkManagerExecutorService(this, ctx.WorkManager); } log.log(Level.INFO, "camunda BPM executor service started."); }
private SecurityToken GetActAsToken(BootstrapContext context) { string stsAddress = "https://identity.thinktecture.com/idsrvsample/issue/wstrust/mixed/username"; string realm = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Realm; var factory = new WSTrustChannelFactory( new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(stsAddress)); factory.TrustVersion = TrustVersion.WSTrust13; factory.Credentials.UserName.UserName = "******"; factory.Credentials.UserName.Password = "******"; var rst = new RequestSecurityToken { AppliesTo = new EndpointReference(realm), RequestType = RequestTypes.Issue, KeyType = KeyTypes.Bearer, ActAs = new SecurityTokenElement(context.SecurityToken) }; var channel = factory.CreateChannel(); var delegationToken = channel.Issue(rst); return(delegationToken); }
public HttpResponseMessage SignInCallBack(string callback) { diagnostics.WriteInformationTrace(TraceEventId.InboundParameters, "Client callback uri:{0}", callback); ClaimsPrincipal principal = this.User as ClaimsPrincipal; BootstrapContext context = principal.Identities.First().BootstrapContext as BootstrapContext; JWTSecurityToken jwtToken = context.SecurityToken as JWTSecurityToken; UriBuilder builder = new UriBuilder(new Uri(callback)); TimeSpan span = jwtToken.ValidTo.Subtract(jwtToken.ValidFrom); double seconds = span.TotalSeconds; string queryparam = string.Format("{0}={1}&{2}={3}", Constants.JWTCOOKIETOKEN_PARAM, HttpUtility.UrlEncode(jwtToken.RawData), Constants.JWTCOOKIETOKEN_VALIDTO_PARAM, HttpUtility.UrlEncode(seconds.ToString())); builder.Query = queryparam; var response = Request.CreateResponse(HttpStatusCode.Moved); response.Headers.Location = builder.Uri; diagnostics.WriteVerboseTrace(TraceEventId.OutboundParameters, "Redirect Uri post authentication process:{0}", response.Headers.Location); return(response); }
public ChangeEvent Create(BootstrapContext db, string createdByUserIdCode = null) { var updatedByUserIdCode = createdByUserIdCode; var deletedByUserIdCode = createdByUserIdCode; return(Create(db, DateTime.UtcNow, DateTime.UtcNow, null, createdByUserIdCode, updatedByUserIdCode, deletedByUserIdCode)); }
private SecurityToken GetActAsToken() { // Retrieve the token that was saved during initial user login BootstrapContext bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext; // Use the Thinktecture-implementation of the UserNameWSBinding to setup the channel factory to ADFS var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential); var factory = new WSTrustChannelFactory(binding, new EndpointAddress("https://[ADFS]/adfs/services/trust/13/usernamemixed")); // For demo purposes, we're authenticating to ADFS using a user name and password representing the web application // If the web server is domain-joined, you can use Windows Authentication instead factory.Credentials.UserName.UserName = "******"; factory.Credentials.UserName.Password = "******"; factory.TrustVersion = TrustVersion.WSTrust13; // Setup the request details to ask for a token for the backend service, acting as the logged in user var request = new RequestSecurityToken(); request.RequestType = Thinktecture.IdentityModel.Constants.WSTrust13Constants.RequestTypes.Issue; request.AppliesTo = new EndpointReference("https://[BackendService]/Service.svc"); request.ActAs = new SecurityTokenElement(bootstrapContext.SecurityToken); // Create the channel var channel = factory.CreateChannel(); RequestSecurityTokenResponse response = null; SecurityToken delegatedToken = channel.Issue(request, out response); // Return the acquired token return(delegatedToken); }
private void DisplayReceivedToken(ClaimsPrincipal claimsPrincipal) { ClaimsIdentity identity = claimsPrincipal.Identity as ClaimsIdentity; BootstrapContext bootstrapContext = identity.BootstrapContext as BootstrapContext; this.tokenStringLabel.Text += bootstrapContext.Token; this.tokenStringLabel.Visible = true; }
public static void SetBootstrapToken(BootstrapContext bootstrapToken) { if (bootstrapToken.IsNull()) { return; } ContainerFactory.Current.Bind(typeof(BootstrapContext), bootstrapToken, Scope.Context); }
protected virtual void Configure(IModuleContext <TModule> moduleContext, IApplicationBuilder app) { Filters.BuildFilterPipeline( BootstrapContext.Advanced.FrameworkServices.GetServices <IWebModuleConfigureFilter>(), (ctx, appBuilder) => { ModuleMethodInvoker.CallOptionalMethod(BootstrapContext.ToModuleContext(app.ApplicationServices), "Configure", appBuilder); })(moduleContext, app); }
public virtual JsonResult GetPictures(string path) { path = NormalizePath(path); if (AuthorizeRead(path)) { try { directoryBrowser.Server = Server; var result = new List <SimpleCMS.Models.KendoEditor.FileBrowserEntry>(); using (var db = new BootstrapContext()) { var images = db.Images; var imagesFiltered = images.FilterDeleted().ToList(); var imagesSelected = imagesFiltered.Select(m => new { name = m.File != null ? m.File.Name : string.Empty, size = m.File != null ? m.File.Length : -1 }); foreach (var image in imagesSelected) { var filePath = Path.Combine(Server.MapPath(path), image.name); if (System.IO.File.Exists(filePath)) { result.Add(new SimpleCMS.Models.KendoEditor.FileBrowserEntry() { Name = image.name, Size = image.size, Type = EntryType.File }); } } } return(Json(result.Select(m => new { name = m.Name, size = m.Size, type = "f" }), JsonRequestBehavior.AllowGet)); //var result = directoryBrowser // .GetContent(path, DefaultFilter) // .Select(f => new // { // name = f.Name, // type = f.Type == EntryType.File ? "f" : "d", // size = f.Size // }); //return Json(result, JsonRequestBehavior.AllowGet); } catch (DirectoryNotFoundException) { throw new HttpException(404, "File Not Found"); } } throw new HttpException(403, "Forbidden"); }
public void Ctor_StringToken_Works() { BootstrapContext bootstrapContext = new BootstrapContext("token"); Assert.AreEqual("token", bootstrapContext.Token, "#1"); Assert.IsNull(bootstrapContext.TokenBytes, "#2"); Assert.IsNull(bootstrapContext.SecurityToken, "#3"); Assert.IsNull(bootstrapContext.SecurityTokenHandler, "#4"); }
private static string GetTokenAsXml(BootstrapContext bootstrapContext) { var builder = new StringBuilder(); using (var writer = XmlWriter.Create(builder)) { new Saml2SecurityTokenHandler(new SamlSecurityTokenRequirement()).WriteToken(writer, bootstrapContext.SecurityToken); } return(builder.ToString()); }
public MasterDataClient(string serviceName, BootstrapContext token = null) { Tracer = TracerFactory.StartTracer(this, "ctor"); var runtime = RuntimeFactory.CreateRuntime(); Container = runtime.CreateServiceProxy <IMasterDataManagementService>(serviceName); if (token.IsInstance()) { Container.Initialize(token); } }
public static SecurityToken GetTokenForActasWithCertificate(BootstrapContext token) { var securityToken = WsTrustClient.RequestSecurityTokenWithX509( Constants.StsAddressCertificate, Constants.StsCertificate, Constants.PocServiceAddress, Constants.GetPocClientCertificate(),//KmdProveopgave, EnsureBootstrapSecurityToken(token)); return(securityToken); }
public void Ctor_ByteArrayToken_Works() { BootstrapContext bootstrapContext = new BootstrapContext(new byte [] { 0x01 }); Assert.IsNotNull(bootstrapContext.TokenBytes, "#1"); Assert.AreEqual(1, bootstrapContext.TokenBytes.Length, "#2"); Assert.AreEqual(1, bootstrapContext.TokenBytes [0], "#3"); Assert.IsNull(bootstrapContext.Token, "#4"); Assert.IsNull(bootstrapContext.SecurityToken, "#5"); Assert.IsNull(bootstrapContext.SecurityTokenHandler, "#6"); }
public ChangeEvent Delete(BootstrapContext db, int?id) { ChangeEvent changeEvent = Get(db, id); if (changeEvent != null) { changeEvent.DeletedOn = DateTime.UtcNow; changeEvent.DeletedByUserIdCode = this._userIdCode; db.Entry(changeEvent).State = System.Data.Entity.EntityState.Modified; } return(changeEvent); }
public void PeekNearest_Ok() { var obj = new BootstrapContext(viewContext, null, null, null); var obj1 = new Class1(); var obj2 = new Class2(); var obj3 = new Class1(); obj.Push(obj1); obj.Push(obj2); obj.Push(obj3); Assert.Same(obj2, obj.PeekNearest <Class2>()); }
public void Deserialize_StringToken_Works() { BinaryFormatter binaryFormatter = new BinaryFormatter(); using (var s = new MemoryStream(SerializedBootstrapContextString)) { BootstrapContext bootstrapContext = binaryFormatter.Deserialize(s) as BootstrapContext; Assert.IsNotNull(bootstrapContext, "#1"); Assert.AreEqual("token", bootstrapContext.Token, "#2"); Assert.IsNull(bootstrapContext.TokenBytes, "#3"); Assert.IsNull(bootstrapContext.SecurityToken, "#4"); Assert.IsNull(bootstrapContext.SecurityTokenHandler, "#5"); } }
public void PeekNearest_Ok() { var obj = new BootstrapContext(viewContext, null, null, null); var obj1 = new Class1(); var obj2 = new Class2(); var obj3 = new Class1(); obj.Push(obj1); obj.Push(obj2); obj.Push(obj3); Assert.Same(obj2, obj.PeekNearest<Class2>()); }
/// <summary> /// Validates the token using the wrapped token handler and generates IAuthorizationPolicy /// wrapping the returned ClaimsIdentities. /// </summary> /// <param name="token">Token to be validated.</param> /// <returns>Read-only collection of IAuthorizationPolicy</returns> protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token) { ReadOnlyCollection <ClaimsIdentity> identities = null; try { identities = _wrappedX509SecurityTokenHandler.ValidateToken(token); } catch (Exception ex) { if (!_exceptionMapper.HandleSecurityTokenProcessingException(ex)) { throw; } } // tlsnego will dispose of the x509, when we write out the bootstrap we will get a dispose error. bool shouldSaveBootstrapContext = SecurityTokenHandlerConfiguration.DefaultSaveBootstrapContext; if (_wrappedX509SecurityTokenHandler.Configuration != null) { shouldSaveBootstrapContext = _wrappedX509SecurityTokenHandler.Configuration.SaveBootstrapContext; } if (shouldSaveBootstrapContext) { X509SecurityToken x509Token = token as X509SecurityToken; SecurityToken tokenToCache; if (x509Token != null) { tokenToCache = new X509SecurityToken(x509Token.Certificate); } else { tokenToCache = token; } BootstrapContext bootstrapContext = new BootstrapContext(tokenToCache, _wrappedX509SecurityTokenHandler); foreach (ClaimsIdentity identity in identities) { identity.BootstrapContext = bootstrapContext; } } List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1); policies.Add(new AuthorizationPolicy(identities)); return(policies.AsReadOnly()); }
private static SecurityToken EnsureBootstrapSecurityToken(BootstrapContext bootstrapContext) { if (bootstrapContext.SecurityToken != null) { return(bootstrapContext.SecurityToken); } if (string.IsNullOrWhiteSpace(bootstrapContext.Token)) { return(null); } var handlers = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers; return(handlers.ReadToken(new XmlTextReader(new StringReader(bootstrapContext.Token)))); }
public static bool AreEqual(BootstrapContext bc1, BootstrapContext bc2) { if (bc1 == null && bc2 == null) { return(true); } if (bc1 == null || bc2 == null) { return(false); } if (bc1.SecurityToken == null && bc2.SecurityToken != null) { return(false); } if (bc1.SecurityToken != null && bc2.SecurityToken == null) { return(false); } if (bc1.SecurityToken != null && bc2.SecurityToken != null) { if (bc1.SecurityToken.GetType() != bc2.SecurityToken.GetType()) { return(false); } } if (bc1.Token == null && bc2.Token != null) { return(false); } if (bc1.Token != null && bc2.Token == null) { return(false); } if (bc1.Token != null && bc2.Token != null) { if (bc1.Token.GetType() != bc2.Token.GetType()) { return(false); } } return(true); }
public void Ctor_SecurityToken_Works() { var securityToken = new UserNameSecurityToken(user, password); var securityTokenHandler = new SimpleSecurityTokenHandler(); BootstrapContext bootstrapContext = new BootstrapContext(securityToken, securityTokenHandler); Assert.IsNotNull(bootstrapContext.SecurityToken, "#1"); Assert.AreEqual(user, securityToken.UserName, "#2"); Assert.AreEqual(password, securityToken.Password, "#3"); Assert.AreEqual(securityTokenHandler, bootstrapContext.SecurityTokenHandler, "#4"); Assert.IsNull(bootstrapContext.Token, "#5"); Assert.IsNull(bootstrapContext.TokenBytes, "#6"); }
private static bool AreBootstrapContextsEqual(BootstrapContext bc1, BootstrapContext bc2, CompareContext context) { if (!AreEqual <SecurityToken>(bc1.SecurityToken, bc2.SecurityToken, context, AreSecurityTokensEqual)) { return(false); } if (!AreEqual <string>(bc1.Token, bc2.Token, context, AreStringsEqual)) { return(false); } return(true); }
public static SecurityToken GetTokenFromBootstrapContext(BootstrapContext bootstrapContext) { if (null != bootstrapContext?.SecurityToken) { return(bootstrapContext.SecurityToken as SecurityToken); } if (!string.IsNullOrWhiteSpace(bootstrapContext?.Token)) { return(GetTokenFromXml(bootstrapContext.Token)); } return(null); }
public ChangeEvent Create(BootstrapContext db, DateTime?_createdOn, DateTime?_updatedOn, DateTime?_deletedOn = null, string createdByUserIdCode = null, string updatedByUserIdCode = null, string deletedByUserIdCode = null) { var changeEvent = new ChangeEvent() { CreatedOn = _createdOn.HasValue ? _createdOn.Value : DateTime.Now, UpdatedOn = _updatedOn.HasValue ? _updatedOn.Value : DateTime.Now, DeletedOn = _deletedOn, CreatedByUserIdCode = !String.IsNullOrEmpty(createdByUserIdCode) ? createdByUserIdCode : this._userIdCode, DeletedByUserIdCode = deletedByUserIdCode, UpdatedByUserIdCode = !String.IsNullOrEmpty(updatedByUserIdCode) ? updatedByUserIdCode : this._userIdCode, }; return(changeEvent); }
public void Deserialize_ByteArrayToken_Works() { BinaryFormatter binaryFormatter = new BinaryFormatter(); using (var s = new MemoryStream(SerializedBootstrapContextByteArray)) { BootstrapContext bootstrapContext = binaryFormatter.Deserialize(s) as BootstrapContext; Assert.IsNotNull(bootstrapContext, "#1"); Assert.IsNotNull(bootstrapContext.TokenBytes, "#2"); Assert.AreEqual(1, bootstrapContext.TokenBytes.Length, "#3"); Assert.AreEqual(1, bootstrapContext.TokenBytes [0], "#4"); Assert.IsNull(bootstrapContext.Token, "#5"); Assert.IsNull(bootstrapContext.SecurityToken, "#6"); Assert.IsNull(bootstrapContext.SecurityTokenHandler, "#7"); } }
public ChangeEvent Update(BootstrapContext db, int?changeEventId) { ChangeEvent changeEvent = Get(db, changeEventId); if (changeEvent == null) { changeEvent = Create(db); } else { changeEvent.UpdatedOn = DateTime.UtcNow; changeEvent.UpdatedByUserIdCode = this._userIdCode; db.Entry(changeEvent).State = System.Data.Entity.EntityState.Modified; } return(changeEvent); }
public void Serialize_StringToken_Works() { BootstrapContext bootstrapContext = new BootstrapContext("token"); BinaryFormatter binaryFormatter = new BinaryFormatter(); using (var s = new MemoryStream()) { binaryFormatter.Serialize(s, bootstrapContext); s.Position = 0; BootstrapContext bootstrapContext2 = binaryFormatter.Deserialize(s) as BootstrapContext; Assert.IsNotNull(bootstrapContext2, "#1"); Assert.AreEqual(bootstrapContext.Token, bootstrapContext2.Token, "#2"); Assert.AreEqual(bootstrapContext.TokenBytes, bootstrapContext2.TokenBytes, "#3"); Assert.AreEqual(bootstrapContext.SecurityToken, bootstrapContext2.SecurityToken, "#4"); Assert.AreEqual(bootstrapContext.SecurityTokenHandler, bootstrapContext2.SecurityTokenHandler, "#5"); } }
// GET: JWT2SAMLTransition public async Task <JWT2SAMLTransition> Get() { BootstrapContext bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext; string accessToken = bootstrapContext.Token; using (HttpClient azureADTokenClient = new HttpClient()) { string azureADTokenEndpoint = string.Format("https://login.microsoftonline.com/{0}/oauth2/token", ConfigurationManager.AppSettings["ida:Tenant"]); HttpResponseMessage response = await azureADTokenClient.PostAsync(azureADTokenEndpoint, new FormUrlEncodedContent( new Dictionary <string, string> { { "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer" }, { "assertion", accessToken }, // #access token is scoped to api manager service { "client_id", ConfigurationManager.AppSettings["ida:Audience"] }, // #api manager service { "client_secret", ConfigurationManager.AppSettings["ida:ClientSecret"] }, // #api manager client secret { "resource", ConfigurationManager.AppSettings["ida:BackEndAPIResource"] }, // #Backend api -- SAML App Entity ID { "requested_token_use", "on_behalf_of" }, { "requested_token_type", "urn:ietf:params:oauth:token-type:saml2" } } )); string responseContentString = await response.Content.ReadAsStringAsync(); OnBehalfOfTokenResponse tokenResponse = JsonConvert.DeserializeObject <OnBehalfOfTokenResponse>(responseContentString); JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler(); string decodedJwt = jwtHandler.ReadToken(accessToken).ToString(); string encodedSamlToken = tokenResponse.AccessToken; //Adjust format in the SAML token, which comes as JSON Base64 //Learn more: https://jb64.org/specification/ string adjustedFormat = encodedSamlToken.Replace("_", "/").Replace("-", "+"); adjustedFormat = adjustedFormat.PadRight(adjustedFormat.Length + (4 - adjustedFormat.Length % 4) % 4, '='); string decodedSamlToken = Encoding.UTF8.GetString(Convert.FromBase64String(adjustedFormat)); //NOTE: for this example, we are returning the SAML token for debugging/demo purposes. //The actual scenario in production should be to have the frontend interacting with the backend //via Service-To-Service (S2S). return(new JWT2SAMLTransition { JWT = accessToken, SAMLToken = encodedSamlToken, DecodedSAMLToken = decodedSamlToken }); } }