public async Task<IUserInfoResponse> GetUserInfo(Uri userInfoEndpoint, string accessToken) { var userInfoClient = new UserInfoClient(userInfoEndpoint, accessToken); var response = await userInfoClient.GetAsync().ConfigureAwait(false); if (response.IsError) throw new Exception("Error while retrieving userinfo: " + response.ErrorMessage); return new UserInfoResponse(response.Raw); }
public void Configuration(IAppBuilder app) { AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub"; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = "hybridclient", Authority = IdServBaseUri, RedirectUri = ClientUri, PostLogoutRedirectUri = ClientUri, ResponseType = "code id_token token", Scope = "openid profile email roles offline_access", SignInAsAuthenticationType = "Cookies", Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async n => { var identity = n.AuthenticationTicket.Identity; var nIdentity = new ClaimsIdentity(identity.AuthenticationType, "email", "role"); var userInfoClient = new UserInfoClient( new Uri(UserInfoEndpoint), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(x => nIdentity.AddClaim(new Claim(x.Item1, x.Item2))); var tokenClient = new OAuth2Client(new Uri(TokenEndpoint), "hybridclient", "idsrv3test"); var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri); nIdentity.AddClaim(new Claim("access_token", response.AccessToken)); nIdentity.AddClaim( new Claim("expires_at", DateTime.UtcNow.AddSeconds(response.ExpiresIn).ToLocalTime().ToString(CultureInfo.InvariantCulture))); nIdentity.AddClaim(new Claim("refresh_token", response.RefreshToken)); nIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); n.AuthenticationTicket = new AuthenticationTicket( nIdentity, n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value; n.ProtocolMessage.IdTokenHint = idTokenHint; } } } }); }
public void Configuration(IAppBuilder appBuilder) { //var options = new IdentityServerOptions //{ // SigningCertificate = Certificate.Load(), // Factory = factory, //}; //appBuilder.UseIdentityServer(options); var connectionString = "MembershipReboot"; //------------------------------------------------ const string IdServBaseUri = @"https://*****:*****@"https://localhost:44333/admin/"; AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub"; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); appBuilder.Map("/admin", adminApp => { adminApp.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); adminApp.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { AuthenticationType = "oidc", ClientId = "hybridclient", Authority = IdServBaseUri, RedirectUri = ClientUri, PostLogoutRedirectUri = @"https://*****:*****@"https://localhost:44333/connect/userinfo"), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); List<Tuple<string, string>> mn = userInfo.Claims as List<Tuple<string, string>>; mn.ForEach(x => nIdentity.AddClaim(new Claim(x.Item1, x.Item2))); //userInfo.Claims.ToList().ForEach(x => nIdentity.AddClaim(new Claim(x.Item1, x.Item2))); /*var tokenClient = new OAuth2Client(new Uri(@"https://*****:*****@"https://localhost:44333/useraccount/", ResponseType = "code id_token token", Scope = "openid profile email roles all_claims", //offline_access SignInAsAuthenticationType = "Cookies", PostLogoutRedirectUri = @"https://*****:*****@"https://localhost:44333/connect/userinfo"), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); List<Tuple<string, string>> mn = userInfo.Claims as List<Tuple<string, string>>; mn.ForEach(x => nIdentity.AddClaim(new Claim(x.Item1, x.Item2))); nIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); n.Options.Caption += "id_token_hint=" + n.ProtocolMessage.IdToken; n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket( nIdentity, n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value; n.ProtocolMessage.IdTokenHint = idTokenHint; //var caption = n.Options.Caption; //var indexOfTokenHint = caption.IndexOf("id_token_hint="); //var idTokenHint = caption.Substring(indexOfTokenHint).Replace("id_token_hint=", ""); //n.Options.Caption = caption.Remove(indexOfTokenHint); //n.ProtocolMessage.IdTokenHint = idTokenHint; } } } }); }); var idSvrFactory = Factory.Configure(); idSvrFactory.ConfigureCustomUserService(connectionString); idSvrFactory.ViewService = new Thinktecture.IdentityServer.Core.Configuration.Registration<IViewService>(typeof(CustomViewService)); var options = new IdentityServerOptions { IssuerUri = "https://localhost:44333/", //"https://localhost:44333/core" SiteName = "SLEEK Auth System", SigningCertificate = Certificate.Load(), //.Get(), Factory = idSvrFactory, CorsPolicy = CorsPolicy.AllowAll, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureAdditionalIdentityProviders, LoginPageLinks = new LoginPageLink[] { new LoginPageLink(){ Href = "UserAccount/PasswordReset", Text = "I can't access my account" }, new LoginPageLink(){ Href = "Registration", Text = "Create account" } } }, //EnableWelcomePage = false }; appBuilder.UseIdentityServer(options); }
public void Configuration(IAppBuilder app) { app.Map("/identity2", idsrvApp => { idsrvApp.UseIdentityServer(new IdentityServerOptions { SiteName = "Embedded IdentityServer", SigningCertificate = LoadCertificate(), //Factory = InMemoryFactory.Create( // users: Users.Get(), // clients: Clients.Get(), // scopes: StandardScopes.All) Factory = InMemoryFactory.Create( users: Users.Get(), clients: Clients.Get(), scopes: Scopes.Get()) }); }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { Authority = "https://localhost:44301/identity2", ClientId = "mvc", Scope = "openid profile roles sampleApi", RedirectUri = "http://localhost:44300/home/about", ResponseType = "id_token token", SignInAsAuthenticationType = "Cookies", Notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = async n => { var id = n.AuthenticationTicket.Identity; // we want to keep first name, last name, subject and roles var givenName = id.FindFirst(Constants.ClaimTypes.GivenName); var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName); var sub = id.FindFirst(Constants.ClaimTypes.Subject); var roles = id.FindAll(Constants.ClaimTypes.Role); // create new identity and set name and role claim type var nid = new ClaimsIdentity( id.AuthenticationType, Constants.ClaimTypes.GivenName, Constants.ClaimTypes.Role); // get userinfo data var userInfoClient = new UserInfoClient( new Uri(n.Options.Authority + "/connect/userinfo"), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2))); // keep the id_token for logout nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); // add access token for sample API nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // keep track of access token expiration nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString())); //nid.AddClaim(givenName); //nid.AddClaim(familyName); //nid.AddClaim(sub); //nid.AddClaims(roles); // add some other app specific claim nid.AddClaim(new Claim("app_specific", "some data")); nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); n.AuthenticationTicket = new AuthenticationTicket( nid, n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value; n.ProtocolMessage.IdTokenHint = idTokenHint; } } } }); //The long claim names come from Microsoft's JWT handler trying to map some claim types to .NET's ClaimTypes class types. You can turn off this behavior with the following line of code (in Startup). AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.UseResourceAuthorization(new AuthorizationManager()); }
public void Configuration(IAppBuilder app) { LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.Map("/identity", idsrvApp => { idsrvApp.UseIdentityServer(new IdentityServerOptions { SiteName = "Embedded IdentityServer", SigningCertificate = LoadCertificate(), Factory = InMemoryFactory.Create( users: Users.Get(), clients: Clients.Get(), scopes: Scopes.Get()), AuthenticationOptions = new Thinktecture.IdentityServer.Core.Configuration.AuthenticationOptions { IdentityProviders = ConfigureIdentityProviders } }); }); app.UseResourceAuthorization(new AuthorizationManager()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { Authority = "https://localhost:44319/identity", ClientId = "mvc", Scope = "openid profile roles sampleApi", ResponseType = "id_token token", RedirectUri = "https://localhost:44319/", SignInAsAuthenticationType = "Cookies", UseTokenLifetime = false, Notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = async n => { var nid = new ClaimsIdentity( n.AuthenticationTicket.Identity.AuthenticationType, Constants.ClaimTypes.GivenName, Constants.ClaimTypes.Role); // get userinfo data var userInfoClient = new UserInfoClient( new Uri(n.Options.Authority + "/connect/userinfo"), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2))); // keep the id_token for logout nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); // add access token for sample API nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // keep track of access token expiration nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString())); // add some other app specific claim nid.AddClaim(new Claim("app_specific", "some data")); n.AuthenticationTicket = new AuthenticationTicket( nid, n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); if (idTokenHint != null) { n.ProtocolMessage.IdTokenHint = idTokenHint.Value; } } } } }); }
public void ConfigureAuth(IAppBuilder app) { // LG.Owin.Security.Enviornment.Startup.ConfigAuth(app); AntiForgeryConfig.UniqueClaimTypeIdentifier = Thinktecture.IdentityServer.Core.Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.UseResourceAuthorization( new AuthorizationManager()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies", AuthenticationMode = AuthenticationMode.Active }); app.SetDefaultSignInAsAuthenticationType("External"); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { Authority = LG.Owin.Security.Config.ServerSettings.Url, ClientId = LG.Owin.Security.Config.ClientSettings.ClientID, ClientSecret = "51FC860D-07D3-4296-9147-2E40AC7FF6C8".Sha256(), Scope = "openid profile roles all_claims", ResponseType = "id_token token", RedirectUri = "https://www.1888md.com/Members/", SignInAsAuthenticationType = "Cookies", UseTokenLifetime = false, Notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = async n => { var nid = new ClaimsIdentity( n.AuthenticationTicket.Identity.AuthenticationType, Thinktecture.IdentityServer.Core.Constants.ClaimTypes.GivenName, Thinktecture.IdentityServer.Core.Constants.ClaimTypes.Role); var userInfoClient = new UserInfoClient( new Uri(n.Options.Authority + "/connect/userinfo"), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2))); //userInfo.Claims.ToList().ForEach(ui => nid.AddClaim( // new Claim(ui.Item1, ui.Item2))); // keep the id_token for logout nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); // add access token for sample API nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // keep track of access token expiration nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString())); // add some other app specific claim //nid.AddClaim(new Claim("app_specific", "some data")); n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest) { await GetWaiter(); var sb = new StringBuilder(); var custom = n.OwinContext.Get<Dictionary<string, string>>("OpenIdConnect.Parameters"); if (custom != null) { foreach (var c in custom) { // ReSharper disable once UseStringInterpolation sb.Append(string.Format(" {0}={1}", c.Key, c.Value)); } } if (sb.Length > 0) { sb.Remove(0, 1); } n.ProtocolMessage.AcrValues = sb.ToString(); } if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); if (idTokenHint != null) { n.ProtocolMessage.IdTokenHint = idTokenHint.Value; } } } } }); }
private async Task<IEnumerable<Claim>> GetUserInfoClaimsAsync(string accessToken) { var userInfoClient = new UserInfoClient(new Uri(Constants.UserInfoEndpoint), accessToken); var userInfo = await userInfoClient.GetAsync(); var claims = new List<Claim>(); userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2))); return claims; }
public void Configuration(IAppBuilder app) { LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); app.Map(IdsrvPath, coreApp => { var factory = InMemoryFactory.Create( users: Users.Get(), clients: Clients.Get(), scopes: Scopes.Get()); var options = new IdentityServerOptions { IssuerUri = "https://idsrv3.com", SiteName = "IdentityServer3 - LocalizedViewService", RequireSsl = false, EnableWelcomePage = true, SigningCertificate = Certificate.Get(), Factory = factory, CorsPolicy = CorsPolicy.AllowAll, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureAdditionalIdentityProviders, } }; var viewLocalizationOptions = new IdentityServerViewLocalizationOptions { LocalizationServiceOptions = { // Add not standard scopes ScopeLocalizationRequest = info => { return new ScopeLocalizationCollection { { "pt-BR", new ScopeTranslations { {"read", "Ler dados", "Ler dados do aplicativo"}, // {"write", "Escrever dados" } // Fallback use default } }, // override defaults { "en", new ScopeTranslations { {"read", "Read application data"}, {"write", "Write application data", "Custom description of Write data"} } } }; } } }; // This "Use" order is important coreApp.UseIdentityServerViewLocalization(options, viewLocalizationOptions); coreApp.UseIdentityServer(options); }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = "owin", Authority = AuthorityUri, RedirectUri = SelfHostUri, PostLogoutRedirectUri = SelfHostUri, SignInAsAuthenticationType = "Cookies", ResponseType = "code id_token token", Scope = "openid profile email offline_access phone roles all_claims address", // Scope = "openid profile offline_access read write", Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async n => { // filter "protocol" claims var claims = new List<Claim>(from c in n.AuthenticationTicket.Identity.Claims where c.Type != "iss" && c.Type != "aud" && c.Type != "nbf" && c.Type != "exp" && c.Type != "iat" && c.Type != "nonce" && c.Type != "c_hash" && c.Type != "at_hash" select c); // get userinfo data var userInfoClient = new UserInfoClient( new Uri(UserInfoClientUri), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2))); // get access and refresh token var tokenClient = new OAuth2Client( new Uri(TokenClientUri), "owin", "secret"); var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri); claims.Add(new Claim("access_token", response.AccessToken)); claims.Add(new Claim("expires_at", DateTime.Now.AddSeconds(response.ExpiresIn).ToLocalTime().ToString())); claims.Add(new Claim("refresh_token", response.RefreshToken)); claims.Add(new Claim("id_token", n.ProtocolMessage.IdToken)); n.AuthenticationTicket = new AuthenticationTicket(new ClaimsIdentity(claims.Distinct(new ClaimComparer()), n.AuthenticationTicket.Identity.AuthenticationType), n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { // if signing out, add the id_token_hint if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value; n.ProtocolMessage.IdTokenHint = idTokenHint; } } } }); var httpConfig = new HttpConfiguration(); httpConfig.MapHttpAttributeRoutes(); httpConfig.Routes.MapHttpRoute("Home", "", new { controller = "Page", action = "Index" }); httpConfig.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); app.UseWebApi(httpConfig); }
public void Configuration(IAppBuilder app) { JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = "katanaclient", Authority = Constants.BaseAddress, RedirectUri = "http://localhost:2672/", PostLogoutRedirectUri = "http://localhost:2672/", ResponseType = "code id_token token", Scope = "openid email profile read write offline_access", SignInAsAuthenticationType = "Cookies", Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async n => { // filter "protocol" claims var claims = new List<Claim>(from c in n.AuthenticationTicket.Identity.Claims where c.Type != "iss" && c.Type != "aud" && c.Type != "nbf" && c.Type != "exp" && c.Type != "iat" && c.Type != "nonce" && c.Type != "c_hash" && c.Type != "at_hash" select c); // get userinfo data var userInfoClient = new UserInfoClient( new Uri(Constants.UserInfoEndpoint), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2))); // get access and refresh token var tokenClient = new OAuth2Client( new Uri(Constants.TokenEndpoint), "katanaclient", "secret"); var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri); claims.Add(new Claim("access_token", response.AccessToken)); claims.Add(new Claim("expires_at", DateTime.Now.AddSeconds(response.ExpiresIn).ToLocalTime().ToString())); claims.Add(new Claim("refresh_token", response.RefreshToken)); claims.Add(new Claim("id_token", n.ProtocolMessage.IdToken)); n.AuthenticationTicket = new AuthenticationTicket(new ClaimsIdentity(claims.Distinct(new ClaimComparer()), n.AuthenticationTicket.Identity.AuthenticationType), n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { // if signing out, add the id_token_hint if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value; n.ProtocolMessage.IdTokenHint = idTokenHint; } }, } }); }