locked
how can i make header Authorization bearer “token” invalid if request another login api RRS feed

  • Question

  • User2131089582 posted

    my access_token always valid although it has already change to another access token

    i'm building login api using jwt in asp net, by following this tutorial https://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

    here is my code for oauth provider *

    using System.Linq;
    using System.Web;
    namespace BusinessTranslation.UserAccount
    {
        using System;
        using System.Collections.Generic;
        using System.Security.Claims;
        using System.Threading.Tasks;
        using Microsoft.Owin.Security.OAuth;
        using Microsoft.AspNet.Identity.Owin;
        using Microsoft.Owin.Security;
        using Services;
        using Libraries;
        using Services.Subscription;
        /// <summary>
        /// Another important is on Auth
        /// </summary>
        public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
        {
            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 override Task MatchEndpoint(OAuthMatchEndpointContext context)
            //{
            //    if (context.IsTokenEndpoint && context.Request.Method == "OPTIONS")
            //    {
            //        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "authorization" });
            //        context.RequestCompleted();
            //        return Task.FromResult(0);
            //    }
            //    return base.MatchEndpoint(context);
            //}
            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                // Resource owner password credentials does not provide a client ID.
                if (context.ClientId == null)
                {
                    context.Validated();
                }
                return Task.FromResult<object>(null);
            }
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var data = await context.Request.ReadFormAsync();
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
                var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
                ApplicationUser user = await userManager.FindByNameAsync(context.UserName);
                if (user == null)
                {
                    context.SetError("invalid_user", ConstantsMessage.EmailIsNotAvailableMsg);
                    return;
                }
    
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
                foreach (var item in user.Roles)
                {
                    string name = FactoryService.CreateAppRole().InitModel().FindById(item.RoleId).FirstOrDefault().Name;
                    identity.AddClaim(new Claim(ClaimTypes.Role, name));
                }
                int membershipType = (int)MembershipSvc.Instance.CheckUserIsPremium(user.UserName);
                AuthenticationProperties properties =
                    CreateProperties(user.UserName,
                    string.Join(":", user.Roles.Select(c => FactoryService.CreateAppRole().InitModel().FindById(c.RoleId).FirstOrDefault().Name))
                );
                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
                context.Validated(ticket);
            }
            public static AuthenticationProperties CreateProperties(string userName, string Roles)
            {
                IDictionary<string, string> data = new Dictionary<string, string>
                {
                    {"userName", userName },
                    {"roles",Roles}
                };
                return new AuthenticationProperties(data);
            }
        }
    }

    *

    I'm success to create it, but i have problem when i access login api (in postman) by entering right credential, i will get something like this

    {
        "access_token": "suHuxUqYTAdsyW23trucHDZ2xq2ZyYMoub1bq-xHCka0EvqwxBDY8Ut8BtxDlfm1OPHddJ3h8xyreX6TBgJmDnV7G4sVLTyRaVk4KXyTF5zsGodvDesE7ia6YLE1n_vIMYTjM4zzHJNZfMyE8d6CBdVFcQMP6uMaCPtW9rFu8h8JP35lKAtPRoRJJgECZOggFeaYXZcxvKYsrFAkYahejLkSom1HkRrq0M3fDv6Zb4u9_FjuqpwbtupVOw7HDpHwHS1hjEeXjyty5A5nIo8tz6lJQ70DS6okFP_OqGL5i5lNK3CBcADCyOewRIK1PMxGocCIuUUQKpRufwJwNJkiYKoVNyRLXqtcH55hTLOfxS_fBK7h87s7gstZeglbGyFzqQZ8RvKMT4WCRca4kBbY0HG0PJc66Pou3480dqLJi1M",
        "token_type": "bearer",
        "expires_in": 31535999,
        "userName": "xyz@gmail.com",
        "roles": "SuperAdmin",
        ".issued": "Sat, 26 Oct 2019 22:10:12 GMT",
        ".expires": "Sun, 25 Oct 2020 22:10:12 GMT"
    }

    everytime i press or test the login api i must always get new access token this is sample for my second request

    {
        "access_token": "dwFRwsU9AOZIHL_YccU9Xi90pojpYg8zrSEmHSjKL5TErM7Vs9psmPtZw0HuScB89XZ8T5263KzZum3bWDsGfKdGd7cIe187YAXxwiE2qM7xgnOiX5f02PvVyddE6xCrsZHRyOaO4lV7Aw_qiUsqBi12hwewq78CJ5ONSkZHbna6B67vQGuZ-wwYbVfOM9GLdciDMdsc5AUzyWf7Fp_XmjVfJhaFwv-3amGKT0jXsS85_cKPFky7L6gInAWxF3VJt6gmASaz_xAvOXfpp4ggWW3G-AqYOr22P3_aOGay_ANO5z68IG4CYFKRIja3kVvvc4MAtTz0BXHFD25JxJxkl3_vQiRDCyLnDMCS2UNAM9zdYnD4riq0TI-xgslCOkVHaecn7J082eC-Zws9r1zmR-ovjvmRcu5zTQzqupg5I7U",
        "token_type": "bearer",
        "expires_in": 31535999,
        "userName": "xyz@gmail.com",
        "roles": "SuperAdmin",
        ".issued": "Sat, 26 Oct 2019 22:11:34 GMT",
        ".expires": "Sun, 25 Oct 2020 22:11:34 GMT"
    }

    how can i check the first token is invalid and it should change to the second token ?

    ok here is the implementation first i login using device A, then i get first token json then i login using same account in device B, then i get the second token json of course the first token on device A will invalid and when device A added a header Authorization bearer "sometoken" it will not invalid anymore or failed how can i check that

    </div> <div class="post-taglist grid gs4 gsy fd-column"></div> </div>

    Saturday, October 26, 2019 10:27 PM

All replies

  • User475983607 posted

    how can i check the first token is invalid and it should change to the second token ?

    As far as I can tell, the login is functioning as expected.  A token is exchanged for a valid username and password.  Why should the first token become invalid?

    ok here is the implementation first i login using device A, then i get first token json then i login using same account in device B, then i get the second token json of course the first token on device A will invalid and when device A added a header Authorization bearer "sometoken" it will not invalid anymore or failed how can i check that

    If I understand you designed code that does not allow multiple active logins for a single user.  The code shown does not have this functionality.  Share the code that invalids tokens.

    Sunday, October 27, 2019 12:27 PM
  • User-474980206 posted

    You are confusing your tokens. Both tokens a good for a year. The first token given by the oauth server only has the user name. The second token has the access allowed for your application. You should use a tool to dump the tokens payload (data between first and second dots) which is in base64 url encoding.

    if you look at the content you will see the difference.

    Sunday, October 27, 2019 3:28 PM
  • User2131089582 posted

    Yes thank for your answer, my problem is same as this https://stackoverflow.com/questions/24733718/how-to-make-bearer-token-invalid

    i have reasearched and it says i have to using refresh token right ?

    Sunday, October 27, 2019 9:48 PM
  • User2131089582 posted

    Sorry i don't understand with you mean my target is something like this https://stackoverflow.com/questions/24733718/how-to-make-bearer-token-invalid

    Sunday, October 27, 2019 9:49 PM
  • User475983607 posted

    Yes thank for your answer, my problem is same as this https://stackoverflow.com/questions/24733718/how-to-make-bearer-token-invalid

    i have reasearched and it says i have to using refresh token right ?

    No.  A refresh token does not invalidate an access token it does the opposite by definition.  A refresh token refreshes the access token. As state above, if you wish to invalidate a token you need to design and write code.  Design a table  that stores information about every token created by your token server.  You'll check this table when the user logs in and  invalidate a previous token if the user has an active token.  You'll also use this table on every request to see if the token has been invalidated.  

    Sunday, October 27, 2019 10:27 PM
  • User2131089582 posted

    it seems good approach with your sheme, how should i compare a token from my client with current token on database

    Sunday, October 27, 2019 10:50 PM
  • User2131089582 posted

    so it does not invalid the first token if using refresh token ?

    Sunday, October 27, 2019 10:51 PM
  • User-474980206 posted

    a token goes invalid when it expires. The tokens you have last 1 year. You can also add addition validation by checking the payload. This what the validation logic is for if you need validation beyond expiration  and the hash code.

    Usually you use a refresh token with a long expiration and bearer tokens with a short. In your case the bear tokens also are long lived.

    Sunday, October 27, 2019 11:27 PM
  • User2131089582 posted

    ok i see so what is the right solution with my problem.

    it doesnot relate with expires token or not

    i want to make an old token invalid when new token requested

    Sunday, October 27, 2019 11:55 PM
  • User475983607 posted

    ok i see so what is the right solution with my problem.

    it doesnot relate with expires token or not

    i want to make an old token invalid when new token requested

    This is a basic state management design question.  It is up to you to design and write code that fits your requirement.

    Monday, October 28, 2019 11:16 AM
  • User-474980206 posted

    ok i see so what is the right solution with my problem.

    it doesnot relate with expires token or not

    i want to make an old token invalid when new token requested

    then you should use a key value (say the username) and counter  in the payload and store on your server. Increment the counter when you assign a ticket. Then add to the ticket validation a check if the counter is valid.

    Monday, October 28, 2019 1:52 PM