public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { return(Task.Factory.StartNew(() => { try { if (actionContext.Request.Headers.Contains(TransactionId)) { var values = actionContext.Request.Headers.GetValues(TransactionId); if (values != null && values.Any()) { byte[] transactionToken = Convert.FromBase64String(values.FirstOrDefault()); var transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(transactionToken); var transactionScope = new TransactionScope(transaction); actionContext.Request.Properties.Add(TransactionId, transactionScope); } } } catch (Exception ex) { _logService.LogMessage(ex); } })); }
private async Task <AuthenticationTicket> CreateAuthenticationTicket(IOwinContext owinContext, ClaimsIdentity oAuthIdentity) { ILogServiceAsync <ILogServiceSettings> logService = GlobalConfiguration.Configuration.DependencyResolver.GetService <ILogServiceAsync <ILogServiceSettings> >(); var sqlUserManager = owinContext.GetUserManager <ApplicationUserManager>(); var sqlUser = await sqlUserManager.FindByNameAsync(oAuthIdentity.Name); //http://www.c-sharpcorner.com/UploadFile/ff2f08/angularjs-enable-owin-refresh-tokens-using-asp-net-web-api/ var newIdentity = new ClaimsIdentity(oAuthIdentity); //SqlServerClaimsGenerator claimsGenerator = new SqlServerClaimsGenerator( // sqlUser, // oAuthIdentity, // owinContext.Get<RepoBase<SystemUser>>()); //claimsGenerator.GenerateClaims(); oAuthIdentity.AddClaim(new Claim("projectRequestRole", JsonConvert.SerializeObject(new SimpleRoleClaim { UserId = 2154, //_user.SystemUserID, DomainLogin = "******", //_user.DomainLogin.Trim(), UserName = "******", //_user.DomainLogin.Trim(), EmailAddress = "*****@*****.**", //_user.EmailAddress.Trim(), DepartmentDescription = "some dp des", //_user.DepartmentDescr, DepartmentId = 33, //_user.DepartmentID, IsActive = true, //_user.boolIsActive, Role = "user", //_user.AppRole }))); var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow; AuthenticationProperties properties = CreateProperties(sqlUser); AuthenticationTicket ticket = new AuthenticationTicket(newIdentity, properties); ticket.Properties.IssuedUtc = DateTime.UtcNow; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));//TODO: configure token expiration time in web config ticket.Properties.AllowRefresh = true; var principal = new ClaimsPrincipal(new[] { oAuthIdentity }); owinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); logService.LogMessage(new { type = "claimsRefreshed", endpoint = owinContext.Request.Uri, userName = oAuthIdentity.Name, data = new { orgUsers = principal.GetClaim <SimpleRoleClaim>("projectRequestRole"), } }); return(ticket); }
static void Main(string[] args) { ILogServiceAsync <LogServiceOptions> logService = LogServiceAsync <LogServiceOptions> .Instance; List <int> x = Enumerable.Repeat(1, 10000000).ToList(); int counter = 0; x.AsParallel().WithDegreeOfParallelism(100).ForAll(item => { logService.LogMessage(new { messag = String.Format("Loop count: {0}", counter++) }); }); }
public virtual async Task <TApiModel> GetAsync(string endpointFormat, params string[] urlParameters) { var requestId = Guid.NewGuid().ToString(); var endpoint = String.Format(endpointFormat, urlParameters).Replace(" ", "-"); var client = await GetClient(); var result = await client.GetAsync(String.Format("{0}/{1}", _settings.IisAppName, endpoint)).ContinueWith <Task <TApiModel> >(async response => { if (response.Result.IsSuccessStatusCode) { var deserializedResult = response.Result.Content.ReadAsAsync <TApiModel>(); var serializedResult = await response.Result.Content.ReadAsStringAsync(); return(await deserializedResult); } return(await Task.FromResult <TApiModel>(default(TApiModel))); }); var resposne = await result; _logService.LogMessage(new { type = "endpointClient", msg = "GetAllAsync", data = new { endpoint, settings = _settings, request = new { defaultRequestHeaders = client.DefaultRequestHeaders.ToList(), }, resposne, }, }); return(resposne); }
public async Task <bool> LoginAsync() { await RefreshTokenAsync(); var client = await GetClient(); var endpoint = String.Format("{0}/{1}", Settings.IisAppName, Settings.TokenEndpoint); var postData = new StringContent(String.Format("grant_type=password&username={0}&password={1}", Settings.Username, Settings.Password)); client.BaseAddress = new Uri(Settings.BaseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _logService.LogMessage(new { msg = "wtf", type = "authenticationclient", data = new { endpoint, postData = String.Format("grant_type=password&username={0}&password={1}", Settings.Username, Settings.Password), client.BaseAddress, client.DefaultRequestHeaders, } }); var response = await client.PostAsync(endpoint, postData); _logService.LogMessage(new { msg = "response retrieved", type = "authenticationclient", data = new { endpoint, } }); if (!response.IsSuccessStatusCode) { _logService.LogMessage(new { type = "authenticationclient", clientType = _logService.GetType().FullName, msg = "LoginAsync failed", data = new { request = new { response.RequestMessage.RequestUri, response.RequestMessage.Headers, response.RequestMessage.Method, response.RequestMessage.Properties, }, response = new { response.ReasonPhrase, response.Headers, response.IsSuccessStatusCode, response.StatusCode, response.Version, }, settings = Settings, } }); return(false); } var resultContent = await response.Content.ReadAsStringAsync(); Settings.BearerToken = JsonConvert.DeserializeObject <TokenModel>(resultContent); _logService.LogMessage(new { type = "authenticationclient", clientType = _logService.GetType().FullName, msg = "token endpoint called", data = new { request = new { response.RequestMessage.RequestUri, response.RequestMessage.Headers, response.RequestMessage.Method, response.RequestMessage.Properties, }, response = new { body = resultContent, response.ReasonPhrase, response.Headers, response.IsSuccessStatusCode, response.StatusCode, response.Version, }, settings = Settings, } }); if (Settings.BearerToken == null) { return(false); } _logService.LogMessage(new { type = "authenticationclient", clientType = _logService.GetType().FullName, msg = "token retrieved", data = Settings, }); return(true); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { ILogServiceAsync <ILogServiceSettings> logService = GlobalConfiguration.Configuration.DependencyResolver.GetService <ILogServiceAsync <ILogServiceSettings> >(); var sqlUserManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); var sqlUser = await sqlUserManager.FindAsync(context.UserName, context.Password); if (sqlUser == null || !sqlUser.IsActive) { context.SetError("invalid_grant", "The user name or password is incorrect."); logService.LogMessage(new { type = "claimsGenerated", endpoint = context.Request.Uri, userName = context.UserName, data = new { message = "invalid_grant The user name or password is incorrect", } }); return; } ClaimsIdentity oAuthIdentity = await sqlUser.GenerateUserIdentityAsync(sqlUserManager, OAuthDefaults.AuthenticationType); //ClaimsGenerator claimsGenerator = new ClaimsGenerator( // sqlUser, // oAuthIdentity, // context.OwinContext.Get<RepoBase<SystemUser>>()); //claimsGenerator.GenerateClaims(); //claims generator is the same as this: oAuthIdentity.AddClaim(new Claim("projectRequestRole", JsonConvert.SerializeObject(new SimpleRoleClaim { UserId = 2154, //_user.SystemUserID, DomainLogin = "******", //_user.DomainLogin.Trim(), UserName = "******", //_user.DomainLogin.Trim(), EmailAddress = "*****@*****.**", //_user.EmailAddress.Trim(), DepartmentDescription = "some dp des", //_user.DepartmentDescr, DepartmentId = 33, //_user.DepartmentID, IsActive = true, //_user.boolIsActive, Role = "user", //_user.AppRole }))); ClaimsIdentity cookiesIdentity = await sqlUser.GenerateUserIdentityAsync(sqlUserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(sqlUser); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); ticket.Properties.AllowRefresh = true; context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); //TODO: Document this /*http://stackoverflow.com/questions/21971190/asp-net-web-api-2-owin-authentication-unsuported-grant-type/21979279#21979279 ********************************* * it wasn't enough adding config.EnableCors(new EnableCorsAttribute("*", "*", "*")); to WebApiConfig.cs * or the controllers. example: * [EnableCors(origins: "*", headers: "*", methods: "*")] * public class ValuesController : ApiController */ var principal = new ClaimsPrincipal(new[] { oAuthIdentity }); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); logService.LogMessage(new { type = "claimsGenerated", endpoint = context.Request.Uri, userName = context.UserName, data = new { orgUsers = principal.GetClaim <SimpleRoleClaim>("projectRequestRole"), } }); }