Auth custom using IAuthenticationFilter and AuthorizeAttribute

public class AuthenticationServiceAttribute : IAuthenticationFilter
{

public AuthenticationServiceAttribute()
{

}

public async Task AuthenticateAsync(HttpAuthenticationContext actionContext, CancellationToken cancellationToken)
{
if (actionContext.Request.Headers.Authorization != null)
{
var cacheResponse = _memoryProvider.Get<MYCLASS>(“key”);

if (cacheResponse != null)
{

await Validate(cacheResponse.access_token, actionContext.Request.Headers.Authorization.Parameter.ToString(), actionContext);
return;
}
else
{
AuthTokenEntity serviceToken = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings[“AuthBaseAddress”]);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>(“scope”, “can_access,can_add”),
new KeyValuePair<string, string>(“grant_type”, “client_credentials”),
new KeyValuePair<string, string>(“id”, “123”),
new KeyValuePair<string, string>(“pass”, “pass”)
});

var resposnse = await client.PostAsync(“/mydemo/mydemo”, content);
serviceToken = JsonConvert.DeserializeObject<AuthTokenEntity>(await resposnse.Content.ReadAsStringAsync());
}
_memoryProvider.Set(“community_service”, new AuthTokenEntity
{
user= serviceToken.user,

},60);

// validation of user access token
await ValidateAccessToken(serviceToken.access_token, actionContext.Request.Headers.Authorization.Parameter.ToString(), actionContext);
return;
}
}
else
{
actionContext.ErrorResult = new AuthenticationFailureResult(actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, _responseService.CreateErrorResponseMessage((int)HttpStatusCode.BadRequest, Ecng_APIMsg.AuthProviderAuthorizationHeaderEmpty)));
return;
}
}
public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
}
public bool AllowMultiple
{
get
{
return true;
}
}
private async Task ValidateAccessToken(string serviceToken, string userAccessToken, HttpAuthenticationContext actionContext)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings[“baseaddress”]);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, serviceToken);
var resposnse = await client.GetAsync(“/demo/demo/validate/” + userAccessToken);
var resposnseContent = await resposnse.Content.ReadAsStringAsync();
if (resposnse.StatusCode != HttpStatusCode.OK)
{
myclass errorResponse = JsonConvert.DeserializeObject<myclass>(resposnseContent);
actionContext.ErrorResult = new AuthenticationFailureResult(actionContext.Request.CreateResponse(resposnse.StatusCode, errorResponse));
return;
}
}
}
}

 

Authorize

public class AuthorizeServiceAttribute : AuthorizeAttribute
{
private readonly ResponseService _responseService;
private readonly ICache _memoryProvider;
private static AuthErrorResponseEntity errorResponse;
private Task<HttpResponseMessage> serviceAuthorizeResult;
private HttpResponseMessage unhandledResponseMessage;

public AuthorizeServiceAttribute()
{

}

/// <summary>
/// IsAuthorized
/// </summary>
/// <param name=”actionContext”>actionContext</param>
/// <returns></returns>
protected override bool IsAuthorized(HttpActionContext actionContext)
{
try
{
// get community_service token from cache if not expires
var cacheResponse = _memoryProvider.Get<AuthTokenEntity>(“community_service”);
if (cacheResponse != null)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, cacheResponse.access_token);
client.BaseAddress = new Uri(ConfigurationManager.AppSettings[“BaseAddress”]);
dynamic type = RequestAction(actionContext);

if (type != null)
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>(“request[id]”, type.requestAction),
new KeyValuePair<string, string>(“request[name]”,type.systemId),
new KeyValuePair<string, string>(“user_access_token”,actionContext.Request.Headers.Authorization.Parameter.ToString())
});

serviceAuthorizeResult = client.PostAsync(string.Format(“/{0}/demo/{1}/authorize”, “5.0”, Route(actionContext)), content);
var response = serviceAuthorizeResult.Result.Content.ReadAsStringAsync();
var serviceToken = JsonConvert.DeserializeObject<UserData>(response.Result);
if (serviceAuthorizeResult.Result.StatusCode == HttpStatusCode.OK)
{
actionContext.Request.Properties[“id”] = serviceToken.data.id;
return true;
}
else
{
errorResponse = JsonConvert.DeserializeObject<myclass>(response.Result);
unhandledResponseMessage = actionContext.Request.CreateResponse(serviceAuthorizeResult.Result.StatusCode, errorResponse);
return false;
}
}
else
{
return false;
}
}
}
else
{
unhandledResponseMessage = actionContext.Request.CreateResponse(HttpStatusCode.InternalServerError, _responseService.CreateErrorResponseMessage((int)HttpStatusCode.InternalServerError));
return false;
}
}
catch (Exception ex)
{
// TODO: Log Error
unhandledResponseMessage = actionContext.Request.CreateResponse(HttpStatusCode.InternalServerError, _responseService.CreateErrorResponseMessage((int)HttpStatusCode.InternalServerError));
return false;
}

}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
actionContext.Response = unhandledResponseMessage;
}
private string Route(HttpActionContext actionContext)
{
var requestUri = actionContext.Request.RequestUri.AbsolutePath;
if (requestUri.ToLower().Contains(“abc”))
{
return “notice”;
}
else if (requestUri.ToLower().Contains(“xyz”))
{
return “post”;
}
else
{
return string.Empty;
}
}

private object RequestAction(HttpActionContext actionContext)
{
string methodType = actionContext.Request.Method.Method;

if (methodType.ToUpper().Equals(“POST”))
{
Task<string> content = actionContext.Request.Content.ReadAsStringAsync();
JObject Jobj = JObject.Parse(content.Result);
string buildingId = (string)Jobj[“buildingId”];
if (buildingId != null)
{
return new { requestAction = “CREATE”, id= id};
}
else
{
unhandledResponseMessage = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, _responseService.CreateErrorResponseMessage((int)HttpStatusCode.BadRequest, “Parameter missing – systemId is null.”));
return null;
}
}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s