public IActionResult DecryptCookie() { ViewData["Message"] = "This is the decrypt page"; var user = HttpContext.User; //User will be set to the ClaimsPrincipal //Get the encrypted cookie value string cookieValue = HttpContext.Request.Cookies["gicoOAU"]; IDataProtectionProvider provider = HttpContext.RequestServices.GetService <IDataProtectionProvider>(); //Get a data protector to use with either approach var dataProtector = provider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2"); //Get the decrypted cookie as plain text UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookieValue); byte[] plainBytes = dataProtector.Unprotect(protectedBytes); string plainText = specialUtf8Encoding.GetString(plainBytes); //Get teh decrypted cookies as a Authentication Ticket TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtector); AuthenticationTicket ticket = ticketDataFormat.Unprotect(cookieValue); return(Content("111")); }
protected void Init() { clients = TestClients.Get(); var clientStore = new InMemoryClientStore(clients); var scopeStore = new InMemoryScopeStore(TestScopes.Get()); var factory = new IdentityServerServiceFactory { ScopeStore = Registration.RegisterFactory <IScopeStore>(() => scopeStore), ClientStore = Registration.RegisterFactory <IClientStore>(() => clientStore) }; server = TestServer.Create(app => { appBuilder = app; mockUserService = new Mock <InMemoryUserService>(TestUsers.Get()); mockUserService.CallBase = true; factory.UserService = Registration.RegisterFactory <IUserService>(() => mockUserService.Object); options = TestIdentityServerOptions.Create(); options.Factory = factory; options.AuthenticationOptions.IdentityProviders = OverrideIdentityProviderConfiguration ?? ConfigureAdditionalIdentityProviders; protector = options.DataProtector; app.UseIdentityServer(options); ticketFormatter = new TicketDataFormat( new DataProtectorAdapter(protector, options.AuthenticationOptions.CookieOptions.Prefix + Constants.PartialSignInAuthenticationType)); }); client = server.HttpClient; }
public static AuthenticationTicket GetCookieAuthenticationTicket(this HttpContext context, CookieAuthenticationOptions options) { try { //Get the encrypted cookie value string cookieValue = context.Request.Cookies[".AspNetCore.CookieAuth"]; //Get a data protector to use with either approach var dataProtector = options.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "CookieAuth", "v2"); //Get the decrypted cookie as plain text UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookieValue); byte[] plainBytes = dataProtector.Unprotect(protectedBytes); string plainText = specialUtf8Encoding.GetString(plainBytes); //Get the decrypted cookie as a Authentication Ticket TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtector); AuthenticationTicket ticket = ticketDataFormat.Unprotect(cookieValue); return(ticket); } catch (Exception) { return(null); } }
private Tuple <Token, User> GenerateToken(User user) { var secureDataFormat = new TicketDataFormat(_dataProtector); var expirationDate = DateTimeOffset.UtcNow.AddDays(1); var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType); identity.AddClaims(user.GetClaims()); var tokenValue = secureDataFormat.Protect(new AuthenticationTicket(identity, new AuthenticationProperties() { IssuedUtc = DateTime.UtcNow, ExpiresUtc = expirationDate })); var token = new Token() { AccessToken = tokenValue, TokenType = OAuthDefaults.AuthenticationType, ExpiresAt = expirationDate, ExpiresIn = (uint)(expirationDate - DateTime.UtcNow).TotalSeconds }; return(Tuple.Create(token, user)); }
private async Task <string> GetCookie() { await CreateNewUser(); if (NewUser == null) { return(null); } var authenticationMethod = NewUser.Logins.FirstOrDefault()?.LoginProvider ?? "Google"; var claims = new[] { new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", NewUser.Id.ToString()), new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", NewUser.UserName), new Claim("AspNet.Identity.SecurityStamp", NewUser.SecurityStamp), new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", authenticationMethod) }; const string cookieSchema = "Identity.Application"; var myService = TestServer.Host.Services.GetRequiredService <IOptionsMonitor <CookieAuthenticationOptions> >(); var dataProtector = myService.CurrentValue.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", cookieSchema, "v2"); var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, cookieSchema)); var ticket = new AuthenticationTicket(principal, cookieSchema); var ticketDataFormat = new TicketDataFormat(dataProtector); var cookie = ticketDataFormat.Protect(ticket); return(cookie); }
private ISecureDataFormat <AuthenticationTicket> CreateProtector() { IDataProtector protector = _dataProtectionProvider.CreateProtector(Options.CookingSettings.SecretKey); ISecureDataFormat <AuthenticationTicket> ticketDataFormat = new TicketDataFormat(protector); return(ticketDataFormat); }
public ActionResult Index() { var accessToken = Request.Form["AccessToken"] ?? ""; var refreshToken = Request.Form["RefreshToken"] ?? ""; InitializeWebServerClient(); if (string.IsNullOrEmpty(accessToken)) { var authorizationState = _webServerClient.ProcessUserAuthorization(Request); if (authorizationState != null) { var secureDataFormat = new TicketDataFormat(new MachineKeyProtector()); AuthenticationTicket ticket = secureDataFormat.Unprotect(authorizationState.AccessToken); var identity = ticket != null ? ticket.Identity : null; // Add the cookie to the request to save it HttpCookie cookie = new HttpCookie("CWAuthToken", authorizationState.AccessToken); cookie.HttpOnly = true; HttpContext.Response.Cookies.Add(cookie); Response.Cookies.Add(cookie); FormsAuthentication.SetAuthCookie(identity.Name, false); return(RedirectToAction("index", "admin")); } Response.Cookies["CWAuthToken"].Expires = DateTime.Now.AddDays(-1); return(RedirectToAction("Index", "Home")); } return(View()); }
public string GetUserIdFromTicket(string tiket) { var secureDataFormat = new TicketDataFormat(new MachineKeyProtector()); AuthenticationTicket ticketContent = secureDataFormat.Unprotect(tiket); return(ticketContent.Identity.Name); }
/// <summary> /// 解密 /// </summary> /// <param name="httpContext">Http内容</param> /// <param name="cookieSchema">原加密的架构</param> /// <param name="CookieName">Cookie名称</param> /// <returns></returns> public static AuthenticationTicket Decrypt(HttpContext httpContext, string cookieSchema = "Identity.Application", string cookieName = ".AspNetCore.Identity.Application") { // Get the encrypted cookie value var CookieOpt = httpContext.RequestServices.GetRequiredService <Microsoft.Extensions.Options.IOptionsMonitor <CookieAuthenticationOptions> >(); var CookieOptVal = CookieOpt?.CurrentValue; var cookieManager = CookieOptVal?.CookieManager ?? new ChunkingCookieManager(); var cookie = cookieManager.GetRequestCookie(httpContext, cookieName); if (!string.IsNullOrWhiteSpace(cookie)) { ////自定义MachineKey或者其他密钥 数据保护提供者 //var provider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\")); var provider = CookieOptVal.DataProtectionProvider; var dataProtector = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", cookieSchema, "v2"); ////Get the decrypted cookie as plain text //UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); //byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookie); //byte[] plainBytes = dataProtector.Unprotect(protectedBytes); //string plainText = specialUtf8Encoding.GetString(plainBytes); //Get teh decrypted cookies as a Authentication Ticket TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtector); AuthenticationTicket ticket = ticketDataFormat.Unprotect(cookie); return(ticket); } else { return(null); } }
public String Test() { var accessToken = "2wtL7hU4pHVdblFMBpS4l1Kwn6RP5_l_8pTp3PGS7tb4qetsCcuRNDzWmcM1oEpIMprjAgbEDB6XZ8WI4Y0yUEm-e39B3Eqnee2XD59Bs6x2S6L3mwHU7CyP3lzZpL8HxRiqBlwk2rY83DyB_AF-itWFHCOtPAjfW0tBvWh-gZFekmhpYS5aTF16J4bD4EWZ-lo-Ma-L3OC4ep1R1xhWsuAYWDY-j_7zOYeEmAtbPJDt8iDqBQ4okL5aCYZBbIh26Km1CIGSEccWygM3I_-lwQ"; var secureDataFormat = new TicketDataFormat(new MachineKeyProtector()); AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken); return(""); }
public TicketDataFormatTokenValidator(IDataProtectionProvider dataProtectionProvider) { if (dataProtectionProvider == null) { dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer"); } _ticketDataFormat = new TicketDataFormat(dataProtectionProvider.CreateProtector("Access_Token", "v1")); }
public TicketDataFormatTokenValidator(IDataProtectionProvider dataProtectionProvider) { if (dataProtectionProvider == null) { dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer"); } _ticketDataFormat = new TicketDataFormat(dataProtectionProvider.CreateProtector("Access_Token", "v1")); }
private static ISecureDataFormat <AuthenticationTicket> GetTokenTicketFormat(IAppBuilder app) { var tokenDataProtector = app.CreateDataProtector( typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1"); var tokenTicketFormat = new TicketDataFormat(tokenDataProtector); return(tokenTicketFormat); }
public async Task <IActionResult> Index() { foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync()) { var handler1 = await _handlers.GetHandlerAsync(HttpContext, scheme.Name) as IAuthenticationRequestHandler; if (handler1 != null && await handler1.HandleRequestAsync()) { return(View()); } } var target = ResolveTarget(_options.CurrentValue.ForwardAuthenticate); var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync(); if (defaultAuthenticate != null) { var result = await HttpContext.AuthenticateAsync(defaultAuthenticate.Name); if (result?.Principal != null) { HttpContext.User = result.Principal; } } string cookieValue = HttpContext.Request.Cookies[".Aspnetcore.Identity.Application"]; var provider = _options.CurrentValue.DataProtectionProvider; //Get a data protector to use with either approach IDataProtector dataProtector = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2"); //Get the decrypted cookie as plain text UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookieValue); byte[] plainBytes = dataProtector.Unprotect(protectedBytes); string plainText = specialUtf8Encoding.GetString(plainBytes); //Get the decrypted cookie as a Authentication Ticket TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtector); AuthenticationTicket ticket = ticketDataFormat.Unprotect(cookieValue); //CookieAuthenticationHandler a; //a.AuthenticateAsync() //var result = (await handler.AuthenticateAsync()) ?? AuthenticateResult.NoResult(); //if (!result.Succeeded) //{ // return View(); //} //var options = _options.CurrentValue; //var cookie = options.CookieManager.GetRequestCookie(HttpContext, options.Cookie.Name!); var b = await ReadCookieTicket(); //var a = options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding()); return(View()); }
public MyHandler(IOptionsMonitor <ApiAuthenticationSchemeOption> options, IDataProtectionProvider dp, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { _logger = logger.CreateLogger("MyHandler"); if (dp == null) { return; } this._dataformat = new TicketDataFormat(dp.CreateProtector("APIAuthentication")); }
public ApiAuthenticationHandler(IOptionsMonitor <ApiAuthenticationOptions> options, UserManager <IdentityUser> userManager, IDataProtectionProvider dp, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { _log = logger.CreateLogger("ApiAuthenticationHandler"); if (dp == null) { return; } _format = new TicketDataFormat(dp.CreateProtector("APIAuthentication")); _userManager = userManager; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); var contentRoot = _hostingEnvironment.ContentRootPath; var keyRingPath = Path.GetFullPath(Path.Combine(contentRoot, "..", "AspNetInterop.KeyRing")); var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(keyRingPath)); var dataProtector = protectionProvider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookie", "v2"); var ticketFormat = new TicketDataFormat(dataProtector); services.AddIdentity <ApplicationUser, IdentityRole>(options => { options.Cookies = new IdentityCookieOptions { ApplicationCookie = new CookieAuthenticationOptions { AuthenticationScheme = "Cookie", CookieName = ".AspNet.SharedCookie", TicketDataFormat = ticketFormat, LoginPath = new PathString("/Account/Login/"), AccessDeniedPath = new PathString("/Error/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = true, // If you have subdomains use this config: CookieDomain = "localhost" } }; }) .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); services.AddAuthorization(options => { options.AddPolicy("CanWriteCustomerData", policy => policy.Requirements.Add(new ClaimRequirement("Customers", "Write"))); options.AddPolicy("CanAccessCustomerData", policy => policy.Requirements.Add(new ClaimRequirement("Customers", "Access"))); }); // Add application services. services.AddTransient <IEmailSender, AuthMessageSender>(); services.AddTransient <ISmsSender, AuthMessageSender>(); services.AddSingleton <IAuthorizationHandler, ClaimsRequirementHandler>(); }
private AuthenticationTicket UnProtecedData(string protectedText) { if (_dataFormat == null) { _dataFormat = CreateDataFormat(); } var ticket = _dataFormat.Unprotect(protectedText); return(ticket); }
public ClaimsIdentity GetIdentityFromToken(string token) { var secureDataFormat = new TicketDataFormat(_dataProtector); var data = secureDataFormat.Unprotect(token); if (null == data) { throw new UnauthorizedAccessException($"Cannot deserialize {token} data"); } return(data.Identity); }
private string ProtectedData(AuthenticationTokenCreateContext context) { if (_dataFormat == null) { _dataFormat = CreateDataFormat(); } var data = context.Ticket; var text = _dataFormat.Protect(data); return(text); }
public void Initialize(ITelemetry telemetry) { if (_httpContextAccessor.HttpContext == null) { return; } //if (!(telemetry is RequestTelemetry)) return; if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) { var principal = _httpContextAccessor.HttpContext.User; var userId = principal.FindFirst(ClaimTypes.NameIdentifier); telemetry.Context.User.Id = userId.Value; return; } // Get the encrypted cookie value var cookie = _httpContextAccessor.HttpContext.Request.Cookies[IdentityConstants.TwoFactorUserIdScheme]; // Decrypt if found if (!string.IsNullOrEmpty(cookie)) { try { if (_httpContextAccessor.HttpContext.RequestServices == null) { return; } var dataProtector = _httpContextAccessor.HttpContext.RequestServices.GetDataProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", IdentityConstants.TwoFactorUserIdScheme, "v2"); ////https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication.Cookies/PostConfigureCookieAuthenticationOptions.cs //var dataProtector = _dataProtectProvider.CreateProtector( // "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", // IdentityConstants.TwoFactorUserIdScheme, "v2"); var ticketDataFormat = new TicketDataFormat(dataProtector); var ticket = ticketDataFormat.Unprotect(cookie); var val = ticket?.Principal?.Claims?.FirstOrDefault(f => f.Type == ClaimTypes.Name); if (val != null) { telemetry.Context.User.Id = val.Value; //telemetry.Context.Session.Id = val.Value; } } catch (Exception) { //_logger.Value.TrackException(ex); // ignored } } }
public TicketDataFormatTokenValidator(IDataProtectionProvider dataProtectionProvider) { if (dataProtectionProvider == null) { #if DNXCORE50 dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer"); #else dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.Machine))).CreateProtector("OAuth.AspNet.AuthServer"); #endif } _ticketDataFormat = new TicketDataFormat(dataProtectionProvider.CreateProtector("Access_Token", "v1")); }
private static AuthenticationTicket GetAuthenticationKeyTicket() { AuthenticationTicket ticket = null; var ctx = HttpContext.Current.Request; if (ctx.Cookies != null && ctx.Cookies[".AspNet.Cookies"] != null) { var cookie = ctx.Cookies[".AspNet.Cookies"]; var secureDataFormat = new TicketDataFormat(new MachineKeyProtector()); ticket = secureDataFormat.Unprotect(cookie.Value); } return ticket; }
public TicketDataFormatTokenValidator(IDataProtectionProvider dataProtectionProvider) { if (dataProtectionProvider == null) { #if DNXCORE50 dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer"); #else dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.Machine))).CreateProtector("OAuth.AspNet.AuthServer"); #endif } _ticketDataFormat = new TicketDataFormat(dataProtectionProvider.CreateProtector("Access_Token", "v1")); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // We need to configure data protection to use a specific key directory // we can share between applications. // // We also need a common protector purpose, as different purposes are // automatically isolated from one another. // // Finally we need to wire up a common ticket formatter. // Normally you'd just have a hard coded, or configuration based path, // but for this demo we're going to share a directory in the solution directory, // so we have to do some jiggery-pokery to figure it out. string contentRoot = env.ContentRootPath; string keyRingPath = Path.GetFullPath(Path.Combine(contentRoot, "..", "idunno.KeyRing")); // Now we create a data protector, with a fixed purpose and sub-purpose used in key derivation. var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(keyRingPath)); var dataProtector = protectionProvider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookie", "v2"); // And finally create a new auth ticket formatter using the data protector. var ticketFormat = new TicketDataFormat(dataProtector); // Now configure the cookie options to have the same cookie name, and use // the common format. app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie", CookieName = ".AspNet.SharedCookie", TicketDataFormat = ticketFormat }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public string GetUserIdFromTicket(string tiket) { var secureDataFormat = new TicketDataFormat(new MachineKeyProtector()); AuthenticationTicket ticketContent = secureDataFormat.Unprotect(tiket); if (ticketContent != null) { Claim claim = ticketContent.Identity.FindFirst(t => t.Type == "sub"); return(claim.Value); } return(string.Empty); }
private static AuthenticationTicket GetAuthenticationKeyTicket() { AuthenticationTicket ticket = null; var ctx = HttpContext.Current.Request; if (ctx.Cookies != null && ctx.Cookies[".AspNet.Cookies"] != null) { var cookie = ctx.Cookies[".AspNet.Cookies"]; var secureDataFormat = new TicketDataFormat(new MachineKeyProtector()); ticket = secureDataFormat.Unprotect(cookie.Value); } return(ticket); }
public static System.Security.Claims.ClaimsIdentity GetUserIdentty() { HttpCookie authCookie = HttpContext.Current.Request.Cookies.Get("CWAuthToken"); if (authCookie != null) { var secureDataFormat = new TicketDataFormat(new MachineKeyProtector()); AuthenticationTicket ticket = secureDataFormat.Unprotect(authCookie.Value); var identity = ticket != null ? ticket.Identity : null; return(identity); } return(null); }
private IEnumerable <Claim> GetClaimFromCookie(HttpContext httpContext, string cookieName, string cookieSchema) { IOptionsMonitor <CookieAuthenticationOptions> opt = httpContext.RequestServices.GetRequiredService <IOptionsMonitor <CookieAuthenticationOptions> >(); string cookie = opt.CurrentValue.CookieManager.GetRequestCookie(httpContext, cookieName); if (!string.IsNullOrEmpty(cookie)) { IDataProtector dataProtector = opt.CurrentValue.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", cookieSchema, "v2"); TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtector); AuthenticationTicket ticket = ticketDataFormat.Unprotect(cookie); return(ticket.Principal.Claims); } return(null); }
public ActionResult Index() { var cookie = System.Web.HttpContext.Current.Request.Cookies.Get(".AspNet.ApplicationCookie"); var ticket = cookie.Value; //Handle encoding ticket = ticket.Replace('-', '+').Replace('_', '/'); var padding = 3 - ((ticket.Length + 3) % 4); if (padding != 0) { ticket = ticket + new string('=', padding); } var machineKeyProtector = new MachineKeyProtector(); var ticketData = new TicketDataFormat(machineKeyProtector); //Set the purpose for decrypting the cookie based ticket machineKeyProtector.Purpose = new string[] { typeof(CookieAuthenticationMiddleware).FullName, "ApplicationCookie", "v1" }; var decryptedTicket = ticketData.Unprotect(ticket); //Change the purpose for creating an encrypted bearer token machineKeyProtector.Purpose = new string[] { typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1" }; var encryptedTicket = ticketData.Protect(decryptedTicket); string bearerToken = $"Bearer {encryptedTicket}"; var client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:58719/"); client.DefaultRequestHeaders.Add("Authorization", bearerToken); var result = client.GetAsync("/api/ResourceData").Result.Content.ReadAsStringAsync().Result; ViewBag.ResultData = result; ViewBag.BearerToken = bearerToken; return(View()); }
/// <summary> /// <![CDATA[配置简化授权模式]]> /// </summary> /// <param name="app"></param> public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888 app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, AuthenticationType = "Brearer", Description = new Microsoft.Owin.Security.AuthenticationDescription() { }, Provider = new OAuthBearerAuthenticationProvider() { //http头中携带access_token时, OnRequestToken = (e) => { //解密令牌,生成身份票据 if (string.IsNullOrEmpty(e.Token) == false) { IDataProtector protector = app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1"); TicketDataFormat ticketDataFormat = new TicketDataFormat(protector); var ticket = ticketDataFormat.Unprotect(e.Token); e.Request.User = new ClaimsPrincipal(ticket.Identity); } return(Task.FromResult(0)); }, OnValidateIdentity = (e) => { if (e.Ticket != null) { e.Validated(); } return(Task.FromResult(0)); } } }); //认证服务中间件 app.UseOAuthAuthorizationServer(new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, AuthenticationType = "Bearer", AuthorizeEndpointPath = new PathString("/oauth2/Authorize"), TokenEndpointPath = new PathString("/oauth2/Token"), Provider = new ImpicitAuthorizationServerProvider(), AccessTokenExpireTimeSpan = new TimeSpan(2, 0, 0), }); }
public SqlAuthSessionStore(TicketDataFormat tdf, string cns = "AuthSessionStoreContext") { //Log.Info("ADFSAuth: Initializing SqlAuthSessionStore", this); _connectionString = cns; _formatter = tdf; if (_gcTimer == null) { _gcTimer = new Timer(900000); // 15 min _gcTimer.Elapsed += GarbageCollect; _gcTimer.Enabled = true; } if (_permStore == null) { _permStore = new SQLAuthSessionStoreContext(_connectionString); } }
// OWINで生成したアクセストークンを復号する // https://long2know.com/2015/05/decrypting-owin-authentication-ticket/ public bool Decrypt(string accessToken) { IDataProtector protector = null; if (this.Type == TokenType.AccessToken) { protector = new AccessTokenMachineKeyProtector(); } else if (this.Type == TokenType.RefreshToken) { protector = new RefreshTokenMachineKeyProtector(); } // Decrypt var secureDataFormat = new TicketDataFormat(protector); AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken); if (ticket == null) { return(false); } { var jstTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"); DateTimeIssued = System.TimeZoneInfo.ConvertTimeFromUtc(ticket.Properties.IssuedUtc.Value.DateTime, jstTimeZoneInfo); DateTimeExpires = System.TimeZoneInfo.ConvertTimeFromUtc(ticket.Properties.ExpiresUtc.Value.DateTime, jstTimeZoneInfo); } // get identity var identity = ticket.Identity as ClaimsIdentity; var roleClaims = identity.Claims.Where(x => x.Type == ClaimsIdentity.DefaultRoleClaimType).Select(x => x.Value).ToList(); var nonRoleClaims = identity.Claims.Where(x => x.Type != ClaimsIdentity.DefaultRoleClaimType).Select(x => new { Type = x.Type, Value = x.Value }).ToList(); IdentityName = identity.Name; Roles = roleClaims; Claims = new List <Claim>(); foreach (var c in nonRoleClaims) { var setc = new TokenDecrypt.Claim(); setc.Type = c.Type; setc.Value = c.Value; Claims.Add(setc); } return(true); }
private static void SetupAuth(IAppBuilder app, IKernel kernel) { var ticketDataFormat = new TicketDataFormat(kernel.Get<IDataProtector>()); var type = typeof(CookieAuthenticationOptions) .Assembly.GetType("Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware"); app.Use(type, app, new CookieAuthenticationOptions { LoginPath = new PathString("/account/login"), LogoutPath = new PathString("/account/logout"), CookieHttpOnly = true, AuthenticationType = Constants.JabbRAuthType, CookieName = "jabbr.id", ExpireTimeSpan = TimeSpan.FromDays(30), TicketDataFormat = ticketDataFormat, Provider = kernel.Get<ICookieAuthenticationProvider>() }); app.Use(typeof(CustomAuthHandler)); app.Use(typeof(WindowsPrincipalHandler)); //var config = new FederationConfiguration(loadConfig: false); //config.WsFederationConfiguration.Issuer = ""; //config.WsFederationConfiguration.Realm = "http://localhost:16207/"; //config.WsFederationConfiguration.Reply = "http://localhost:16207/wsfederation"; //var cbi = new ConfigurationBasedIssuerNameRegistry(); //cbi.AddTrustedIssuer("", ""); //config.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://localhost:16207/")); //config.IdentityConfiguration.IssuerNameRegistry = cbi; //config.IdentityConfiguration.CertificateValidationMode = X509CertificateValidationMode.None; //config.IdentityConfiguration.CertificateValidator = X509CertificateValidator.None; //app.UseFederationAuthentication(new FederationAuthenticationOptions //{ // ReturnPath = "/wsfederation", // SigninAsAuthenticationType = Constants.JabbRAuthType, // FederationConfiguration = config, // Provider = new FederationAuthenticationProvider() //}); }
private static void SetupAuth(IAppBuilder app, IKernel kernel) { var ticketDataFormat = new TicketDataFormat(kernel.Get<IDataProtector>()); var type = typeof(CookieAuthenticationOptions) .Assembly.GetType("Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware"); app.Use(type, app, new CookieAuthenticationOptions { LoginPath = new PathString("/account/login"), LogoutPath = new PathString("/account/logout"), CookieHttpOnly = true, AuthenticationType = Constants.JabbRAuthType, CookieName = "jabbr.id", ExpireTimeSpan = TimeSpan.FromDays(30), TicketDataFormat = ticketDataFormat, Provider = kernel.Get<ICookieAuthenticationProvider>() }); app.Use(typeof(CustomAuthHandler)); app.Use(typeof(WindowsPrincipalHandler)); }
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 }); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); CookieAuthenticationOptions cookieOptions = new CookieAuthenticationOptions { CookieName = CookieName, }; app.UseCookieAuthentication(cookieOptions); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, PostLogoutRedirectUri = postLogoutRedirectUri, RedirectUri = redirectUri, //Authority = AADInstance + "common", MetadataAddress = metadataAddress, TokenValidationParameters = new TokenValidationParameters { // NOTE: Not Good Practice. See https://github.com/AzureADSamples/WebApp-MultiTenant-OpenIdConnect-DotNet // for proper issues validation in a multi-tenant app. ValidateIssuer = false, }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = OwinStartup.AuthorizationCodeRecieved, AuthenticationFailed = OwinStartup.AuthenticationFailed, RedirectToIdentityProvider = OwinStartup.RedirectToIdentityProvider, SecurityTokenValidated = OwinStartup.SecurityTokenValidated, }, }); IDataProtector dataProtector = app.CreateDataProtector( typeof(CookieAuthenticationMiddleware).FullName, cookieOptions.AuthenticationType, "v1"); ticketDataFormat = new TicketDataFormat(dataProtector); }