While desinging Rest API ,we almost need to security layer to keep our data source in safety. The most popular authentication is OAuth in last years.
What is OAuth ?
OAuth is an authentication which allow to use RestApi Architecture more secure. There are several type of usage which is seperated with GrantTypes as follow;
Grant Types
- Authorization Code
- Implicit
- Password
- Client Credentials
- Device Code
- Refresh Token
We will explain to usage of Password Grant Type and implement in via Asp.Net Web Api.
So lets follow the basic steps to implement password grant type OAuth2:
- Create a Visual Studio Project as Asp.Net Web Api project.
- As default we have a ValuesController which allow to call http get : http://localhost:3221/api/values without any security control.
- Lets call http://localhost:3221/api/values url to see data before implement anything.
- Add new item in App_Start folder as Startup.cs.
- Add the following codes into Startup File configuration method.
public void Configuration(IAppBuilder app)
{
HttpConfiguration httpConfiguration = new HttpConfiguration();
this.ConfigureAuth(app);
WebApiConfig.Register(httpConfiguration);
app.UseWebApi(httpConfiguration);
}
private void ConfigureAuth(IAppBuilder appBuilder)
{
OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true,
Provider = new ICRONClientAuthorizationServerProvider()
};
//fill the settings for OAuth to create new token properly
appBuilder.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);
appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
- Create folder in root as OAuth then add new class into this directory as Provider
resource:
https://oauth.net/2/grant-types/