Generate bearer token using c#

37,425

Solution 1

I followed below article http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

Downloaded their sourcecode and checked it. They have good example on how to create token.

Solution 2

If you have created a new ASP.NET Web Application -> Web API with Individual User Accounts. Have a look at App_Start -> Startup.Auth.cs.

It should contain something like this:

PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);

This means that you can send a request for an access token, example request:

enter image description here

You can then verify that the access token works:

enter image description here

With this token you can now access all protected resources that the user has access to.

Solution 3

Asp.net default implementation will use DPAPI in your Authorization Server, so it will use the “validationKey” value in machineKey node stored in machine.config file to issue the access token and protect it. The same case applies when you send the access token to your Resource Server, it will use the same machineKey to decrypt the access token and extract the authentication ticket from it.

ASP.NET

If you want to generate a JWT encoded Bearer Token, you should override ISecureDataFormat<AuthenticationTicket>.Protect() Method:

CustomJwtFormat.cs

    string symmetricKeyAsBase64 = audience.Base64Secret;
    var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
    var signingKey = new HmacSigningCredentials(keyByteArray);
    var issued = data.Properties.IssuedUtc;             var expires = data.Properties.ExpiresUtc;
    JwtSecurityToken token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime,expires.Value.UtcDateTime, signingKey);
    var handler = new JwtSecurityTokenHandler();
    //serialize the JSON Web Token to a string
    var jwt = handler.WriteToken(token);
    return jwt;

Add your custom JWT formatter to OAuth Option

  OAuthAuthorizationServerOptions OAuthServerOptions = new 
  OAuthAuthorizationServerOptions()
        {
            //For Dev enviroment only (on production should be AllowInsecureHttp = false)
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/oauth/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            AccessTokenFormat = new CustomJwtFormat("http://localhost:5001")
        };

        //  Generation and validation
        app.UseOAuthBearerTokens(OAuthServerOptions);

The app.UseOAuthBearerTokens helper method creates both the token server and the middleware to validate tokens for requests in the same application.

If this is an Authorization server(generate token) , you should use app.UseOAuthAuthorizationServer(OAuthServerOptions) in the last line

ASP.NET Core

Unforturnately, the ASP.NET team simply decided not to port OAuthAuthorizationServerMiddleware to asp.net core: https://github.com/aspnet/Security/issues/83

community-provided, open source authentication options for ASP.NET Core:

AspNet.Security.OpenIdConnect.Server:low-level, protocol-first OpenID Connect server framework for ASP.NET Core and OWIN/Katana.

IdentityServer:OpenID Connect and OAuth 2.0 framework for ASP.NET Core, officially certified by the OpenID Foundation and under governance of the .NET Foundation.

OpenIddict: easy-to-use OpenID Connect server for ASP.NET Core.

Share:
37,425
Ravindra Kumar Challagandla
Author by

Ravindra Kumar Challagandla

Updated on March 27, 2020

Comments

  • Ravindra Kumar Challagandla
    Ravindra Kumar Challagandla about 4 years

    I have a web application. My requirement is that i need to generate oauth2 bearer token on every login. Currently we are using thinktecture to generate token, but this procedure is taking almost 7 seconds to generate token everytime. Is there any way i can generate token without using thinktecture ?