0

Asp.Net MVC Identity 2.0을 작동시키는 법을 배우고 있습니다.OAuth 베어러 인증을위한 ASP.NET MVC ID 해설

나는 ClaimsIdentity 및 AuthenticationTicket 및 I의 소스 코드를 살펴 보았다

//This will used the HTTP header Authorization: "Bearer 1234123412341234asdfasdfasdfasdf" 
    OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); 
    app.UseOAuthBearerAuthentication(OAuthBearerOptions); 

Startup.Auth.cs에 대한 코드는 다음 OAuth를 무기명에 대한

[HttpGet] 
    [ActionName("Authenticate")] 
    [AllowAnonymous] 
    public String Authenticate(string user, string password) 
    { 
     if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password)) 
     { 
      return "Failed"; 
     } 

     var userIdentity = UserManager.FindAsync(user, password).Result; 
     if (userIdentity != null) 
     { 
      if (User.Identity.IsAuthenticated) 
      { 
       return "Already authenticated!"; 
      } 

      var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); 
      identity.AddClaim(new Claim(ClaimTypes.Name, user)); 
      identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id)); 

      AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); 
      var currentUtc = new SystemClock().UtcNow; 
      ticket.Properties.IssuedUtc = currentUtc; 
      ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(1)); 

      string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); 
      return AccessToken; 
     } 
     return "Failed in the end"; 
    } 

작동이 코드가 티켓이 신원에 어떻게 등록되어 있는지 보지 마십시오.

제 질문은이 티켓이 Owin 파이프 라인에 어떻게 등록 되었습니까?

가능한 경우이 티켓을 취소하는 것이 목표입니다.

미리 감사드립니다.

답변

0

먼저 Taiseer Joudeh의 great tutorial on ASP.NET Identity 2입니다.

이것은 OWIN 응용 프로그램 파이프 라인에 무기명 토큰 처리를 추가하는 줄입니다.

app.UseOAuthBearerAuthentication(OAuthBearerOptions); 

또한 인증 제공자를 직접 작성 했습니까? 내 시작 코드 더 다음과 같습니다

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
{ 
    var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*"; 

    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); 

    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); 

    ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); 

    if (user == null) 
    { 
     context.SetError("invalid_grant", "The user name or password is incorrect."); 
     return; 
    } 

    var identity = new ClaimsIdentity(context.Options.AuthenticationType); 
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); 
    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); 
    identity.AddClaim(new Claim("sub", context.UserName)); 

    foreach (var role in userManager.GetRoles(user.Id)) 
    { 
     identity.AddClaim(new Claim(ClaimTypes.Role, role)); 
    } 

    var props = new AuthenticationProperties(new Dictionary<string, string> 
    { 
     {"as:client_id", context.ClientId ?? string.Empty} 
    }); 

    var ticket = new AuthenticationTicket(identity, props); 
    context.Validated(ticket); 
} 

이 단지에 대한 모든이의 위에서 언급 한 튜토리얼을 기반으로했다 :

app.CreatePerOwinContext(ApplicationDbContext.Create); 
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 

PublicClientId = "self"; 
OAuthServerOptions = new OAuthAuthorizationServerOptions 
{ 
    AllowInsecureHttp = true, 
    TokenEndpointPath = new PathString("/Token"), 
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1440),  //TODO: change to smaller value in production, 15 minutes maybe 
    Provider = new SimpleAuthorizationServerProvider(PublicClientId), 
    RefreshTokenProvider = new SimpleRefreshTokenProvider() 
}; 

app.UseOAuthAuthorizationServer(OAuthServerOptions); 

OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); 
app.UseOAuthBearerAuthentication(OAuthBearerOptions); 

내 SimpleAuthorizationServerProvider는이 같은 부여 방법이있다. 희망이 도움이됩니다.

업데이트 는 Taiseer on this page에 따라 토큰을 취소하기위한 표준 방법은 없습니다. 인증 된 사용자의 액세스를 해지

: 사용자 일단 오래 그는 오랫동안 자신의 액세스 토큰이 만료되지 않는 서버 자원 에 액세스 할 수 있습니다 액세스 토큰을 살았 획득하고, 표준 방법 에 없다 권한 서버가 사용자 정의 로직을 구현하지 않는 한 액세스 토큰을 취소하여 생성 된 액세스 토큰을 데이터베이스에 저장하고 각 요청마다 데이터베이스 점검을 수행하도록하십시오. 그러나 새로 고치는 토큰을 사용하면 시스템 관리자는 데이터베이스에서 새로 고침 토큰 식별자를 삭제하기 만하면 액세스를 취소 할 수 있으므로 시스템에서 삭제 된 새로 고침 토큰을 사용하여 새 액세스 토큰을 요청하면 인증 서버는 새로 고침 토큰 더 이상 을 사용할 수 없습니다 (자세한 내용은 여기에 있습니다).

그러나, 필요한 것을 달성 할 수있는 here is an interesting approach. 약간의 맞춤 구현이 필요합니다.

+0

답장을 보내 주셔서 감사합니다. 네, 타이세이의 튜토리얼을 공부했는데 아주 좋습니다. 내가 게시 한 코드도 똑같이 작동합니다. 내가 티켓을 취소 할 수있는 방법이 있는지 알고 싶습니다. – superfly71

+0

@ superfly71 게시물을 업데이트했습니다. 원하는 것을 성취하기 위해 새로 고침 토큰을 구현해야한다고 생각합니다. – BBauer42

+0

내가 제공 한 링크에서 언급 한 블랙리스트 접근 방식을 실제로 채택했습니다. 나는 더 나은 접근법을 기대하고 있었다. 아무튼 감사 해요! – superfly71