Merhaba Arkadaşlar,
Bu makalemde sizlere mobile uygulamlara açtığımız restful servislerde nasıl güvenlik önlemleri alabiliriz bunun hakkında bilgi vermeye çalışacam.Öncelikle ben bir web API uygulaması açıyorum.Bu uygulamayı açtıktan sonra nuget’tan aşağıdaki eklemeleri projemize yapıyouz.
install-package Microsoft.Owin
Microsoft.Owin.Cors
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Securit
Microsoft.Owin.Security.Cookies
Microsoft.Owin.Security.OAuth
Microsoft.AspNet.WebApi
Microsoft.AspNet.Web.Optimization
Microsoft.AspNet.WebApi.WebHost
bu eklemeleri yaptıktan sonra artık kod üzerinde işlemlerimizi yapmaya başlayalım.
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString(“/authtoken”),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
bool isValidUser = false;
context.OwinContext.Response.Headers.Add(“Access-Control-Allow-Origin”, new[] { “*” });
if(context.UserName == “brk” && context.Password == “123”)
{
isValidUser = true;
}
if (!isValidUser)
{
context.SetError(“invalid_grant”, “Kullanıcı ad yada şifre hatalı”);
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(“sub”, context.UserName));
identity.AddClaim(new Claim(“role”, “user”));
context.Validated(identity);
}
}
public class ProductsController : ApiController
{
public ProductsController()
{
db = new SucuDBEntities();
}
SucuDBEntities db;
// GET api/values
[HttpGet]
[Authorize]
public List GetProducts()
{
return db.Products.Select(x => new ProductDTO { Name=x.ProductName, Price=x.UnitPrice,Id=x.ProductID}).ToList();
}
}
Şimdi istersen Fiddler composer kullanarak deneyin isterseniz direk mobile uygulama HttpPost ve HttpGet ilede deneyebilirsiniz.
http://localhost:2418/authtoken adresine post isteği ile
Request’in body kısmına aşağıdaki kod satırını
grant_type=password&username=brk&password=123
ile istekte bulunuyorum.Daha sonra response da aşağıdaki json sonucu göreceğiz.
{
"access_token"
:
"fGRssefsd-123sdfFSFczzfse..."
,
"token_type"
:
"bearer"
,
"expires_in"
:86399
}
burada bizim için access_token idsi önemli.Bu id ile artık ProductController’dan güvenli bir şekilde veri çekebileceğiz.Son olarak
http://localhost:2418/api/Products ‘a Get ile istekte bulunduğumuzda aşağıdaki Requestheader ile erişimimiz başarılı bir şekilde gerçekleşecek.
Authorization: Bearer fGRssefsd-123sdfFSFczzfse…
Kodumuzun hayrını görün :))