5 ASP.NET承载的OAuth令牌认证 [英] ASP.NET 5 OAuth bearer token authentication

查看:112
本文介绍了5 ASP.NET承载的OAuth令牌认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现OAuth的承载在ASP.NET中5令牌认证,并很努力,因为OWIN东西在ASP.NET 5已更改为找到如何做到这一点的例子。

例如 IApplicationBuilder.UseOAuthAuthorizationServer() IApplicationBuilder。 UseOAuthBearerAuthentication()要么不存在了,或我缺少一个参考?

任何指针将大大AP preciated。


解决方案

我做了工作,但与建立 Thinktecture的身份认证服务器V 3 我的令牌供应商,但我认为,如果你有另一个令牌提供商将是相同的流....

(更新:我添加了code一个GitHub库:的这里

这是我的启动类:(Identityserver v3还对Vnext了一些小调整运行)。请注意我有服务器,并在同一Web应用程序的网页API。它也行,如果你有两个不同的Web项目,但在这里它是演示的缘故...

 公共类启动
{
    //有关如何配置应用程序的更多信息,请访问:http://go.microsoft.com/fwlink/?LinkID=398940
    公共无效ConfigureServices(IServiceCollection服务)
    {
        services.AddMvc();
    }    公共无效配置(IApplicationBuilder应用程序)
    {
        app.Map(/核心,核心= GT;
        {
            VAR厂= InMemoryFactory.Create(
                                    用户:Users.Get(),
                                    客户端:Clients.Get()
                                    范围:Scopes.Get());            VAR idsrvOptions =新IdentityServerOptions
            {
                IssuerUri =htt​​ps://idsrv3.com
                网站名称=测试vnext身份服务器,
                厂=工厂,
                SigningCertificate = Certificate.Get(),
                RequireSsl =假,                CorsPolicy = CorsPolicy.AllowAll,                AuthenticationOptions =新AuthenticationOptions
                {
                }
            };            core.UseIdentityServer(idsrvOptions);
        });        app.Map(/ API,API = GT;
        {            api.UseOAuthBearerAuthentication(选项=> {
                options.Authority = Constants.AuthorizationUrl;
                options.MetadataAddress = Constants.AuthorizationUrl +/.well-known/openid-configuration
                options.TokenValidationParameters.ValidAudience =htt​​ps://idsrv3.com/resources;
            });            api.UseMvc();        });    }
}

从这里可以看到我的IdentityServerV3被映射到'/核心,并在同一个Web应用程序项目(也可能是另一个),我有一个使用MVC的网页API。下面是控制器:

  [授权]
[路线([控制器])]
公共类测试:控制器
{
    [HTTPGET]
    公共JsonResult获得()
    {
        返回JSON(新
        {
            消息=你看这则它的确定AUTH是:+ User.Identity.IsAuthenticated,
        });
    }
}

我在我的身份的服务器配置客户端:

 新客户
            {
                 //资源所有者流客户端(我们的Web UI)
                CLIENTNAME =WebUI中
                启用=真,                客户端Id =IdentityWebUI
                ClientSecrets =新的List< ClientSecret>
                {
                    新ClientSecret(秘密.Sha256())
                },                流量= Flows.ResourceOwner,
                AccessTokenType = AccessTokenType.Jwt,
                AccessTokenLifetime = 3600            }

和这里的用户(使用InMemory用户):

 返回新的List< InMemoryUser>
        {
            新InMemoryUser
            {
                用户名=为testUser
                密码=testPwd
                主题=我的主题
            }        };

在菲德勒我发出以下POST得到一个承载令牌:

  POST:HTTP://本地主机:4357 /核心/连接/令牌    用户代理:提琴手
    主机:本地主机:4357
    内容长度:67
    内容类型:应用程序/ x-WWW的形式urlen codeD
    授权:基本SWRlbnRpdHlXZWJVSTpzZWNyZXQ =    grant_type =密码&放大器;用户名=&为testUser放大器;密码= testPwd&安培;范围=的OpenID

在响应中,你会得到一个ACCESS_TOKEN

<$p$p><$c$c>{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJJZGVudGl0eVdlYlVJIiwic2NvcGUiOiJvcGVuaWQiLCJzdWIiOiJJIGFtIHRoZSBTdWJqZWN0IiwiYW1yIjoicGFzc3dvcmQiLCJhdXRoX3RpbWUiOjE0MjgzOTQ3MzAsImlkcCI6Imlkc3J2IiwiaXNzIjoiaHR0cHM6Ly9pZHNydjMuY29tIiwiYXVkIjoiaHR0cHM6Ly9pZHNydjMuY29tL3Jlc291cmNlcyIsImV4cCI6MTQyODM5ODMzMCwibmJmIjoxNDI4Mzk0NzMwfQ.cbB4YrRXaaRDNw8BjeI4Q1DvXN28xmJScMJBGWCM_zSLcH1i63cQVTmR8X86rGP5VrR0Ly4-EmWZ8911Vh4jc4Ua0Kgz2n7RbmQ6VqQX5Z_lM3F8EIgD81kpUn0v3hhSFW06aJ2Lo1XOZG_re84xGgqre-H4dC0XZR6IQMEAQ9Q5dOXBh8V1NxyLSh0PzyrRRmOnEndoaY4uaIFtbp9j7KnXxQ3ZdGmaYAO96xuhHfO1DbgRdw6fYyf4nnC795yhnwDh1QZGxPsFaysJSA_3-cjmw-29m-Ga0hD1ALfVE7R57iNLxkB6dyEuz1UFJhJyibRDW9sNspo2gQFZZGxMKQ\",\"expires_in\":3600,\"token_type\":\"Bearer\"}

然后,我使用的access_token打电话给我的web API

这里是小提琴手(以作曲家窗格)

  GET HTTP://本地主机:4357 / API /测试    用户代理:提琴手
    主机:本地主机:4357
    内容长度:0
    内容类型:应用程序/ x-WWW的形式urlen codeD
    授权:承载eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJJZGVudGl0eVdlYlVJIiwic2NvcGUiOiJvcGVuaWQiLCJzdWIiOiJJIGFtIHRoZSBTdWJqZWN0IiwiYW1yIjoicGFzc3dvcmQiLCJhdXRoX3RpbWUiOjE0MjgzOTQ3MzAsImlkcCI6Imlkc3J2IiwiaXNzIjoiaHR0cHM6Ly9pZHNydjMuY29tIiwiYXVkIjoiaHR0cHM6Ly9pZHNydjMuY29tL3Jlc291cmNlcyIsImV4cCI6MTQyODM5ODMzMCwibmJmIjoxNDI4Mzk0NzMwfQ.cbB4YrRXaaRDNw8BjeI4Q1DvXN28xmJScMJBGWCM_zSLcH1i63cQVTmR8X86rGP5VrR0Ly4-EmWZ8911Vh4jc4Ua0Kgz2n7RbmQ6VqQX5Z_lM3F8EIgD81kpUn0v3hhSFW06aJ2Lo1XOZG_re84xGgqre-H4dC0XZR6IQMEAQ9Q5dOXBh8V1NxyLSh0PzyrRRmOnEndoaY4uaIFtbp9j7KnXxQ3ZdGmaYAO96xuhHfO1DbgRdw6fYyf4nnC795yhnwDh1QZGxPsFaysJSA_3-cjmw-29m-Ga0hD1ALfVE7R57iNLxkB6dyEuz1UFJhJyibRDW9sNspo2gQFZZGxMKQ

然后我得到的回应仍然是菲德勒:

您可以通过以下方法<一个更多信息href=\"http://cedric-dumont.com/tutorials/identityserver-v3-membershi$p$pboot-angularjs-webapi-2-and-mvc-mix-it-introduction/identityserver-v3-membershi$p$pboot-angularjs-webapi-2-and-mvc-mix-it-part-1/\"相对=nofollow>以下链接,但它vnext是不相关的。我将创建这个职位,因为我需要一个angularJS应用验证和使用隐式流动,而不是资源所有者流...在Visual Studio 2015年preVIEW

I’m trying to implement OAuth bearer token authentication in ASP.NET 5 and am struggling to find an example of how to do this because the OWIN stuff has changed in ASP.NET 5.

For example IApplicationBuilder.UseOAuthAuthorizationServer() and IApplicationBuilder. UseOAuthBearerAuthentication() either don’t exist anymore or I’m missing a reference?

Any pointers would be greatly appreciated.

解决方案

I did it work, but with setting up Thinktecture's identity server v 3 as my token provider but I think if you have another token provider it will be the same flow....

(update : I added a github repo with the code : here)

here is my startup class: (Identityserver v3 also runs on Vnext with some little tweaking). notice I have the server and the web api in same web app. it's also ok if you have two different web project but here it's for the sake of demo...

public class Startup
{
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.Map("/core", core =>
        {
            var factory = InMemoryFactory.Create(
                                    users: Users.Get(),
                                    clients: Clients.Get(),
                                    scopes: Scopes.Get());

            var idsrvOptions = new IdentityServerOptions
            {
                IssuerUri = "https://idsrv3.com",
                SiteName = "test vnext Identity server",
                Factory = factory,
                SigningCertificate = Certificate.Get(),
                RequireSsl = false,

                CorsPolicy = CorsPolicy.AllowAll,

                AuthenticationOptions = new AuthenticationOptions
                {
                }
            };

            core.UseIdentityServer(idsrvOptions);
        });

        app.Map("/api", api =>
        {

            api.UseOAuthBearerAuthentication(options => {
                options.Authority = Constants.AuthorizationUrl;
                options.MetadataAddress = Constants.AuthorizationUrl + "/.well-known/openid-configuration";
                options.TokenValidationParameters.ValidAudience = "https://idsrv3.com/resources"; 
            });

            api.UseMvc();

        });

    }
}

from here you can see that my IdentityServerV3 is mapped to '/core' and in the same web app project (it could be another one), I have an web api that uses MVC. below is the controller:

  [Authorize]
[Route("[controller]")]
public class Test : Controller
{
    [HttpGet]
    public JsonResult Get()
    {
        return Json(new
        {
            message = "You See this then it's ok auth is  :" + User.Identity.IsAuthenticated,
        });
    }
}

I have configure a Client in my identity server :

  new Client
            {
                 //Resource Owner Flow Client (our web UI)
                ClientName = "WebUI",
                Enabled = true,

                ClientId = "IdentityWebUI",
                ClientSecrets = new List<ClientSecret>
                {
                    new ClientSecret("secret".Sha256())
                },

                Flow = Flows.ResourceOwner,
                AccessTokenType = AccessTokenType.Jwt,
                AccessTokenLifetime = 3600

            }

and here is the User (used InMemory user):

 return new List<InMemoryUser>
        {
            new InMemoryUser
            {
                Username = "testUser",
                Password = "testPwd",
                Subject = "I am the Subject"
            }

        };

In fidler I issue the following POST to get a bearer token:

    POST : http://localhost:4357/core/connect/token

    User-Agent: Fiddler
    Host: localhost:4357
    Content-Length: 67
    Content-Type: application/x-www-form-urlencoded
    Authorization: Basic SWRlbnRpdHlXZWJVSTpzZWNyZXQ=

    grant_type=password&username=testUser&password=testPwd&scope=openid

in the response you will get an Access_token

{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJJZGVudGl0eVdlYlVJIiwic2NvcGUiOiJvcGVuaWQiLCJzdWIiOiJJIGFtIHRoZSBTdWJqZWN0IiwiYW1yIjoicGFzc3dvcmQiLCJhdXRoX3RpbWUiOjE0MjgzOTQ3MzAsImlkcCI6Imlkc3J2IiwiaXNzIjoiaHR0cHM6Ly9pZHNydjMuY29tIiwiYXVkIjoiaHR0cHM6Ly9pZHNydjMuY29tL3Jlc291cmNlcyIsImV4cCI6MTQyODM5ODMzMCwibmJmIjoxNDI4Mzk0NzMwfQ.cbB4YrRXaaRDNw8BjeI4Q1DvXN28xmJScMJBGWCM_zSLcH1i63cQVTmR8X86rGP5VrR0Ly4-EmWZ8911Vh4jc4Ua0Kgz2n7RbmQ6VqQX5Z_lM3F8EIgD81kpUn0v3hhSFW06aJ2Lo1XOZG_re84xGgqre-H4dC0XZR6IQMEAQ9Q5dOXBh8V1NxyLSh0PzyrRRmOnEndoaY4uaIFtbp9j7KnXxQ3ZdGmaYAO96xuhHfO1DbgRdw6fYyf4nnC795yhnwDh1QZGxPsFaysJSA_3-cjmw-29m-Ga0hD1ALfVE7R57iNLxkB6dyEuz1UFJhJyibRDW9sNspo2gQFZZGxMKQ","expires_in":3600,"token_type":"Bearer"}

then I use that access_token to call my web api

here is the fiddler (in composer pane)

    GET http://localhost:4357/api/Test

    User-Agent: Fiddler
    Host: localhost:4357
    Content-Length: 0
    Content-Type: application/x-www-form-urlencoded
    Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJJZGVudGl0eVdlYlVJIiwic2NvcGUiOiJvcGVuaWQiLCJzdWIiOiJJIGFtIHRoZSBTdWJqZWN0IiwiYW1yIjoicGFzc3dvcmQiLCJhdXRoX3RpbWUiOjE0MjgzOTQ3MzAsImlkcCI6Imlkc3J2IiwiaXNzIjoiaHR0cHM6Ly9pZHNydjMuY29tIiwiYXVkIjoiaHR0cHM6Ly9pZHNydjMuY29tL3Jlc291cmNlcyIsImV4cCI6MTQyODM5ODMzMCwibmJmIjoxNDI4Mzk0NzMwfQ.cbB4YrRXaaRDNw8BjeI4Q1DvXN28xmJScMJBGWCM_zSLcH1i63cQVTmR8X86rGP5VrR0Ly4-EmWZ8911Vh4jc4Ua0Kgz2n7RbmQ6VqQX5Z_lM3F8EIgD81kpUn0v3hhSFW06aJ2Lo1XOZG_re84xGgqre-H4dC0XZR6IQMEAQ9Q5dOXBh8V1NxyLSh0PzyrRRmOnEndoaY4uaIFtbp9j7KnXxQ3ZdGmaYAO96xuhHfO1DbgRdw6fYyf4nnC795yhnwDh1QZGxPsFaysJSA_3-cjmw-29m-Ga0hD1ALfVE7R57iNLxkB6dyEuz1UFJhJyibRDW9sNspo2gQFZZGxMKQ

Then I get the response still in fidler:

you can have more info by following this link below, but it's not related to vnext. I will create a post on this as I need an angularJS app to authenticate and use an implicit flow instead of resource owner flow... with visual studio 2015 preview

这篇关于5 ASP.NET承载的OAuth令牌认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