简体   繁体   English

ASP.NET Identity 2.0针对我们自己的承载服务器进行身份验证

[英]ASP.NET Identity 2.0 Authenticate against our own bearer server

All, 所有,

I've got a security server which sole purpose is to provide bearer tokens from a single endpoint: http://example.com/token 我有一个安全服务器,其唯一目的是从单个端点提供承载令牌: http//example.com/token

Example request: 示例请求:

POST http://example.com/token HTTP/1.1
User-Agent: Fiddler
Content-Type: x-www-form-urlencoded
Host: example.com
Content-Length: 73

grant_type=password&username=example@example.com&password=examplePassword

Example response: 响应示例:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Tue, 16 Aug 2016 12:04:39 GMT
{
  "access_token": "xxxx",
  "token_type": "bearer",
  "expires_in": 17999,
  "refresh_token": "xxxx",
  ".issued": "Tue, 16 Aug 2016 12:04:38 GMT",
  ".expires": "Tue, 16 Aug 2016 17:04:38 GMT"
}

We have an angular application which uses this endpoint to authenticate, and does so just fine. 我们有一个角度应用程序,它使用此端点进行身份验证,并且这样做很好。

What we are trying to achieve without much success is to create an MVC application which uses the same server to authenticate, we'd like the code to sit on top of Identity 2.0 if possible. 我们试图在没有太大成功的情况下实现的是创建一个使用相同服务器进行身份验证的MVC应用程序,我们希望代码尽可能位于Identity 2.0之上。

In our AccountController (example project) we have our Login(LoginModel model) method which handles login and looks like this (same as example project template): 在我们的AccountController (示例项目)中,我们有Login(LoginModel model)方法来处理登录并且看起来像这样(与示例项目模板相同):

var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);

We have our own implemention of IUserStore, UserManager, SignInManager. 我们有自己的IUserStore,UserManager,SignInManager实现。

I've considered overriding 我考虑过压倒一切

public Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout) on `SignInManager<,>` and make a web call across to the security server.

The default implementation of PasswordSignInAsync calls UserManager.FindByNameAsync however this would mean I'd have to expose a lookup method on my security server to confirm a username exists which really doesn't sound good. PasswordSignInAsync的默认实现调用UserManager.FindByNameAsync但是这意味着我必须在我的安全服务器上公开查找方法以确认存在真正听起来不太好的用户名。

I must be missing something and I know it wouldn't be this complicated, our MVC app needs to use cookie authentication but also maintain the bear token for subsequent calls to our other resource server. 我必须遗漏一些东西而且我知道它不会那么复杂,我们的MVC应用程序需要使用cookie身份验证,但也为后续调用我们的其他资源服务器维护熊令牌。

(I appreciate I might be mixing up technologies here, hence the question). (我很欣赏我可能会在这里混合技术,因此问题)。

This is also running on OWIN. 这也在OWIN上运行。

In this case, I don't think you should use Identity 2.0 in your MVC application. 在这种情况下,我认为您不应该在MVC应用程序中使用Identity 2.0。 You should create an AuthenticationClient to call your authentication server, you could also use this library to build such a client https://www.nuget.org/packages/Thinktecture.IdentityModel.Client/ 您应该创建一个AuthenticationClient来调用您的身份验证服务器,您也可以使用此库来构建这样的客户端https://www.nuget.org/packages/Thinktecture.IdentityModel.Client/

public class AuthenticationClient {
    public ClaimsIdentity GetClaimsIdentity(string username, string password) {
         //Call your authentication server to get your token and also claims associated with your identity.
         //You can look at an example code how to do it: https://github.com/IdentityServer/IdentityServer3.Samples/blob/master/source/Clients/ConsoleResourceOwnerClient/Program.cs
         //and create a ClaimsIdentity object out of those information

         var identity = GetIdentity();

         //The key point here is to add AccessToken and RefreshToken as custom claims to your identity so you retrieve these tokens back on subsequent requests.
        identity.AddClaim(new Claim("access_token", accessToken));
        identity.AddClaim(new Claim("refresh_token", refreshToken));
    }
}

This will fulfill your requirements: 这将满足您的要求:

Use cookie authentication but also maintain the bear token for subsequent calls to our other resource server. 使用cookie身份验证,但也为后续调用我们的其他资源服务器维护熊令牌。

Your Login method on AccountController should be like this: 您在AccountController上的Login方法应如下所示:

public ActionResult Login(LoginModel model)
{
     var identity = authenticationClient.GetClaimsIdentity(model.UserName, model.Password);

     if (identity == null) {
         return new HttpUnauthorizedResult();
     }
     //Sign in the user
     var ctx = Request.GetOwinContext();
     var authenticationManager = ctx.Authentication;
     authenticationManager.SignIn(identity);

     return new HttpStatusCodeResult(HttpStatusCode.OK);
}

I assume that you already register this middleware to use Cookie authentication: 我假设您已经注册此中间件以使用Cookie身份验证:

public void ConfigureAuth(IAppBuilder app)
{
   app.UseCookieAuthentication(new CookieAuthenticationOptions
   {
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
      LoginPath = new PathString("/Account/Login")
   });
}

Now for all subsequent requests, you could retrieve back the access token to call your resource server from your ClaimsIdentity: 现在,对于所有后续请求,您可以检索访问令牌以从您的ClaimsIdentity调用资源服务器:

User.Identity.Claims.FirstOrDefault(x => x.Type == "access_token");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 asp.net Identity 2.0可以在自己的项目中运行吗? - Can asp.net identity 2.0 run in it's own project? Identity Server 4(2.0)不读取Asp.Net核心标识cookie - Identity Server 4 (2.0) not reading Asp.Net Core Identity cookies ASP.NET使用身份,针对不同的身份前身份数据库进行身份验证 - ASP.NET using identity, authenticate against a different pre-identity membership database 具有承载令牌的Asp.Net身份IUserSecurityStampStore - Asp.Net Identity IUserSecurityStampStore with Bearer Tokens 使用 Identity 2.0 数据库对 ASP.NET Core 1.0 应用程序进行身份验证 - Use a Identity 2.0 Database to Authenticate a ASP.NET Core 1.0 application JWT 不记名令牌不适用于 ASP.Net Core 3.1 + Identity Server 4 - JWT Bearer Token not working with ASP.Net Core 3.1 + Identity Server 4 ASP.NET 核心 API 使用 JWT 不记名令牌进行身份验证 - ASP.NET Core API authenticate using JWT bearer tokens 如何使用asp.net Identity 2.0授权用户仅查看自己的记录 - How to authorize a user to only see his own records with asp.net Identity 2.0 Ninject 和 ASP.NET Identity 2.0 - Ninject and ASP.NET Identity 2.0 Identity 2.0 中的 ASP.NET 角色管理 - ASp.net Role management in Identity 2.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM