locked
Authorize through refresh token in asp.net Web API. RRS feed

  • Question

  • User659551701 posted

    I am searching for a hint of my question. My question is that how can I authorize using the access token.  I have my clientID and refresh token. All I needed is how to authorize. Startup Class

    public void Configuration(IAppBuilder app)
    {
    HttpConfiguration config = new HttpConfiguration(); ConfigureOAuth(app); WebApiConfig.Register(config); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    }
    public void ConfigureOAuth(IAppBuilder app)
    {
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
    AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
    Provider = new SimpleAuthorizationServerProvider()
    {
    OnValidateClientAuthentication = async c => { c.Validated();
    },
    OnGrantResourceOwnerCredentials = async c =>
    {
    if (c.UserName == "_User" && c.Password == "_password")
    {
    Claim claim1 = new Claim(ClaimTypes.Name, c.UserName);
    Claim[] claims = new Claim[] { claim1 };
    ClaimsIdentity claimsIdentity = new ClaimsIdentity( claims, OAuthDefaults.AuthenticationType); c.Validated(claimsIdentity);
    }
    }
    },
    RefreshTokenProvider = new RefreshTokenProvider()
    };
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    }

    Webapi
    [HttpPost] [Authorize] [Route("Oauth/Token")]
    public TokenResponse GetResponse(string client_id,string refresh_token,string grant_type)
    { return new TokenResponse() { scope = "Authenticate" }; }
    clientID is in encrypted form. please suggsest if i can send it in decrypted form
    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated();
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    if (context.UserName == "_username" && context.Password == "_password")
    {
    identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
    identity.AddClaim(new Claim("username", "_userName"));
    identity.AddClaim(new Claim(ClaimTypes.Name, "Our System"));
    context.Validated(identity);
    }
    else
    {
    context.SetError("invalid_grant", "Provided username and password is incorrect");
    return;
    }
    }
    }
    public class RefreshTokenProvider : IAuthenticationTokenProvider
    {
    private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
    public void Create(AuthenticationTokenCreateContext context)
    {
    // Expiration time in seconds
    int expire = 12 * 60;
    context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
    context.SetToken(context.SerializeTicket());
    }
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
    var guid = Guid.NewGuid().ToString(); // maybe only create a handle the first time, then re-use
    _refreshTokens.TryAdd(guid, context.Ticket); // consider storing only the hash of the handle
    context.SetToken(guid);
    }
    public void Receive(AuthenticationTokenReceiveContext context)
    {
    context.DeserializeTicket(context.Token);
    }
    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
    AuthenticationTicket ticket;
    if (_refreshTokens.TryRemove(context.Token, out ticket))
    { context.SetTicket(ticket); } } }

    Monday, March 18, 2019 8:50 PM

All replies

  • User36583972 posted


    Hi pirates,

    I am searching for a hint of my question. My question is that how can I authorize using the access token.  I have my clientID and refresh token. All I needed is how to authorize. Startup Class

    From your description, We are not very clear about the specific issue you need to solve. I suggest you can describe clearly and include all necessary code snippets for anyone else to be able to reproduce your issue from scratch along with a detailed description about the results including any exception messages.

    The following links may helpful for you.

    Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2
    https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

    Securing ASP.NET Web API using Token Based Authentication and using it in Angular.js application
    https://www.dotnetcurry.com/aspnet/1223/secure-aspnet-web-api-using-tokens-owin-angularjs

    Best Regards

    Yong Lu

    Tuesday, March 19, 2019 8:29 AM
  • User-2054057000 posted

    The ASP.NET Core has this feature to use 3rd party authentication. Go to your Startup.cs file, and inside its ConfigureServices method, set up the Authentication service and provide the OAuth credentials you got from the provider.

    The code will be:

    services.AddAuthentication().AddGoogle(opts => {
        opts.ClientId = "clientId";
        opts.ClientSecret = "clientsecret";
    });

    In the above code you have to change the .AddGoogle() with your provider method.

    You should also take a look to How to integrate Google login in Identity Membership System

     

    Wednesday, March 20, 2019 9:47 AM