WEB API KEY
참고 - http://www.whoiskevinrich.com/adding-user-claims-via-api-keys-in-webapi-2
new project
컨트롤러를 만들자.
//[Authorize]
public class ValuesController : ApiController
{
// GET /values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
실행해보자.
http://localhost:59486/values
값이 오는걸 확인하자.
Authorize 주석 해제 후 다시 테스트
401을 확인하자.
Add WebApi.AuthenticationFilter Package
PM> Install-Package WebApi.AuthenticationFilter
ApiKeyAuthenticationFilter를 만들자.
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Web.Http.Filters;
using System.Web.Http.Results;
using WebApi.AuthenticationFilter;
namespace apikey.App_Start
{
public class ApiKeyAuthenticationFilter : AuthenticationFilterAttribute
{
public override void OnAuthentication(HttpAuthenticationContext context)
{
if (!Authenticate(context))
{
context.ErrorResult = new StatusCodeResult(HttpStatusCode.Unauthorized,
context.Request);
}
}
private bool Authenticate(HttpAuthenticationContext context)
{
// Get the value for the "api-key" header key
// TODO: replace hard coded literal with AppSetting
var apikey = context.Request?
.Headers?
.SingleOrDefault(x => x.Key == "api-key")
.Value?
.FirstOrDefault();
// TODO: replace hard coded literal with AppSetting or Database check
if (string.IsNullOrWhiteSpace(apikey) || apikey != "password") return false;
// Authentication logic here (ideally, assign apikeys in a database somewhere)
var username = "someauthuser";
// Create the claim for the username
var usernameClaim = new Claim(ClaimTypes.Name, username);
// Create the claim for the user role
var roleClaim = new Claim(ClaimTypes.Role, "AuthorizedApiKeys");
// TODO: add additional claims such as email / dob / etc
// Build the identity
var identity = new ClaimsIdentity(new[] { usernameClaim, roleClaim }, "ApiKey");
// Assign/Build the pricipal
context.Principal = new ClaimsPrincipal(identity);
// User is authenticated
return true;
}
}
}
WebApiConfig 를 수정하자.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ApiKeyAuthenticationFilter 추가
config.Filters.Add(new ApiKeyAuthenticationFilter());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
프로젝트를 실행하자.
fiddler 로 테스트
401 에러가 난다.
apikey와 함게 리퀘스트를 던저 보자.
200 ..성공
이제 하드코딩된 apikey부분을 디비에서 가져오게만 바꾸면될듯
참고로 api key를 만드는 코드는 다음처럼 하면될듯 하다.
```cs using (var cryptoProvider = new RNGCryptoServiceProvider()) { byte[] secretKeyByteArray = new byte[32]; //256 bit cryptoProvider.GetBytes(secretKeyByteArray); var APIKey = Convert.ToBase64String(secretKeyByteArray); } ``