Skip to content

lzh-boy/bearer-authentication

Repository files navigation

bearer-authentication

Contents

NuGet Installation

Install-Package BearerAuthentication

You can find the NuGet package here

About

Bearer authentication is an easy way to implement token authentication on your WebAPI.

Simple to implement.

Implementation

First of all you need to add these three keys on your Web.config to have your own crypto keys, I recommend to change the values.

<add key="BearerAuthentication.Crypto.PasswordHash" value="MYP4SSW0RDH4SH"/>
<add key="BearerAuthentication.Crypto.SaltKey" value="S@LTK3Y"/>
<add key="BearerAuthentication.Crypto.VIKey" value="V1KEY"/>

If you want to add expire time on access token just add

<add key="BearerAuthentication.ExpireMinutes" value="60"/>

Then in your FilterConfig.cs need to add BearerAuthenticationFilter

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterWebApiFilters(System.Web.Http.Filters.HttpFilterCollection filters)
    {
        filters.Add(new BearerAuthenticationFilter());
    }
}

and you alter Global.asax.cs should be like this, adding the Filter, and adding the Application_PostAuthorizeRequest method

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);

    //REGISTERING MY FILTERS
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    FilterConfig.RegisterWebApiFilters(GlobalConfiguration.Configuration.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

protected void Application_PostAuthorizeRequest()
{
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

To finish you need to implement the step in which the user logs into the system, then it will look like this

BearerToken bearerToken = new BearerToken();
bearerToken.GenerateHeaderToken(user.identifier, user.email);

Then after this step, the access_token will always be updated with each request, so it is necessary that always send the latest access_token

Ok, now you can be happy with Bearer Authentication =)

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages