首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ASP.NET内核中基于令牌的身份认证

ASP.NET内核中基于令牌的身份认证
EN

Stack Overflow用户
提问于 2015-03-14 18:59:08
回答 2查看 85.5K关注 0票数 166

我正在使用ASP.NET核心应用程序。我正在尝试实现基于令牌的身份验证,但不知道如何在我的情况下使用新的Security System。我使用了examples,但他们对我帮助不大,他们要么使用cookie身份验证,要么使用外部身份验证(GitHub,微软,推特)。

我的场景是: angularjs应用程序应该请求传递用户名和密码的/token url。WebApi需要对用户进行授权,并返回access_token,该app将被angularjs app在以下请求中使用。

我找到了一篇很好的文章,介绍了在当前版本的ASP.NET - Token Based Authentication using ASP.NET Web API 2, Owin, and Identity中实现我所需要的东西。但对于我来说,在ASP.NET核心中如何做同样的事情并不明显。

我的问题是:如何配置ASP.NET核心WebApi应用程序以使用基于令牌的身份验证?

EN

回答 2

Stack Overflow用户

发布于 2016-02-23 21:50:24

您可以查看OpenId连接示例,其中演示了如何处理不同的身份验证机制,包括JWT令牌:

https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Samples

如果您查看Cordova后端项目,API的配置如下所示:

代码语言:javascript
复制
           // Create a new branch where the registered middleware will be executed only for non API calls.
        app.UseWhen(context => !context.Request.Path.StartsWithSegments(new PathString("/api")), branch => {
            // Insert a new cookies middleware in the pipeline to store
            // the user identity returned by the external identity provider.
            branch.UseCookieAuthentication(new CookieAuthenticationOptions {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                AuthenticationScheme = "ServerCookie",
                CookieName = CookieAuthenticationDefaults.CookiePrefix + "ServerCookie",
                ExpireTimeSpan = TimeSpan.FromMinutes(5),
                LoginPath = new PathString("/signin"),
                LogoutPath = new PathString("/signout")
            });

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

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

/Providers/AuthorizationProvider.cs中的逻辑和该项目的RessourceController也值得一看;)。

或者,您也可以使用以下代码来验证令牌(还有一个代码片段可以让它与signalR一起工作):

代码语言:javascript
复制
        // Add a new middleware validating access tokens.
        app.UseOAuthValidation(options =>
        {
            // Automatic authentication must be enabled
            // for SignalR to receive the access token.
            options.AutomaticAuthenticate = true;

            options.Events = new OAuthValidationEvents
            {
                // Note: for SignalR connections, the default Authorization header does not work,
                // because the WebSockets JS API doesn't allow setting custom parameters.
                // To work around this limitation, the access token is retrieved from the query string.
                OnRetrieveToken = context =>
                {
                    // Note: when the token is missing from the query string,
                    // context.Token is null and the JWT bearer middleware will
                    // automatically try to retrieve it from the Authorization header.
                    context.Token = context.Request.Query["access_token"];

                    return Task.FromResult(0);
                }
            };
        });

对于颁发令牌,您可以使用openId连接服务器包,如下所示:

代码语言:javascript
复制
        // Add a new middleware issuing access tokens.
        app.UseOpenIdConnectServer(options =>
        {
            options.Provider = new AuthenticationProvider();
            // Enable the authorization, logout, token and userinfo endpoints.
            //options.AuthorizationEndpointPath = "/connect/authorize";
            //options.LogoutEndpointPath = "/connect/logout";
            options.TokenEndpointPath = "/connect/token";
            //options.UserinfoEndpointPath = "/connect/userinfo";

            // Note: if you don't explicitly register a signing key, one is automatically generated and
            // persisted on the disk. If the key cannot be persisted, an exception is thrown.
            // 
            // On production, using a X.509 certificate stored in the machine store is recommended.
            // You can generate a self-signed certificate using Pluralsight's self-cert utility:
            // https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
            // 
            // options.SigningCredentials.AddCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
            // 
            // Alternatively, you can also store the certificate as an embedded .pfx resource
            // directly in this assembly or in a file published alongside this project:
            // 
            // options.SigningCredentials.AddCertificate(
            //     assembly: typeof(Startup).GetTypeInfo().Assembly,
            //     resource: "Nancy.Server.Certificate.pfx",
            //     password: "Owin.Security.OpenIdConnect.Server");

            // Note: see AuthorizationController.cs for more
            // information concerning ApplicationCanDisplayErrors.
            options.ApplicationCanDisplayErrors = true // in dev only ...;
            options.AllowInsecureHttp = true // in dev only...;
        });

我使用Aurelia前端框架和ASP.NET核心实现了一个基于令牌的身份验证实现的单页面应用程序。还有一个信号R持久连接。但是,我还没有做任何DB实现。代码在这里:https://github.com/alexandre-spieser/AureliaAspNetCoreAuth

票数 3
EN

Stack Overflow用户

发布于 2016-01-12 15:39:23

看看OpenIddict --这是一个新项目(在撰写本文时),它使得在ASP.NET 5中配置JWT令牌的创建和刷新令牌变得很容易。令牌的验证由其他软件处理。

假设您将IdentityEntity Framework一起使用,最后一行是您要添加到ConfigureServices方法中的内容:

代码语言:javascript
复制
services.AddIdentity<ApplicationUser, ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders()
    .AddOpenIddictCore<Application>(config => config.UseEntityFramework());

Configure中,您可以设置OpenIddict来提供JWT令牌:

代码语言:javascript
复制
app.UseOpenIddictCore(builder =>
{
    // tell openiddict you're wanting to use jwt tokens
    builder.Options.UseJwtTokens();
    // NOTE: for dev consumption only! for live, this is not encouraged!
    builder.Options.AllowInsecureHttp = true;
    builder.Options.ApplicationCanDisplayErrors = true;
});

还可以在Configure中配置令牌的验证

代码语言:javascript
复制
// use jwt bearer authentication
app.UseJwtBearerAuthentication(options =>
{
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;
    options.RequireHttpsMetadata = false;
    options.Audience = "http://localhost:58292/";
    options.Authority = "http://localhost:58292/";
});

还有一两件小事,比如你的DbContext需要从OpenIddictContext派生。

你可以在这篇博客文章上看到完整的解释:http://capesean.co.za/blog/asp-net-5-jwt-tokens/

功能演示可在以下网址获得:https://github.com/capesean/openiddict-test

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29048122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档