Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API OAUTH - Distinguish between if Identify Token Expired or UnAuthorized

Am currently developing an Authorization server using Owin, Oauth, Claims.

Below is my Oauth Configuration and i have 2 questions

 OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
  {

     AllowInsecureHttp = true,
     TokenEndpointPath = new PathString("/token"),
     AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(1000),
     Provider = new AuthorizationServerProvider()
     //RefreshTokenProvider = new SimpleRefreshTokenProvider()
  };
     app.UseOAuthAuthorizationServer(OAuthServerOptions);
     app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

If the token is expired and user accessing using the expired token user is getting 401(unAuthorized).Checking using Fiddler.

How can i send a customized message to an user stating your token as expired. Which function or module i need to override.

and my another quesiton is What is the use of the below line ?

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); Do i really need this to implement because when i checked it still works without the above line. Any security violation ?

like image 750
Peru Avatar asked Aug 24 '15 11:08

Peru


People also ask

How do I know if my OAuth token is expired?

You can confirm your expiration date anytime by going to Settings > WorkSpace Settings > Social Accounts. Then simply look under the Token Status to learn the expiration date of your accounts token. (This means ContentStudio has access to your social networks for 39 days.

What happens when OAuth token expires?

When a token has expired or has been revoked, it can no longer be used to authenticate Git and API requests. It is not possible to restore an expired or revoked token, you or the application will need to create a new token. This article explains the possible reasons your GitHub token might be revoked or expire.

How do you check JWT token is expired or not online?

You can use a lib(like jwt_decode) to decode your JWT token, where it's most likely contains an expiration timestamp that you can check(compare it with the current timestamp for this moment) and if it exceeded(expired) just delete it from local storage and redirect user to login page.


1 Answers

You can't directly customize the behavior for expired tokens but you can do that with a custom middleware.

First override the AuthenticationTokenProvider so that you can intercept the authentication ticket before it is discarded as expired.

public class CustomAuthenticationTokenProvider : AuthenticationTokenProvider
{
    public override void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket != null &&
            context.Ticket.Properties.ExpiresUtc.HasValue &&
            context.Ticket.Properties.ExpiresUtc.Value.LocalDateTime < DateTime.Now)
        {
            //store the expiration in the owin context so that we can read it later a middleware
            context.OwinContext.Set("custom.ExpriredToken", true);
        }
    }
}

and configure it in the Startup along with a small custom middleware

using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
    AccessTokenProvider = new CustomAuthenticationTokenProvider()
});

//after the request has been authenticated or not
//check for our custom env setting and act accordingly
app.Use(new Func<AppFunc, AppFunc>(next => (env) =>
{
    var ctx = new OwinContext(env);
    if (ctx.Get<bool>("custom.ExpriredToken"))
    {
        //do wathever you want with the response
        ctx.Response.StatusCode = 401;
        ctx.Response.ReasonPhrase = "Token exprired";

        //terminate the request with this middleware
        return Task.FromResult(0);
    }
    else
    {
        //proceed with the rest of the middleware pipeline
        return next(env);
    }
}));

If you have noticed I've placed the custom middleware after the call to UseOAuthBearerAuthentication and this is important and stems from the answer to your second question.

The OAuthBearerAuthenticationMidlleware is responsible for the authentication but not for the authorization. So it just reads the token and fills in the information so that it can be accessed with IAuthenticationManager later in the pipeline.

So yes, with or without it all your request will come out as 401(unauthorized), even those with valid tokens.

like image 145
Angel Yordanov Avatar answered Sep 23 '22 03:09

Angel Yordanov