GithubHelp home page GithubHelp logo

openiddict / openiddict-samples Goto Github PK

View Code? Open in Web Editor NEW
706.0 33.0 297.0 6.14 MB

.NET samples for OpenIddict

Home Page: https://documentation.openiddict.com/

License: Apache License 2.0

Batchfile 0.13% PowerShell 55.25% Shell 40.81% CMake 3.81%
openidconnect oauth2 aspnetcore dotnet

openiddict-samples's Introduction

OpenIddict samples

This repository contains samples demonstrating how to use OpenIddict with the different OAuth 2.0/OpenID Connect flows.

ASP.NET Core samples

  • Aridka: client credentials demo, with a .NET console acting as the client.
  • Balosar: authorization code flow demo, with a Blazor WASM application acting as the client.
  • Contruum: conformance tests project using Razor Pages and 2 hardcoded user identities, meant to be used with the OIDC certification suite.
  • Dantooine: backend-for-frontend (BFF) Blazor WASM application hosted in ASP.NET Core with Microsoft YARP for downstream API.
  • Hollastin: resource owner password credentials demo, with a .NET console acting as the client.
  • Imynusoph: refresh token grant demo, with a .NET console acting as the client.
  • Matty: device authorization flow demo, with a .NET console acting as the client.
  • Mimban: authorization code flow demo using minimal APIs and GitHub delegation for user authentication, with a .NET console acting as the client.
  • Velusia: authorization code flow demo, with an ASP.NET Core application acting as the client.
  • Weytta: authorization code flow with Integrated Windows Authentication support and a .NET console acting as the client.
  • Zirku: authorization code flow demo using minimal APIs with 2 hard-coded user identities, a .NET console and a SPA acting as the clients and two API projects using introspection (Api1) and local validation (Api2).

.NET samples

  • Sorgan: console, Windows Forms, Windows Presentation Foundation and Blazor Hybrid clients using GitHub for user authentication.

OWIN/ASP.NET 4.8 samples

  • Fornax: authorization code flow demo using ASP.NET Web Forms 4.8 and OWIN/Katana, with a .NET Framework 4.8 console acting as the client.
  • Mortis: authorization code flow demo using ASP.NET MVC 5.2 and ASP.NET Web API 2.2, with an ASP.NET MVC 5.2 application acting as the client.
  • Kalarba: resource owner password credentials demo using OWIN/Katana, ASP.NET Web API 2.2 and the OpenIddict degraded mode.

External samples

Looking for additional samples to help you get started with OpenIddict? Don't miss these interesting samples maintained by the community:

Certification

Unlike many other identity providers, OpenIddict is not a turnkey solution but a framework that requires writing custom code to be operational (typically, at least an authorization controller), making it a poor candidate for the certification program.

While a reference implementation could be submitted as-is, this wouldn't guarantee that implementations deployed by OpenIddict users would be standard-compliant.

Instead, developers are encouraged to execute the conformance tests against their own deployment once they've implemented their own logic.

Tip

This repository contains a dedicated sample specially designed to be used with the OpenID Connect Provider Certification tool and demonstrate that OpenIddict can be easily used in a certified implementation. To allow executing the certification tests as fast as possible, that sample doesn't include any membership or consent feature (two hardcoded identities are proposed for tests that require switching between identities).

Security policy

Security issues and bugs should be reported privately by emailing [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message.

Support

If you need support, please first make sure you're sponsoring the project. Depending on the tier you selected, you can open a GitHub ticket or send an email to [email protected] for private support.

Alternatively, you can also post your question on Gitter.

Important

With OpenIddict 5.x being now generally available, the previous version, OpenIddict 4.x, stops being supported and won't receive bug fixes or security updates. As such, it is recommended to migrate to OpenIddict 5.x to continue receiving bug and security fixes.

There are, however, two exceptions to this policy:

  • ABP Framework 7.x users will still receive patches for OpenIddict 4.x for as long as ABP Framework 7.x itself is supported by Volosoft (typically a year following the release of ABP 8.x), whether they have a commercial ABP license or just use the free packages.

  • OpenIddict sponsors who have opted for a $250+/month sponsorship are now offered extended support:

    • $250/month sponsors get full support for OpenIddict 4.x until June 18, 2024 (6 months).
    • $500/month sponsors get full support for OpenIddict 4.x until December 18, 2024 (12 months).
    • $1,000/month sponsors get full support for OpenIddict 4.x until December 18, 2025 (24 months).

Contributors

OpenIddict is actively maintained by Kévin Chalet. Contributions are welcome and can be submitted using pull requests.

License

This project is licensed under the Apache License. This means that you can use, modify and distribute it freely. See http://www.apache.org/licenses/LICENSE-2.0.html for more details.

openiddict-samples's People

Contributors

a-a-k avatar andersco avatar astegmaier avatar atrauzzi avatar bartmax avatar damienbod avatar dampee avatar dependabot[bot] avatar dovydasnavickas avatar greendimka avatar gresau avatar igorhrabrov avatar jeremycook avatar jingliancui avatar joseph7695 avatar kevinchalet avatar marianswa avatar mlhdevelopment avatar mrukas avatar mseada94 avatar pholly avatar shaunluttin avatar verdie-g avatar virzak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openiddict-samples's Issues

Automatic logout after token expiration

I use aurelia-open-id-connect library for user authentication and i use implicit flow!
When i login to the external authority and successfully come back to my client app, every thing works perfect.
my problem is when my token get expired i expect that :

  1. Aurelia router does not show any route items that has OpenIdConnectRoles.Authenticated role!
  2. Logout button () must be changed to login button automatically.
    but none of them happened as i expect!
    here i illustrate my app ViewModel:

import { autoinject, PLATFORM } from 'aurelia-framework';
import { Router, RouterConfiguration } from 'aurelia-router';
import { OpenIdConnect, OpenIdConnectRoles } from "aurelia-open-id-connect";

@autoinject
export class App {

private router: Router;
//private user: User;
constructor(private openIdConnect: OpenIdConnect) {
}

configureRouter(config: RouterConfiguration, router: Router) {

    // switch from hash (#) to slash (/) navigation
    config.options.pushState = true;

    config.title = 'Profile.SPA';
    config.map([{
            route: ['', 'home'],
            name: 'home',
            settings: {
                icon: 'home',
                //roles: [OpenIdConnectRoles.Authenticated]
            },
            moduleId: PLATFORM.moduleName('../home/home'),
            nav: true,
            title: 'home'
        },
        {
            route: 'profile',
            name: 'profile',
            settings: {
                icon: 'user',
                roles: [OpenIdConnectRoles.Authenticated]
            },
            moduleId: PLATFORM.moduleName('../profile/profile'),
            nav: true,
            title: 'profile'
        }
    ]);

    this.openIdConnect.configure(config);
    this.router = router;
}

}

and here i show navbar ViewModel:

import { User } from "oidc-client";
import { Router } from 'aurelia-router';
import { OpenIdConnect } from "aurelia-open-id-connect";
import { autoinject, bindable } from 'aurelia-framework';

@autoinject
export class Navmenu {
@bindable router: Router;
private user: User;
constructor(private openIdConnect: OpenIdConnect) {
this.openIdConnect.observeUser((user: User) => this.user = user);
}
}

Seperate Auth and resource service

Hi,

I am using the Authorization code flow sample, and I would like to separate the authorization and the resource server but I am struggling to understand what code would go into startup to register token introspection middleware.

Can anyone help please?

Create a hybrid(custom?) sample

I'd like for a hybrid sample to be added.
It's not clear how a hybrid app should be added (for example one with response type "code id_token").
Edit: Hybrid flow can be enabled by allowing both Authorization Code and Implicit Flow.

It's not clear as of right now how this should work, even though the documentation mentions it can handle hybrid flows. I do not see a way to implement this in the documentation. The Allow...Flow also don't contain a hybrid one? Does this mean it has to be a custom one and implement it myself? Would be nice if there was a sample doing this then as well.

I'd appreciate it if the client could be a Net framework 4.6.1 with Owin, since i'm currently trying that, but i have some trouble getting just the code to work. I noticed https://stackoverflow.com/a/33662736/7957165) that just code is not supported, so want to do code id_token.

Thanks in advance.

Argument of type 'RequestInit' is no assignable...

I am having an issue with running the AureliaApp because of below error:

Argument of type 'RequestInit' is not assignable to parameter of type 'import(",,,,,,,,/node_modules/aurelia-fetch-client/dist/aurelia-fetch-client").RequestInit'.
Types of property 'body' are incompatible.
Type 'BodyInit' is not assignable to type 'string | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams'.
Type 'ReadableStream' is not assignable to type 'string | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams'.
Type 'ReadableStream' is not assignable to type 'URLSearchParams'.
Property 'append' is missing in type 'ReadableStream'.

The error occurs in

https://github.com/openiddict/openiddict-samples/blob/dev/samples/ImplicitFlow/AureliaApp/src/home.ts in queryResourceServer function.
on below line:
this.httpClient.fetch(fetchUrl, fetchInit )

This error happens when you run it using visual studio code. But when you run from the command prompt using au run the app works fine.

authorize is redirected to /Account/Login

connect/token issue

hi
i cloned the samples and ran both server and client projects,they work good and i make a user and login with it through mvc UI, but when i want to login with the same user through js and i post my credentials to http://localhost:54540/connect/token expecting to get the token but always retruns 400 bad request with error of {"error": "unsupported_grant_type"
"error_description": "The specified grant_type parameter is not allowed."}

here is the credentails i post to server : username=username&password=pass123&grant_type=password
with contenttype :application/x-www-form-urlencoded

also i tried posting them as json with related contenttype but failed again

regards

Potential bug in refresh-flow sample on client side

Hello,
on https://github.com/openiddict/openiddict-samples/blob/master/samples/RefreshFlow/AngularApp/src/core/auth.service.ts is a bug in my opinion.
Starting at line 108. There should be a map to return the Observable.
Or other functions have to be changed.
I couldn't compile this.

I think the right implementation is:

private getTokens(data: RefreshGrantModel | LoginModel, grantType: string): Observable<AuthTokenModel> {
    const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    const options = new RequestOptions({ headers: headers });

    Object.assign(data, { grant_type: grantType, scope: 'openid offline_access' });

    const params = new URLSearchParams();
    Object.keys(data)
      .forEach(key => params.append(key, data[key]));
    return this.http.post(`${environment.baseApiUrl}/connect/token`, params.toString(), options)
      .pipe(
        map(res => res.json()),
        tap(res => {
          const tokens: AuthTokenModel = res;
          const now = new Date();
          tokens.expiration_date = new Date(now.getTime() + tokens.expires_in * 1000).getTime().toString();

          const profile: ProfileModel = jwtDecode(tokens.id_token);

          this.storeToken(tokens);
          this.updateState({ authReady: true, tokens, profile });
      }));
  }

invalid_client Invalid post_logout_redirect_uri

Hi,

while I have read some posts relating to this issue, I can't seem to get rid of the error invalid_client Invalid post_logout_redirect_uri.

Here is the startup.cs for my client

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

namespace MVCClient
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});

        services.AddMvc();

        services.AddSingleton<HttpClient>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseDeveloperExceptionPage();

        app.UseStaticFiles();

        // Insert a new cookies middleware in the pipeline to store the user
        // identity after he has been redirected from the identity provider.
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            LoginPath = new PathString("/signin")
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            // Note: these settings must match the application details
            // inserted in the database at the server level.
            ClientId = "mvc",
            ClientSecret = "901564A5-E7FE-42CB-B10D-61EF6A8F3654",
            PostLogoutRedirectUri = "http://localhost:53507/",
            RequireHttpsMetadata = false,
            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true,

            // Use the authorization code flow.
            ResponseType = OpenIdConnectResponseType.Code,
            AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet,

            // Note: setting the Authority allows the OIDC client middleware to automatically
            // retrieve the identity provider's configuration and spare you from setting
            // the different endpoints URIs or the token validation parameters explicitly.
            Authority = "http://localhost:54540/",

            Scope = { "email", "roles", "offline_access" }
        });

        app.UseMvc();
    }
}

}

and below is for my server

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using AuthorizationServer.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using AspNet.Security.OpenIdConnect.Primitives;
using AuthorizationServer.Services;
using System.Threading;
using OpenIddict.Models;
using OpenIddict.Core;

namespace AuthorizationServer
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddDbContext<ApplicationDbContext>(options =>
        {
            // Configure the context to use Microsoft SQL Server.
            options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]);

            // Register the entity sets needed by OpenIddict.
            // Note: use the generic overload if you need
            // to replace the default OpenIddict entities.
            options.UseOpenIddict();
        });

        // Register the Identity services.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Configure Identity to use the same JWT claims as OpenIddict instead
        // of the legacy WS-Federation claims it uses by default (ClaimTypes),
        // which saves you from doing the mapping in your authorization controller.
        services.Configure<IdentityOptions>(options =>
        {
            options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
            options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
            options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
        });

        // Register the OpenIddict services.
        services.AddOpenIddict(options =>
        {
            // Register the Entity Framework stores.
            options.AddEntityFrameworkCoreStores<ApplicationDbContext>();

            // Register the ASP.NET Core MVC binder used by OpenIddict.
            // Note: if you don't call this method, you won't be able to
            // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
            options.AddMvcBinders();

            // Enable the authorization, logout, token and userinfo endpoints.
            options.EnableAuthorizationEndpoint("/connect/authorize")
                   .EnableLogoutEndpoint("/connect/logout")
                   .EnableTokenEndpoint("/connect/token")
                   .EnableUserinfoEndpoint("/api/userinfo");

            // Note: the Mvc.Client sample only uses the code flow and the password flow, but you
            // can enable the other flows if you need to support implicit or client credentials.
            options.AllowAuthorizationCodeFlow()
                   .AllowPasswordFlow()
                   .AllowRefreshTokenFlow();

            // Make the "client_id" parameter mandatory when sending a token request.
            options.RequireClientIdentification();

            // When request caching is enabled, authorization and logout requests
            // are stored in the distributed cache by OpenIddict and the user agent
            // is redirected to the same page with a single parameter (request_id).
            // This allows flowing large OpenID Connect requests even when using
            // an external authentication provider like Google, Facebook or Twitter.
            options.EnableRequestCaching();

            // During development, you can disable the HTTPS requirement.
            options.DisableHttpsRequirement();

            // Note: to use JWT access tokens instead of the default
            // encrypted format, the following lines are required:
            //
            // options.UseJsonWebTokens();
            // options.AddEphemeralSigningKey();
        });

        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        app.UseDeveloperExceptionPage();

        app.UseStaticFiles();

        app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), branch =>
        {
            // Add a middleware used to validate access
            // tokens and protect the API endpoints.
            branch.UseOAuthValidation();



            // If you prefer using JWT, don't forget to disable the automatic
            // JWT -> WS-Federation claims mapping used by the JWT middleware:
            //
            // JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            // JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            //
            // branch.UseJwtBearerAuthentication(new JwtBearerOptions
            // {
            //     Authority = "http://localhost:54540/",
            //     Audience = "resource_server",
            //     RequireHttpsMetadata = false,
            //     TokenValidationParameters = new TokenValidationParameters
            //     {
            //         NameClaimType = OpenIdConnectConstants.Claims.Subject,
            //         RoleClaimType = OpenIdConnectConstants.Claims.Role
            //     }
            // });

            // Alternatively, you can also use the introspection middleware.
            // Using it is recommended if your resource server is in a
            // different application/separated from the authorization server.
            //
            // branch.UseOAuthIntrospection(options =>
            // {
            //     options.Authority = new Uri("http://localhost:54540/");
            //     options.Audiences.Add("resource_server");
            //     options.ClientId = "resource_server";
            //     options.ClientSecret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd";
            //     options.RequireHttpsMetadata = false;
            // });
        });

        app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch =>
        {
            branch.UseStatusCodePagesWithReExecute("/error");

            branch.UseIdentity();

            branch.UseGoogleAuthentication(new GoogleOptions
            {
                ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com",
                ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f"
            });

            branch.UseTwitterAuthentication(new TwitterOptions
            {
                ConsumerKey = "6XaCTaLbMqfj6ww3zvZ5g",
                ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"
            });
        });

        app.UseOpenIddict();

        app.UseMvcWithDefaultRoute();

        // Seed the database with the sample applications.
        // Note: in a real world application, this step should be part of a setup script.
        InitializeAsync(app.ApplicationServices, CancellationToken.None).GetAwaiter().GetResult();

    }

    private async Task InitializeAsync(IServiceProvider services, CancellationToken cancellationToken)
    {
        // Create a new service scope to ensure the database context is correctly disposed when this methods returns.
        using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            await context.Database.EnsureCreatedAsync();

            var manager = scope.ServiceProvider.GetRequiredService<OpenIddictApplicationManager<OpenIddictApplication>>();

            if (await manager.FindByClientIdAsync("mvc", cancellationToken) == null)
            {
                var application = new OpenIddictApplication
                {
                    ClientId = "mvc",
                    DisplayName = "MVC client application",
                    LogoutRedirectUri = "http://localhost:53507/",
                    RedirectUri = "http://localhost:53507/signin-oidc",
                    
                };

                await manager.CreateAsync(application, "901564A5-E7FE-42CB-B10D-61EF6A8F3654", cancellationToken);
            }

            // To test this sample with Postman, use the following settings:
            //
            // * Authorization URL: http://localhost:54540/connect/authorize
            // * Access token URL: http://localhost:54540/connect/token
            // * Client ID: postman
            // * Client secret: [blank] (not used with public clients)
            // * Scope: openid email profile roles
            // * Grant type: authorization code
            // * Request access token locally: yes
            if (await manager.FindByClientIdAsync("postman", cancellationToken) == null)
            {
                var application = new OpenIddictApplication
                {
                    ClientId = "postman",
                    DisplayName = "Postman",
                    RedirectUri = "https://www.getpostman.com/oauth2/callback"
                };

                await manager.CreateAsync(application, cancellationToken);
            }
        }
    }
}

}

as you can see, my redirecturi on server side is the same as postdirecturi on client side. Kind regards

External providers in password flow

Hi there, let me start by first saying congrats on this repo and the core one obviously. Very good piece of work. I've spent all day today staring at all the information I could possibly find about oauth2 open id connect and many roads led me back here. I 90% made up my mind to use this a go to for my current project's account server needs.

I just have a few questions before I start the work on it if you don't mind.
It feels like your sample for implicit flow is pretty much what I am looking for, but with some alterations. It matches my needs in terms of there being one, isolated auth server that takes care of all the accounts work. There are multiple apis and there is single page client app (actually there's 2 of these as well in my project, but that's not a big deal) what I am trying to solve is :

  1. I like the idea where you redirect to the authorization server to login/register but for my needs, it feels it would fit better to be able to be able to present the username and password directly on the client app single page app. I assume it would just need to change the logic behind this operation to match pasword or refresh sample to achieve that. Right?
  2. This I feel might be a bigger task/problem. What I would like to achieve is experience similar to for example quora.com where you can sign in / register using other providers as well (google/fb/..). I would like to attach these to the "inhouse" account kept in the database and allow one to login using password/google/fb/... and also disconnect these providers. If I am logged in, I wish to end up with a page where I can have a list of providers and dissociate or attach them as I please.
    This is where I struggle to understand how (and if) this is partial purpose of openiddict or if I should look for some other solution, or possibly build one.
    I see that it would be easy to add this to the implicit flow example just following the standard MVC way of doing this as detailed here : https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/index , maybe not as elegant as I want it to be but something that can be lived with.
    However given the fact that I want to perform this in my client app (react single page app), it seems to make things way more difficult. At least for me given my level of understanding. Basically it's something similar to adding external providers to you password flow example.
    Could you please point me to the right direction? It would be much appreciated.

Using access_token in ng2 app example

Should I pass the ngrx store in every service in order to use the access_token? doing something like this:

@Injectable()
export class ServiceOne extends MyService {
access_token: string;

constructor(private http: Http, private store: Store) {
super();
store.subscribe(state => this.access_token = state.auth.authTokens.access_token);

this._headers.append('Content-Type', 'application/json');
this._headers.append('Authorization', 'Bearer ' + this.access_token);

.........
.......
}

Or is there a better (simpler) way to use it?

Access resource server from authorization server

Hello. I have a scenario similar to the ImplicitFlow sample but with the additional need to call one of the resource servers from the authorization server. For example, once the user has signed in I need to have a page in the authorization server to view/edit the user's profile, and some of those details need to be pulled from a resource server. What would be the recommended way to approach this?

Question - Best way to add "Assume Identity" using OpenIddict

We are using OpenIddict to generate tokens to authenticate users and define what modules they have access to. Our support team would like to be able to assume the identity of the customer they are talking to in order to be able to better diagnose issues. Is there an approved way for us to implement this?
The simplest solution would be an additional endpoint where the support user logs in and provides the username they wish to impersonate - this could then generate the token of said user (with additional properties indicating the support persons identity).
Are there any security or other considerations that mean this solution is not recommended?
Thanks
Duncan

Cannot find AddOAuthValidation

Hello, I'm trying to use the password flow example with .NET Core 2.0 but I'm not able to find this extension method found in the sample code: AddOAuthValidation (in ConfigureServices, services.AddAuthentication().AddOAuthValidation()). Could anyone give a hint? My csproj modules are listed below:

  <ItemGroup>
    <PackageReference Include="AspNet.Security.OAuth.Introspection" Version="1.0.0" />
    <PackageReference Include="AspNet.Security.OAuth.Validation" Version="1.0.0" />
    <PackageReference Include="MailKit" Version="1.22.0" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" />
    <PackageReference Include="OpenIddict" Version="2.0.0-rc2-0779" />
    <PackageReference Include="OpenIddict.EntityFrameworkCore" Version="2.0.0-rc2-0779" />
    <PackageReference Include="OpenIddict.Mvc" Version="2.0.0-rc2-0779" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="1.1.0" />
  </ItemGroup>

Failed to start

I got the following error message when I run dotnet run:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NotSupportedException: The keyword 'integrated security' is not supported on this platform.
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)

