Öncelikle nuget arayıcığıyla aşağıdaki paketleri yüklüyoruz.
- Microsoft.AspNet.WebApi.Owin
- Microsoft.Owin.Host.SystemWeb
- Microsoft.Owin.Security.OAuth
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
try
{
HttpConfiguration httpConfiguration = new HttpConfiguration();
ConfigureOAuth(appBuilder);
WebApiConfig.Register(httpConfiguration);
appBuilder.UseWebApi(httpConfiguration);
}
catch (Exception ex)
{
throw;
}
}
private void ConfigureOAuth(IAppBuilder appBuilder)
{
try
{
OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/token"), // token alacağımız path'i belirtiyoruz
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(15),
AllowInsecureHttp = true,
Provider = new SimpleAuthorizationServerProvider(),
RefreshTokenProvider = new SimpleRefreshTokenProvider()
};
appBuilder.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);
appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
catch (Exception)
{
OwinResponse response = new OwinResponse();
response.Context.TraceOutput.ToString();
}
}
}
SimpleAuthorizationServerProvider.cs
public class SimpleAuthorizationServerProvider: OAuthAuthorizationServerProvider
{
// OAuthAuthorizationServerProvider sınıfının client erişimine izin verebilmek için ilgili ValidateClientAuthentication metotunu override ediyoruz.
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
// OAuthAuthorizationServerProvider sınıfının kaynak erişimine izin verebilmek için ilgili GrantResourceOwnerCredentials metotunu override ediyoruz.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// CORS ayarlarını set ediyoruz.
// CORS domain’ler arası kaynak paylaşımını sağlamaya yarayan bir mekanizmadır. Bir domain’in bir başka domain’in kaynağını kullanabilmesini sağlar.
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
// Kullanıcının access_token alabilmesi için gerekli validation işlemlerini yapıyoruz.
if (context.UserName == "Emre" && context.Password == "123456")
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "Kullanıcı adı veya şifre yanlış.");
}
}
}
SimpleRefreshTokenProvider.cs
public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
Create(context);
}
public void Create(AuthenticationTokenCreateContext context)
{
object owinCollection;
context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out owinCollection);
var grantType = ((FormCollection)owinCollection)?.GetValues("grant_type").FirstOrDefault();
if (grantType == null || grantType.Equals("refresh_token")) return;
//Dilerseniz access_token'dan farklı olarak refresh_token'ın expire time'ını da belirleyebilir, uzatabilirsiniz
context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddMinutes(15);
context.SetToken(context.SerializeTicket());
}
public void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
if (context.Ticket == null)
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
context.Response.ReasonPhrase = "invalid token";
return;
}
context.SetTicket(context.Ticket);
}
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
Receive(context);
}
}
TokenController
public class TokenController : ApiController
{
[HttpGet]
[Authorize]
public List<string> List()
{
List<string> orders = new List<string>();
orders.Add("elma");
orders.Add("armut");
orders.Add("erik");
return orders;
}
}
Apiye istek attığımızda henüz token olmadığından hata verecektir. Öncelikle /token diyerek token oluşturuyoruz. Token oluştururken Headers kısmına; Accept : application/json Content-Type : application/x-www-form-urlencoded Body kısmına; grant_type : password username : kullaniciadi password : şifre bilgileri girilip POST olarak çalıştırılmalıdır. Bize dönen Token’ı kopyalayarak bu sefer apiye istek atabiliriz. Apiye istek atarken headers kısmında Authorization: Bearer KOPYALADIĞIMIZ TOKEN şeklinde istek attığımızda sonuç dönecektir.