public async Task<ActionResult> GetToken() { var client = new OAuth2Client( new Uri(Constants.TokenEndpoint), "codeclient", "secret"); var code = Request.QueryString["code"]; var response = await client.RequestAuthorizationCodeAsync( code, "https://localhost:44312/callback"); ValidateResponseAndSignIn(response); if (!string.IsNullOrEmpty(response.IdentityToken)) { ViewBag.IdentityTokenParsed = ParseJwt(response.IdentityToken); } if (!string.IsNullOrEmpty(response.AccessToken)) { ViewBag.AccessTokenParsed = ParseJwt(response.AccessToken); } return View("Token", response); }
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 async Task<ActionResult> Postback() { var client = new OAuth2Client( new Uri(Constants.AS.OAuth2TokenEndpoint), Constants.Clients.CodeClient, Constants.Clients.CodeClientSecret); var code = Request.QueryString["code"]; var response = await client.RequestAuthorizationCodeAsync( code, Constants.Clients.CodeClientRedirectUrl); return View("Postback", response); }
private async void UseCodeButton_Click(object sender, RoutedEventArgs e) { if (_response != null && _response.Values.ContainsKey("code")) { var client = new OAuth2Client( new Uri(Constants.TokenEndpoint), "hybridclient", "secret"); var response = await client.RequestAuthorizationCodeAsync( _response.Code, "oob://localhost/wpfclient"); Textbox1.Text = response.Json.ToString(); } }
private static async Task<TokenResponse> SendTokenRequest(string authCode, string redirectUri) { var tokenclient = new OAuth2Client( new Uri(Constant.TokenEndpoint), Constant.CodeClientId, Constant.CodeClientSecret); return await tokenclient.RequestAuthorizationCodeAsync(authCode, redirectUri); }
public void Configure(IApplicationBuilder app) { app.UseCookieAuthentication(options => { options.AuthenticationScheme = "Cookies"; options.AutomaticAuthentication = true; }); app.Map("/code", application => { application.Use((context, next) => { var client = new OAuth2Client(new Uri("http://localhost:5000/core/connect/authorize")); var url = client.CreateCodeFlowUrl(clientId: "0011FF", redirectUri: "http://localhost:5001/callback", scope: "read write"); context.Response.Redirect(url); return Task.FromResult(0); }); }); app.Map("/callback", application => { application.Use(next => async context => { var client = new OAuth2Client(new Uri("http://localhost:5000/core/connect/token"), "0011FF", "ABCDEFG"); var code = context.Request.Query["code"]; TokenResponse response = await client.RequestAuthorizationCodeAsync(code, "http://localhost:5001/callback"); if (!string.IsNullOrEmpty(response.AccessToken)) { List<Claim> claims = new List<Claim>(); claims.Add(new Claim("access_token", response.AccessToken)); claims.Add(new Claim("expires_at", (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToDateTimeFromEpoch().ToString())); ClaimsIdentity id = new ClaimsIdentity(claims, "cookie"); ClaimsPrincipal principal = new ClaimsPrincipal(id); context.Response.SignIn("Cookies", principal); } }); }); app.Map("/info", application => { application.Use(next => async context => { ClaimsPrincipal principal = context.User; await context.Response.WriteAsync(principal.FindFirst("access_token").Value); }); }); app.Map("/call", application => { application.Use(next => async context => { HttpClient client = new HttpClient(); string accessToken = context.User.FindFirst("access_token").Value; client.SetBearerToken(accessToken); string response = await client.GetStringAsync("http://localhost:5002/action"); await context.Response.WriteAsync(response); }); }); }
public void Configuration(IAppBuilder app) { JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); AntiForgeryConfig.UniqueClaimTypeIdentifier = "unique_user_key"; app.UseResourceAuthorization(new AuthorizationManager()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = "mvc", Authority = ExpenseTrackerConstants.IdSrv, RedirectUri = ExpenseTrackerConstants.ExpenseTrackerClient, SignInAsAuthenticationType = "Cookies", ResponseType = "code id_token token", Scope = "openid profile roles expensetrackerapi offline_access", Notifications = new OpenIdConnectAuthenticationNotifications() { MessageReceived = async n => { EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken); EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken); //var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken); }, SecurityTokenValidated = async n => { var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken); // use the authorization code to get a refresh token var tokenEndpointClient = new OAuth2Client( new Uri(ExpenseTrackerConstants.IdSrvToken), "mvc", "secret"); var tokenResponse = await tokenEndpointClient.RequestAuthorizationCodeAsync( n.ProtocolMessage.Code, ExpenseTrackerConstants.ExpenseTrackerClient); var givenNameClaim = new Claim( Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName, userInfo.Value<string>("given_name")); var familyNameClaim = new Claim( Thinktecture.IdentityModel.Client.JwtClaimTypes.FamilyName, userInfo.Value<string>("family_name")); var roles = userInfo.Value<JArray>("role").ToList(); var newIdentity = new ClaimsIdentity( n.AuthenticationTicket.Identity.AuthenticationType, Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName, Thinktecture.IdentityModel.Client.JwtClaimTypes.Role); newIdentity.AddClaim(givenNameClaim); newIdentity.AddClaim(familyNameClaim); foreach (var role in roles) { newIdentity.AddClaim(new Claim( Thinktecture.IdentityModel.Client.JwtClaimTypes.Role, role.ToString())); } var issuerClaim = n.AuthenticationTicket.Identity .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Issuer); var subjectClaim = n.AuthenticationTicket.Identity .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Subject); newIdentity.AddClaim(new Claim("unique_user_key", issuerClaim.Value + "_" + subjectClaim.Value)); newIdentity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken)); newIdentity.AddClaim(new Claim("access_token", tokenResponse.AccessToken)); newIdentity.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString())); n.AuthenticationTicket = new AuthenticationTicket( newIdentity, n.AuthenticationTicket.Properties); }, } }); }
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; } }, } }); }
public void Configuration(IAppBuilder app) { //This line prevent claim type to be mapped to dotnet's claim types, it resets the mapping dictionary, //ensure that no mapping occurs. //Second benefit is that the claim's names are much more readable. JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); //Use this claim instead of identifier or identity provider claim AntiForgeryConfig.UniqueClaimTypeIdentifier = "unique_user_key"; app.UseResourceAuthorization(new AuthorizationManager()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); //Open connect middleware with supports hybrid flow: app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = "mvc", //this name is defined in id srv: ExpenseTracker.IdSrv.Config.Clients class Authority = ExpenseTrackerConstants.IdSrv, RedirectUri = ExpenseTrackerConstants.ExpenseTrackerClient, SignInAsAuthenticationType = "Cookies", //Possibility to define 3 types of responses: //code for authorization code //token for access token //id_token for an identity //There are 3 types of response types: // code: for authorization code // token: for an access token and to get userInfo // id_token: for identity token ResponseType = "code id_token token", // this depends on the flow you are using (implit vs authorization code flow) //the type above is configured for hybrid flow: //- we are working with identity so we require an id_token //- we also require the authorization code so that the flow can successfully complete //Example: authorization code flow requires authoriation code //If the client does not call the correct response type, the flow would not be able to successfully complete //Configure resource scopes: //Type of id scope are like a collections of claims //Profile matches to profile related claims such as given_name, family_name, picture, gender, etc... //Other scopes: // - address: country, postal code, etc... // - ... //Check openid tech spec to get a full list of scope types Scope = "openid profile roles expensetrackerapi offline_access", //openid scope is a requirement for openid support //roles scope to request roles from id server //expensetrackerapi to allow access to the api Notifications = new OpenIdConnectAuthenticationNotifications() { MessageReceived = async n => { EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken); //When 'token' is set in reponse type, the access token will contain the profile and openid scope EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken); //this allows us to access the user endpoint and retrieve the profile values //given_name and family_name values will be available in userInfo var userInfo = await EndpointAndTokenHelper .CallUserInfoEndpoint(n.ProtocolMessage.AccessToken); //Best practise: //Put very basic information in the id_token, //but return extended information through a seperate call to the userinfo endpoint. }, //Using claims transformation SecurityTokenValidated = async n => { //Debug access token use: EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken) var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken); var givenNameClaim = new Claim( Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName, userInfo.Value<string>("given_name")); var familyNameClaim = new Claim( Thinktecture.IdentityModel.Client.JwtClaimTypes.FamilyName, userInfo.Value<string>("family_name")); var roles = userInfo.Value<JArray>("role").ToList(); var newIdentity = new ClaimsIdentity( n.AuthenticationTicket.Identity.AuthenticationType, Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName, Thinktecture.IdentityModel.Client.JwtClaimTypes.Role); newIdentity.AddClaim(givenNameClaim); newIdentity.AddClaim(familyNameClaim); foreach (var role in roles) //Add the roles to the claims: { newIdentity.AddClaim(new Claim( Thinktecture.IdentityModel.Client.JwtClaimTypes.Role, role.ToString())); } var issuerClaim = n.AuthenticationTicket.Identity .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Issuer); var subjectClaim = n.AuthenticationTicket.Identity .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Subject); newIdentity.AddClaim(new Claim("unique_user_key", //this claim is used as AntiForgery token issuerClaim.Value + "_" + subjectClaim.Value)); //userId is composed of issuer and subject //This is used for client credentials flow (server to server): //var oAuth2Client = new OAuth2Client( // new Uri(ExpenseTrackerConstants.IdSrvToken), // "mvc_api", // "secret"); //var response = oAuth2Client.RequestClientCredentialsAsync("expensetrackerapi").Result; //EndpointAndTokenHelper.DecodeAndWrite(response.AccessToken) //Add access token to list of cliams, next pass this access token to api on each call //so that resource scope can fulfill requests. To do this add it to the bearer token //in the http client headers. //newIdentity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // this token is replaced by the refresh tokens below: // use the authorization code to get a refresh token var tokenEndpointClient = new OAuth2Client( new Uri(ExpenseTrackerConstants.IdSrvToken), "mvc", "secret"); var tokenResponse = await tokenEndpointClient.RequestAuthorizationCodeAsync( n.ProtocolMessage.Code, ExpenseTrackerConstants.ExpenseTrackerClient); newIdentity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken)); newIdentity.AddClaim(new Claim("access_token", tokenResponse.AccessToken)); newIdentity.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString())); n.AuthenticationTicket = new AuthenticationTicket( newIdentity, n.AuthenticationTicket.Properties); }, } }); }