I know MS Sql Server is only running in windows. But I'd like to run my web app in Linux (currently testing under Mac OSX) and connect to MSSql Server in Windows. Is this possible? Thanks.

Error when trying to access login / signup page on OpenID Connect Implicit Flow Demo

Hi,

I have followed the instructions here but get the following error when I click on the "login / signup" link.

vendor-bundle.js:14283 ERROR [app-router] Error: Network Error
at XMLHttpRequest.s.onerror (http://localhost:9000/scripts/vendor-bundle.js:26246:27086)
From previous event:
at t.getJson (http://localhost:9000/scripts/vendor-bundle.js:26246:26794)
at t.getMetadata (http://localhost:9000/scripts/vendor-bundle.js:26246:23437)
at t._getMetadataProperty (http://localhost:9000/scripts/vendor-bundle.js:26246:24956)
at t.getAuthorizationEndpoint (http://localhost:9000/scripts/vendor-bundle.js:26246:23943)
at e.t.createSigninRequest (http://localhost:9000/scripts/vendor-bundle.js:26246:4308)
at http://localhost:9000/scripts/vendor-bundle.js:26319:11990
at
From previous event:
at e._signinStart (http://localhost:9000/scripts/vendor-bundle.js:26319:11917)
at e.signinRedirect (http://localhost:9000/scripts/vendor-bundle.js:26319:9960)
at OpenIdConnectNavigationStrategies.login (http://localhost:9000/scripts/app-bundle.js:540:37)
at Object.navigationStrategy (http://localhost:9000/scripts/app-bundle.js:382:68)
at evaluateNavigationStrategy (http://localhost:9000/scripts/debug-bundle.js:1135:38)
at AppRouter._createNavigationInstruction (http://localhost:9000/scripts/debug-bundle.js:1068:18)
at AppRouter.loadUrl (http://localhost:9000/scripts/debug-bundle.js:1676:19)
at BrowserHistory._loadUrl (http://localhost:9000/scripts/vendor-bundle.js:13611:55)
at BrowserHistory.navigate (http://localhost:9000/scripts/vendor-bundle.js:13567:21)
at HTMLDocument.DefaultLinkHandler._this.handler (http://localhost:9000/scripts/vendor-bundle.js:13378:25)
error @ vendor-bundle.js:14283
(anonymous) @ vendor-bundle.js:13878
(anonymous) @ debug-bundle.js:1679
tryCatcher @ vendor-bundle.js:3411
Promise._settlePromiseFromHandler @ vendor-bundle.js:2627
Promise._settlePromise @ vendor-bundle.js:2684
Promise._settlePromise0 @ vendor-bundle.js:2729
Promise._settlePromises @ vendor-bundle.js:2804
(anonymous) @ vendor-bundle.js:153

When I run the RunDemo.ps1 I also get these errors in the aurelia console
node_modules@types\whatwg-fetch\index.d.ts(11,13): error TS2451: Cannot redeclare block-scoped variable 'fetch'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(11,13): error TS2451: Cannot redeclare block-scoped variable 'fetch'.
node_modules@types\whatwg-fetch\index.d.ts(13,14): error TS2300: Duplicate identifier 'HeadersInit'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(13,14): error TS2300: Duplicate identifier 'HeadersInit'.
node_modules@types\whatwg-fetch\index.d.ts(14,15): error TS2300: Duplicate identifier 'Headers'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(14,15): error TS2300: Duplicate identifier 'Headers'.
node_modules@types\whatwg-fetch\index.d.ts(31,14): error TS2300: Duplicate identifier 'BodyInit'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(31,14): error TS2300: Duplicate identifier 'BodyInit'.
node_modules@types\whatwg-fetch\index.d.ts(43,14): error TS2300: Duplicate identifier 'RequestInfo'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(43,14): error TS2300: Duplicate identifier 'RequestInfo'.
node_modules@types\whatwg-fetch\index.d.ts(44,15): error TS2300: Duplicate identifier 'Request'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(44,15): error TS2300: Duplicate identifier 'Request'.
node_modules@types\whatwg-fetch\index.d.ts(64,11): error TS2300: Duplicate identifier 'Request'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(64,11): error TS2300: Duplicate identifier 'Request'.
node_modules@types\whatwg-fetch\index.d.ts(76,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'window' must be of type 'any', but here has type 'null'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(76,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'window' must be of type 'any', but here has type 'null'.
node_modules@types\whatwg-fetch\index.d.ts(79,6): error TS2300: Duplicate identifier 'RequestType'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(79,6): error TS2300: Duplicate identifier 'RequestType'.
node_modules@types\whatwg-fetch\index.d.ts(80,6): error TS2300: Duplicate identifier 'RequestDestination'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(80,6): error TS2300: Duplicate identifier 'RequestDestination'.
node_modules@types\whatwg-fetch\index.d.ts(81,6): error TS2300: Duplicate identifier 'RequestMode'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(81,6): error TS2300: Duplicate identifier 'RequestMode'.
node_modules@types\whatwg-fetch\index.d.ts(82,6): error TS2300: Duplicate identifier 'RequestCredentials'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(82,6): error TS2300: Duplicate identifier 'RequestCredentials'.
node_modules@types\whatwg-fetch\index.d.ts(83,6): error TS2300: Duplicate identifier 'RequestCache'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(83,6): error TS2300: Duplicate identifier 'RequestCache'.
node_modules@types\whatwg-fetch\index.d.ts(84,6): error TS2300: Duplicate identifier 'RequestRedirect'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(84,6): error TS2300: Duplicate identifier 'RequestRedirect'.
node_modules@types\whatwg-fetch\index.d.ts(86,6): error TS2300: Duplicate identifier 'ReferrerPolicy'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(86,6): error TS2300: Duplicate identifier 'ReferrerPolicy'.
node_modules@types\whatwg-fetch\index.d.ts(88,15): error TS2300: Duplicate identifier 'Response'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(88,15): error TS2300: Duplicate identifier 'Response'.
node_modules@types\whatwg-fetch\index.d.ts(107,11): error TS2300: Duplicate identifier 'Response'.
[20:47:06] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(107,11): error TS2300: Duplicate identifier 'Response'.
node_modules@types\whatwg-fetch\index.d.ts(115,6): error TS2300: Duplicate identifier 'ResponseType'.
[20:47:07] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-fetch\index.d.ts(115,6): error TS2300: Duplicate identifier 'ResponseType'.
node_modules@types\whatwg-streams\index.d.ts(32,15): error TS2300: Duplicate identifier 'ReadableStream'.
[20:47:07] gulp-notify: [Error running Gulp] Error: node_modules@types\whatwg-streams\index.d.ts(32,15): error TS2300: Duplicate identifier 'ReadableStream'.
__lib/lib.dom.d.ts(3896,11): error TS2300: Duplicate identifier 'Headers'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(3896,11): error TS2300: Duplicate identifier 'Headers'.
__lib/lib.dom.d.ts(3905,13): error TS2300: Duplicate identifier 'Headers'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(3905,13): error TS2300: Duplicate identifier 'Headers'.
__lib/lib.dom.d.ts(9029,11): error TS2300: Duplicate identifier 'ReadableStream'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(9029,11): error TS2300: Duplicate identifier 'ReadableStream'.
__lib/lib.dom.d.ts(9035,13): error TS2300: Duplicate identifier 'ReadableStream'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(9035,13): error TS2300: Duplicate identifier 'ReadableStream'.
__lib/lib.dom.d.ts(9051,11): error TS2300: Duplicate identifier 'Request'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(9051,11): error TS2300: Duplicate identifier 'Request'.
__lib/lib.dom.d.ts(9068,13): error TS2300: Duplicate identifier 'Request'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(9068,13): error TS2300: Duplicate identifier 'Request'.
__lib/lib.dom.d.ts(9073,11): error TS2300: Duplicate identifier 'Response'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(9073,11): error TS2300: Duplicate identifier 'Response'.
__lib/lib.dom.d.ts(9084,13): error TS2300: Duplicate identifier 'Response'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(9084,13): error TS2300: Duplicate identifier 'Response'.
__lib/lib.dom.d.ts(14687,18): error TS2451: Cannot redeclare block-scoped variable 'fetch'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14687,18): error TS2451: Cannot redeclare block-scoped variable 'fetch'.
__lib/lib.dom.d.ts(14692,6): error TS2300: Duplicate identifier 'BodyInit'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14692,6): error TS2300: Duplicate identifier 'BodyInit'.
__lib/lib.dom.d.ts(14713,6): error TS2300: Duplicate identifier 'HeadersInit'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14713,6): error TS2300: Duplicate identifier 'HeadersInit'.
__lib/lib.dom.d.ts(14723,6): error TS2300: Duplicate identifier 'RequestInfo'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14723,6): error TS2300: Duplicate identifier 'RequestInfo'.
__lib/lib.dom.d.ts(14771,6): error TS2300: Duplicate identifier 'ReferrerPolicy'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14771,6): error TS2300: Duplicate identifier 'ReferrerPolicy'.
__lib/lib.dom.d.ts(14772,6): error TS2300: Duplicate identifier 'RequestCache'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14772,6): error TS2300: Duplicate identifier 'RequestCache'.
__lib/lib.dom.d.ts(14773,6): error TS2300: Duplicate identifier 'RequestCredentials'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14773,6): error TS2300: Duplicate identifier 'RequestCredentials'.
__lib/lib.dom.d.ts(14774,6): error TS2300: Duplicate identifier 'RequestDestination'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14774,6): error TS2300: Duplicate identifier 'RequestDestination'.
__lib/lib.dom.d.ts(14775,6): error TS2300: Duplicate identifier 'RequestMode'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14775,6): error TS2300: Duplicate identifier 'RequestMode'.
__lib/lib.dom.d.ts(14776,6): error TS2300: Duplicate identifier 'RequestRedirect'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14776,6): error TS2300: Duplicate identifier 'RequestRedirect'.
__lib/lib.dom.d.ts(14777,6): error TS2300: Duplicate identifier 'RequestType'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14777,6): error TS2300: Duplicate identifier 'RequestType'.
__lib/lib.dom.d.ts(14778,6): error TS2300: Duplicate identifier 'ResponseType'.
[20:47:07] gulp-notify: [Error running Gulp] Error: __lib/lib.dom.d.ts(14778,6): error TS2300: Duplicate identifier 'ResponseType'.
[20:47:07] TypeScript: 39 semantic errors
[20:47:07] TypeScript: emit succeeded (with errors)
Finished 'buildTypeScript'
Starting 'writeBundles'...

Add sdk to global.json to indicate which CLI the samples support.

Right now, the global.json says this:

{
    "projects": [ "samples" ]
}

Update it to say this, or to say something equivalent, to specify which SDK the samples support:

{
    "projects": [ "samples" ], 
    "sdk": { "version": "1.0.0-preview2-003133" }
}

That way, those who have multiple CLI versions installed can run the samples more easily.

AddSigningCertificate error

i cloned the samples and when run the server project i get this error
"Additional information: At least one signing key must be registered. Consider registering a X.509 certificate using 'services.AddOpenIddict().AddSigningCertificate()' or call 'services.AddOpenIddict().AddEphemeralSigningKey()' to use an ephemeral key."
do i have to do something or some extra config is missing?

CodeFlow. AccessDenied error when a logged user directly go to ~/signin

I have run CodeFlow sample locally. It works as expected: allows to create a new user and shows all User information on home page.

The problem is that if then I go directly to ~/signin I got redirect to AccessDenied page and see in logs the Cookies was forbidden error:

Request starting HTTP/1.1 GET http://localhost:53508/signin  
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
      HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Cookies.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action method ClientApp.Controllers.AuthenticationController.SignIn (ClientApp) with arguments ((null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes (OpenIdConnect).
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Cookies was successfully authenticated.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[13]
      AuthenticationScheme: Cookies was forbidden.
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectMiddleware[13]
      AuthenticationScheme: OpenIdConnect was forbidden.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action ClientApp.Controllers.AuthenticationController.SignIn (ClientApp) in 0.1443ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 5.5373ms 302 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:53508/Account/AccessDenied?ReturnUrl=%2F

Invalid Object Name OpenIddictApplication when using ClientCredentialsFlow Sample

Hello!

I am using the following sample in order to try and implement client credentials flow:

https://github.com/openiddict/openiddict-samples/tree/dev/samples/ClientCredentialsFlow/AuthorizationServer

I have followed this largely to the letter, only exception being that instead of ApplicationDbContext, I named my context AuthDbContext. When I attempt to run the application, I recieve the following error:

System.Data.SqlClient.SqlException: 'Invalid object name 'OpenIddictApplications'.'

I assumed that Openiddict would create the tables in the database for me. Am I misunderstanding something?

EDIT: I wanted to also add that I tested my connection string in a console app to ensure no hidden characters or mistakes, and I know for sure that it is valid.

Refresh token flow without identity

Hello, i've found a code on the internet to generate a token without using identity to retrieve the user.
I need to do the same hing for the refresh token. Here is the link http://kevinchalet.com/2017/01/30/implementing-simple-token-authentication-in-aspnet-core-with-openiddict/

I need to create the ticket without using coe like 'signInManager.CreateUserPrincipalAsync(user)'

Other queston : could you send me what I need to pass to the request for refreshing a token ? I don't manage to pass in the 'else if (request.IsRefreshTokenGrantType())'

This is what I pass actually to the request :

grant_type :refresh_token
scope : openid offline_access
refresh_token: a token generated with the code in the link above.

This is the response :
{
"error": "invalid_grant",
"error_description": "The specified refresh token is invalid."
}

This is a link to show you my code
https://gist.github.com/galiolas/59597fa61128e27cd27b53cd9eddd8aa

I don't managed to pass in the
'else if (request.IsRefreshTokenGrantType())' with the request params I write above.

Thanks

Redirect URI causes 404

I use the authorize function from the Swagger UI to call my authorization server.
It calls following URI:
http://localhost:5105/connect/authorize?response_type=token&client_id=clientId&redirect_uri=http%3A%2F%2Flocalhost%3A5204%2Foauth2-redirect.html&state=U2F0IEphbiAxOSAyMDE5IDIwOjA5OjU3IEdNVC0wNTAwIChFYXN0ZXJuIFN0YW5kYXJkIFRpbWUp
But all I get is a 404.
When I remove the redirect_uri part of the query string I get following error:

The mandatory 'redirect_uri' parameter is missing.

Here is the Startup.cs:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                {
                    options.UseNpgsql(Configuration.GetConnectionString("PostgresDb"));
                    options.UseOpenIddict();
                });

            services.AddDefaultIdentity<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();
                
            services.AddOpenIddict()
                .AddCore(options =>
                {
                    options.UseEntityFrameworkCore()
                           .UseDbContext<ApplicationDbContext>();
                })
                .AddServer(options =>
                {
                    options.UseMvc();
                    options.EnableAuthorizationEndpoint("/connect/authorize")
                                   .EnableTokenEndpoint("/connect/token");
                    options.AllowImplicitFlow();
                    options.DisableHttpsRequirement();
                    options.AddEphemeralSigningKey();
                })
                .AddValidation();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            InitializeAsync(app.ApplicationServices).GetAwaiter().GetResult();
        }

        private async Task InitializeAsync(IServiceProvider services)
        {
            // Create a new service scope to ensure the database context is correctly disposed when this methods returns.
            using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                await context.Database.EnsureCreatedAsync();

                await CreateApplicationsAsync();

                async Task CreateApplicationsAsync()
                {
                    var manager = scope.ServiceProvider.GetRequiredService<OpenIddictApplicationManager<OpenIddictApplication>>();

                    if (await manager.FindByClientIdAsync("clientId") == null)
                    {
                        var descriptor = new OpenIddictApplicationDescriptor
                        {
                            ClientId = "clientId",
                            DisplayName = "Swagger client application",
                            RedirectUris = { new Uri("http://localhost:5204/oauth2-redirect.html") },
                            Permissions =
                            {
                                OpenIddictConstants.Permissions.Endpoints.Authorization,
                                OpenIddictConstants.Permissions.Endpoints.Logout,
                                OpenIddictConstants.Permissions.GrantTypes.Implicit,
                                OpenIddictConstants.Permissions.Scopes.Email,
                                OpenIddictConstants.Permissions.Scopes.Profile,
                                OpenIddictConstants.Permissions.Scopes.Roles
                            }
                        };

                        await manager.CreateAsync(descriptor);
                    }
                }
            }
        }
    }
}

unsupported_grant_type, password flow

I tried password flow sample and when I send xhr post request with grant_type=password I receive this error:

{
"error": "unsupported_grant_type",
"error_description": "The specified grant_type is not supported by this authorization server."
}

Same behavior in my local project.

Does the id_token have any purpose in the password flow?

The sample authorization controller in the Password Flow Authentication server has some code that causes the /connect/token endpoint issue an id_token as well as an authorization token:

https://github.com/openiddict/openiddict-samples/blob/master/samples/PasswordFlow/AuthorizationServer/Controllers/AuthorizationController.cs#L163-L170

Does the id_token serve any purpose in an app that only uses the password flow? It doesn't seem that the client is using the id_token for anything. Also, the ROPC spec appears to be an OAuth concept that isn't mentioned in the OpenId Connect spec and doesn't mention an id_token.

Forgive me if this is obvious--I'm trying to use the samples as a learning tool to understand OpenIdConnect and OAuth, so I'm wondering if this is a sign of something I don't know about, or if it's just unnecessary code copied over from the other samples. If the latter, perhaps it should be remove from the samples?

Implicit Flow sample can't find NuGet packages

When I ran RunDemo.ps1 I got these:

Errors in C:\Code\ImplicitFlow\AuthorizationServer\AuthorizationServer.csproj
Unable to resolve 'AspNet.Security.OAuth.Validation (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.
Unable to resolve 'OpenIddict.Mvc (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.
Unable to resolve 'Openiddict (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.
Unable to resolve 'OpenIddict.EntityFrameworkCore (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.

Errors in C:\Code\ImplicitFlow\ResourceServer01\ResourceServer01.csproj
Unable to resolve 'AspNet.Security.OAuth.Introspection (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.

Errors in C:\Code\ImplicitFlow\ResourceServer02\ResourceServer02.csproj
Unable to resolve 'AspNet.Security.OAuth.Introspection (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.

My guess is that the AspNet.Security.OAuth packages are still in prerelease, so the csproj files need to be updated, but I couldn't find any OpenIddict packages at nuget.org.

Edit: I see now that the versions are in the dependencies.props file.

Using OpenIddict with JWT Bearer Authentication with a .NET Framework 4.6 Resource server

I am using OpenIddict with the implicit flow for my .NET Core 2.1 combined API and Authorization server that uses JWT Bearer authentication and everything is working great.

Now I need to add a second resource server which is a separate .NET 4.6.1 Framework web application using Web API 1. (This is a reporting API which has to rely on the full .NET Framework). Now I want to secure my Controller endpoint with the [Authorize] tag and get this to play nicely with my main Authorization Server endpoint using JWT Bearer access tokens.

I've seen different ways of setting up JWT Bearer authentication to secure the controller in Web API 1 projects- from writing a custom [JWTAuthentication] attribute filter, to using Owin middleware.

Do you have an example or suggestion on the recommended way to configure a .NET Framework 4.x Resource server which uses the original WEB API (not version 2) with JWT Bearer authentication and allowing it to talk to the main OpenIddict .NET Core Authorization Server? The existing samples that show Resource Servers are all in .NET Core.

Refresh token not being issued

Hi,

I tried the sample (MVC server), and when a make a post request to "../connect/token" I get issued a token, but never a refresh token. Am I missing something?

Thank you

Repair the aurelia part of the implicit flow demo.

With commit e1aeb5c5a3bd939f4cfa1a639e2110b78715074f and node 6.9.1, the call to npm run start produces dozens of TypeScript errors.

Cannot find name...

@PinpointTownes Please assign this issue to me and I will fix it with a PR.

Support for .net 4.6.1

Hi there! I'm very eager to use this library as was using the built-in Microsoft auth solution with Identity, then realized I couldn't use the default SignInManager to get JWT's. So, OpenIddict seems to be a perfect solution for me. Unfortunately, I'm having trouble installing it. Upon adding the necessary dependencies (OpenIddict and OAuth.Validation), I get an error when the packages are installed:

Unable to resolve 'OpenIddict (>= 1.0.0)' for '.NETFramework,Version=v4.6.1'

The "frameworks" node in my package.json looks like this:

"frameworks": { "net461": {} }

Is this supported, or will I not be able to use OpenIddict?

Thanks for your time!

Multiple refresh tokens per user

How can I make a custom provider following the refresh token sample to allow multiple refresh tokens per user (max of 5)? This way if the user logs in from their computer and then goes home and logs in on their phone, they don't have to login each time they get on to a different device. The app.UseOAuthValidation() runs in the background before the authorize controller ever gets called so there is no handle to verify if more than 1 refresh token matches. Another issue is that I am using this:

services.AddDbContext<ApplicationDbContext>(options => {
                options.UseMySql(Configuration.GetConnectionString("DefaultConnection"))
                        .UseOpenIddict();
            });

So I do not have access to the openiddict tables via DbContext to do this manually. Please explain to me how I can achieve this. Thanks.

scripts in AureliaApp are missing

Just wanted to test the AureliaApp sample, but all the javascript files in the scripts directory are missing. How can I get them?
PROBLEM SOLVED: executed RunDemo.ps1

Thanks a lot, Frank

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.