2017-06-28 26 views
0

MVCプロジェクト内でMVC Web APIを使用しています。私はSimpleAuthorizationServerProviderを使用してトークンを生成しました。私はAuthorizeForAPIカスタム属性を使用してトークンを有効にしました。すべてがうまくいっています。 私の質問は、トークンの有効期限が切れている場合、私は、サーバーからのメッセージが送信されますので、トークンの有効期限を検証する方法では、あなたのトークンは、私が生成する方法をOAuth 2.0トークンの有効期限を確認する方法

これを有効期限が切れてきたユーザーに伝えるトークン

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider 
{ 
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 
    { 
     context.Validated(); 
    } 

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 

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

     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("sub", context.UserName)); 
     identity.AddClaim(new Claim("role", "user")); 

     context.Validated(identity); 

    } 


    public override Task TokenEndpoint(OAuthTokenEndpointContext context) 
    { 
     foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) 
     { 
      context.AdditionalResponseParameters.Add(property.Key, property.Value); 
     } 

     return Task.FromResult<object>(null); 
    } 
} 

そして、これはどうすれば有効なトークン

public class AuthorizeForAPI : AuthorizeAttribute 
{ 

    public override void OnAuthorization(HttpActionContext actionContext) 
    { 
     string AccessTokenFromRequest = ""; 
     if (actionContext.Request.Headers.Authorization != null) 
     { 
      // get the access token 
      AccessTokenFromRequest = actionContext.Request.Headers.Authorization.Parameter; 

      var user = HttpContext.Current.User.Identity; 
      if (!user.IsAuthenticated) 
      { 
       actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized user"); 

      } 
     } 
    } 
} 

}

+0

に私は強くあなたがアクセストークンをgenrateし、検証するためのアイデンティティにJWTのミドルウェアを使用しreccomend分、時間、等のためにそれを変更することができます

AccessTokenExpireTimeSpan = TimeSpan.FromDays(22), //22 day before expired 

を使用。それはすべてのネセサリーチェックを処理します。あなたはトークンをどこで生成するのですか?あなたはアイデンティティを設定しているようです。 – NtFreX

答えて

0

あなたが「timespan.from(本)」

+0

まず、あなたのお手伝いと時間を感謝します。 私の問題は、トークンの有効期限に関する問題ではありません。トークンの期限を有効にする方法、つまり、トークンが期限切れになっているかどうかを知る方法。トークンが期限切れになった場合、セッションが期限切れになったというメッセージをクライアントに送信します。 – Tom

+0

あなたはリアルタイムのようにしたいですか? – QueenQuincy

関連する問題