Alexa skill and Azure AD authentication - asp.net

I am trying to build an alexa skill that connects to an enterprise app that uses Azure AD authentication. We set everything up like in this article https://blogs.msdn.microsoft.com/premier_developer/2016/12/12/amazon-alexa-skills-development-with-azure-active-directory-and-asp-net-core-1-0-web-api/, but I am having problems with moving the token from the body of the request to the headers.
The request comes through fine, I can parse it, I add the token to the header but on the test page in amazon I get this message: "There was an error calling the remote endpoint, which returned HTTP 302 : Found"
This is the code for adding the token to the headers:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.Use(async (context, next) =>
{
string path = string.Format(ConfigurationManager.AppSettings["ExchangeTraceDrivePath"], "AlexaRequest", DateTime.Now.ToFileTime(), "");
var stream = context.Request.Body;
try
{
using (var buffer = new MemoryStream())
{
await stream.CopyToAsync(buffer);
var bodyBuffer = new byte[buffer.Length];
buffer.Position = 0L;
buffer.Read(bodyBuffer, 0, bodyBuffer.Length);
var body = Encoding.UTF8.GetString(bodyBuffer);
using (var sw = new StreamWriter(path))
{
sw.WriteLine(DateTime.Now.ToString() + " body: " + body);
sw.WriteLine("---------------------------------------------------------------------------------------------");
foreach (var header in context.Request.Headers)
{
sw.WriteLine(DateTime.Now.ToString() + " header key: " + header.Key);
foreach (var val in header.Value)
{
sw.WriteLine(DateTime.Now.ToString() + " header value: " + val);
}
}
sw.WriteLine("---------------------------------------------------------------------------------------------");
dynamic json = JObject.Parse(body);
sw.WriteLine(DateTime.Now.ToString() + " parsed body: " + json);
sw.WriteLine("---------------------------------------------------------------------------------------------");
if (json?.session?.user?.accessToken != null)
{
sw.WriteLine(DateTime.Now.ToString() + " access accessToken found " +
json?.session?.user?.accessToken);
sw.WriteLine("---------------------------------------------------------------------------------------------");
context.Request.Headers.Add("Authorization",
new string[] { string.Format("Bearer {0}", json?.session?.user?.accessToken) });
foreach (var header in context.Request.Headers)
{
sw.WriteLine(DateTime.Now.ToString() + " header key: " + header.Key);
foreach (var val in header.Value)
{
sw.WriteLine(DateTime.Now.ToString() + " header value: " + val);
}
}
sw.WriteLine("---------------------------------------------------------------------------------------------");
}
buffer.Position = 0L;
context.Request.Body = buffer;
}
}
}
catch
{
}
finally
{
await next.Invoke();
// Restore the original stream.
context.Request.Body = stream;
}
});
//ExpireTimeSpan and SlidinExpiration only work when UseTokenLifetime = false
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
// This is NOT ASP.NET Session Timeout (that should be set to same value in web.config)
// This is the expiration on the cookie that holds the Azure AD token
ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(expirationTimeSpan)),
// Set SlidingExpiration=true to instruct the middleware to re-issue a new cookie
// with a new expiration time any time it processes a request which is more than
// halfway through the expiration window.
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
// This method is called every time the cookie is authenticated, which
// is every time a request is made to the web app
OnValidateIdentity = CookieAuthNotification.OnValidateIdentity
}
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
UseTokenLifetime = false,
/*
* Skipping the Home Realm Discovery Page in Azure AD
* http://www.cloudidentity.com/blog/2014/11/17/skipping-the-home-realm-discovery-page-in-azure-ad/
*/
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = OpenIdConnectNotification.RedirectToIdentityProvider,
MessageReceived = OpenIdConnectNotification.MessageReceived,
SecurityTokenReceived = OpenIdConnectNotification.SecurityTokenReceived,
SecurityTokenValidated = OpenIdConnectNotification.SecurityTokenValidated,
AuthorizationCodeReceived = OpenIdConnectNotification.AuthorizationCodeReceived,
AuthenticationFailed = OpenIdConnectNotification.AuthenticationFailed
},
});
}

I ended up creating a separate middleware to move the token from the body to the header
public class AlexaJWTMiddleware : OwinMiddleware
{
private readonly OwinMiddleware _next;
public AlexaJWTMiddleware(OwinMiddleware next) : base(next)
{
_next = next;
}
public override Task Invoke(IOwinContext context)
{
var stream = context.Request.Body;
if (context.Request.Headers.ContainsKey("SignatureCertChainUrl")
&& context.Request.Headers["SignatureCertChainUrl"]
.Contains("https://s3.amazonaws.com/echo.api/echo-api-cert-4.pem")
&& !context.Request.Headers.ContainsKey("Authorization"))
{
try
{
using (var buffer = new MemoryStream())
{
stream.CopyToAsync(buffer);
var bodyBuffer = new byte[buffer.Length];
buffer.Position = 0L;
buffer.Read(bodyBuffer, 0, bodyBuffer.Length);
var body = Encoding.UTF8.GetString(bodyBuffer);
dynamic json = JObject.Parse(body);
if (json?.session?.user?.accessToken != null)
{
context.Request.Headers.Add("Authorization",
new string[] { string.Format("Bearer {0}", json?.session?.user?.accessToken) });
}
buffer.Position = 0L;
context.Request.Body = buffer;
}
}
catch
{
}
finally
{
// Restore the original stream.
context.Request.Body = stream;
}
}
else
{
return _next.Invoke(context);
}
return _next.Invoke(context);
}
}
and then adding jwt authentication besides the openId one
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.Use(typeof(AlexaJWTMiddleware));
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = domain,
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = ConfigurationManager.AppSettings["ida:AppIdUri"]
},
AuthenticationType = "OAuth2Bearer",
});
//ExpireTimeSpan and SlidinExpiration only work when UseTokenLifetime = false
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
// This is NOT ASP.NET Session Timeout (that should be set to same value in web.config)
// This is the expiration on the cookie that holds the Azure AD token
ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(expirationTimeSpan)),
// Set SlidingExpiration=true to instruct the middleware to re-issue a new cookie
// with a new expiration time any time it processes a request which is more than
// halfway through the expiration window.
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
// This method is called every time the cookie is authenticated, which
// is every time a request is made to the web app
OnValidateIdentity = CookieAuthNotification.OnValidateIdentity
}
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
UseTokenLifetime = false,
/*
* Skipping the Home Realm Discovery Page in Azure AD
* http://www.cloudidentity.com/blog/2014/11/17/skipping-the-home-realm-discovery-page-in-azure-ad/
*/
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = OpenIdConnectNotification.RedirectToIdentityProvider,
MessageReceived = OpenIdConnectNotification.MessageReceived,
SecurityTokenReceived = OpenIdConnectNotification.SecurityTokenReceived,
SecurityTokenValidated = OpenIdConnectNotification.SecurityTokenValidated,
AuthorizationCodeReceived = OpenIdConnectNotification.AuthorizationCodeReceived,
AuthenticationFailed = OpenIdConnectNotification.AuthenticationFailed
},
});
}

Related

Xamarin Http Request Timeout Issue

I have a mobile application based on Xamarin and a Web API based on .Net Core. Mobile app consumes methods of Web API via HttpClient. The code below is my base method to call any Web API method and the point is I want to set a timeout but could not achieved to set the exact timeout value whatever I have implemented. Tried Timespan.FromSeconds() or TimeSpan.FromMilliseconds() etc. When client makes a request to Web API, a loader is displayed to lock UI and removed after API response. Some clients gave me a feedback that the loader is displayed forever and request never ends. Maybe, the server is unreachable in this particular time or internet connection is broken for client etc. All I want to set a timeout and break the request and display an alert message to client. Of course, I googled and tried too much as mentioned but no result. If anyone can help me, will be appreciated.
public async Task<BaseResponseModel> Post(BasePostModel postModel)
{
var responseModel = new BaseResponseModel();
var json = postModel.ToString();
var jsonParam = new StringContent(json, Encoding.UTF8, "application/json");
var isPosted = true;
var clientHandler = new HttpClientHandler()
{
AllowAutoRedirect = true,
};
var url = GetURL(postModel.UrlKey);
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ContractResolver = new DefaultContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
var client = new HttpClient(clientHandler);
//client.Timeout = TimeSpan.FromSeconds(10);
//var cancellationTokenSource = new CancellationTokenSource();
//cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10));
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("X-Env", "MOBILE_API");
AttachToken(ref client, responseModel.Id);
try
{
if (Preferences.ContainsKey("UserJwtExprieDate"))
{
var expiryDate = Preferences.Get("UserJwtExprieDate", null);
if (DateTime.Now > DateTime.Parse(expiryDate))
{
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
int index = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.Count - 1;
Page currPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack[index];
if (currPage as SigninForFactorOne != null)
{}
else
{
App.LogoutUser();
}
}
else
{
var response = await client.PostAsync(url, jsonParam);
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
var resultModel = JsonConvert.DeserializeObject<BaseResponseModel>(result, settings);
if (resultModel.ErrorType == APIErrorTypes.NULL)
{
if (resultModel.IsSucceed)
{
responseModel.Data = resultModel.Data;
}
else
{
responseModel.Error = resultModel.Error;
}
responseModel.Message = resultModel.Message;
}
else
{
responseModel.Error = "Token Expried Date.";
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
App.LogoutUser();
}
}
else
{
new AppException(new Exception("HTTP Client response is not succeed!"), responseModel.Id);
isPosted = false;
}
}
}
else
{
var response = await client.PostAsync(url, jsonParam);
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
var resultModel = JsonConvert.DeserializeObject<BaseResponseModel>(result, settings);
if (resultModel.ErrorType == APIErrorTypes.NULL)
{
if (resultModel.IsSucceed)
{
responseModel.Data = resultModel.Data;
}
else
{
responseModel.Error = resultModel.Error;
}
responseModel.Message = resultModel.Message;
}
else
{
responseModel.Error = "Token Expried Date.";
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
App.LogoutUser();
}
}
else
{
new AppException(new Exception("HTTP Client response is not succeed!"), responseModel.Id);
isPosted = false;
}
}
}
catch (Exception ex)
{
new AppException(ex, responseModel.Id, 500, "anonymous.user", "Unable to post data to API!");
isPosted = false;
}
finally
{
if (!isPosted)
{
responseModel.Error = AppConfiguration.GetSystemMessage(contactYourSystemAdministratorMessage);
responseModel.Message = AppConfiguration.GetSystemMessage(contactYourSystemAdministratorMessage);
}
}
return responseModel;
}
I've used the solution below to manually set a time-out which works fine.
internal class TimeOutHandler : DelegatingHandler
{
private readonly TimeSpan TimeOut;
public TimeOutHandler(TimeSpan timeOut) => TimeOut = timeOut;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage req, CancellationToken ct)
{
using (var ctTimeOut = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
ctTimeOut.CancelAfter(TimeOut);
try
{
return await base.SendAsync(req, ctTimeOut.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException();
}
}
}
}
How to use
var interval = TimeSpan.FromSeconds(10);
var handler = new TimeOutHandler(interval)
{
InnerHandler = new HttpClientHandler()
};
var client = new HttpClient(handler);
For more information, check out: https://thomaslevesque.com/2018/02/25/better-timeout-handling-with-httpclient/

Reverse proxy in .NET Core Middleware “set-cookie” response does not set in browser and not showing in HttpResponseMessage

Here I am making a reverse proxy server to bypass an ASP.NET web application (following this tutorial). I am trying to read the session ID cookie from HttpResponseMessage. I used a cookie container as well but am unable to find it. Implemented in ASP.NET core invoke method, session is working properly but unable to catch session ID in request or response.
public async Task Invoke(HttpContext context, IBrowserDetector detector)
{
//context.Session.SetString(SessionKeyName, "The Doctor");
var browser = detector.Browser;
var targetUri = BuildTargetUri(context.Request);
if (context.Request.Method != HttpMethod.Get.Method)
{
var remoteIp = context.Connection.RemoteIpAddress;
//var gg= context.Request.Headers.ContainsKey.;
var clienttdatetime = context.Request.Headers["Date"].ToString();
//_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
var badIp = true;
var bytes = remoteIp.GetAddressBytes();
//var testIp = IPAddress.Parse(address);
//if (testIp.GetAddressBytes().SequenceEqual(bytes))
//{
// badIp = false;
// break;
//}
if (remoteIp.IsIPv4MappedToIPv6)
{
remoteIp = remoteIp.MapToIPv4();
}
IPAddress remoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress;
string result = "";
if (remoteIpAddress != null)
{
// If we got an IPV6 address, then we need to ask the network for the IPV4 address
// This usually only happens when the browser is on the same machine as the server.
if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
}
result = remoteIpAddress.ToString();
}
if (badIp)
{
//_logger.LogWarning(
// "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
//context.Response.StatusCode = StatusCodes.Status403Forbidden;
//return;
}
}
if (targetUri != null)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie_ in responseCookies)
Console.WriteLine(cookie_.Name + ": " + cookie_.Value);
// ExtractCookiesFromResponse(responseMessage);
context.Response.StatusCode = (int)responseMessage.StatusCode;
CopyFromTargetResponseHeaders(context, responseMessage);
await responseMessage.Content.CopyToAsync(context.Response.Body);
//if(responseMessage.RequestMessage.RequestUri.ToString()== "http://localhost:51125/Menu.aspx")
//{
//Uri uri = new Uri("http://localhost:5000/login.aspx");
//Build the request
//Uri site = targetUri;
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
// CookieContainer cookiesq = new CookieContainer();
// request.CookieContainer = cookiesq;
// //Print out the number of cookies before the response (of course it will be blank)
// Console.WriteLine(cookiesq.GetCookieHeader(site),"1");
// //Get the response and print out the cookies again
// using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
// {
// Console.WriteLine(cookiesq.GetCookieHeader(site), "2");
// }
// Console.ReadKey();
//}
var cookie = context.Request.Cookies["ASP.NET_SessionId"];
}
return;
}
await _nextMiddleware(context);
}
------------------------------------------------------------------------------------
public static IDictionary<string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
{
IDictionary<string, string> result = new Dictionary<string, string>();
IEnumerable<string> values;
if (response.Headers.TryGetValues("Set-Cookie", out values))
{
SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
{
result.Add(cookie.Name.ToString(), cookie.Value.ToString());
});
}
return result;
}
As far as I can see, you created the HttpClientHandler but didn't use it to build the HttpClient to make your request. You are still using the static _httpClient that nothing knows about the cookie container you created.
This should be the reason why you get the CookieContainer still empty.
Take a look here to learn how to get cookies from an HttpResponseMessage.
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
_httpClient = new HttpClient(handler);
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
//var responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
{
if(cookie.Name=="ASP.NET_SessionId")
{
Console.WriteLine(cookie.Name + ": " + cookie.Value);
context.Response.Headers.Add("Set-Cookie", cookie.Name+"="+cookie.Value);
}
}

ASP.NET core 3 Customized authentication with jwt

I am using jwt tokens in my project. When the client logins, he will receive a token with his device id (in mobile) -that was sent to the server in the request body- as the payload...
The thing I want to do is for further requests when the client sends his device id in the body (as a convention in my project) and of course the token in the header request, I want to check if the device id and the token's payload are equal or not.
I did this in a service like this:
public class AuthenticationService
{
public bool IsAuthenticated(HttpRequest req, string deviceId)
{
var token = req.Headers["authorization"];
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken tokenS;
foreach (var stringValue in token)
{
var ss = stringValue.Replace("Bearer ", "");
if (handler.CanReadToken(ss))
{
tokenS = handler.ReadToken(ss) as JwtSecurityToken;
return tokenS.Claims.Any(c => c.Value == deviceId);
}
}
return false;
}
}
And I should inject it in every controller that I want to authorize the user...
if (_authenticationService.IsAuthenticated(Request, deviceId))
{
_logger.LogInformation("authorized!");
}
else
{
_logger.LogCritical("unauthorized");
}
I want to know that if there is a more cleaner way of doing this?
Something to do in the Startup class when I'm configuring the Authentication:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(
Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false,
};
});
AddJwtBearer extension will map the claims in token to user's cliams , you can get the device ID by (if cliam type is deviceId):
var deviceID= context.HttpContext.User.Claims.Where(x => x.Type == "deviceId").FirstOrDefault().Value;
Then you can use Filter or Middleware to read request body and compare the device ID in reuqest body with the one in User's claim . For example , if using Filter :
public class CustomActionFilter : ActionFilterAttribute
{
public override async void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.User.Identity.IsAuthenticated) {
//read request body
var bodyStr = "";
var req = context.HttpContext.Request;
req.EnableBuffering();
req.Body.Position = 0;
using (var stream = new StreamReader(req.Body))
{
bodyStr = await stream.ReadToEndAsync();
}
// here you get device ID from bodyStr ,for example : deviceIDFromReq
var deviceID= context.HttpContext.User.Claims.Where(x => x.Type == "deviceId").FirstOrDefault().Value;
// then compare
if (deviceIDFromReq.Equals(deviceID))
{
context.Result = new BadRequestObjectResult(new
{
status = "error",
description = "deviceID not matched"
});
}
}
base.OnActionExecuting(context);
}
}
Register as global filter :
services.AddControllers(config =>
{
config.Filters.Add<CustomActionFilter>();
});

How to implement OpenID OAuth2 Server in ASP.NET Framework 4.x Web API?

I'm trying to implement OpenID OAuth 2.0 server with ASP.NET Framework 4.7.2 Web API. It will be used to protect resource APIs with JWT Access/Refresh tokens.
I'm fairly new to OpenID and OAuth so I'm looking for advice/guidelines/libray that I can use to implement this Authorization server.
The Auth server needs to be implemented by using ASP.NET Framework 4.7.2, there is no option for Core at the moment. The resource APIs will be written in ASP.NET Core 2.X.
I've followed the awesome Taiseer's tutorials (Part 1, Part 3, Part 5, and JWT Setup), and currently have OAuth server which can generate JWT Tokens, and Core API which can validate the token.
Here is the code that I currently have.
Auth Server:
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
app.CreatePerOwinContext<SecurityUserManager>(SecurityUserManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth2/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new SmAuthorizationServerProvider(),
RefreshTokenProvider = new SmRefreshTokenProvider(),
AccessTokenFormat = new SmJwtFormat("http://localhost:7814"),
ApplicationCanDisplayErrors = true,
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
SmAuthorizationServerProvider.cs
public class SmAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId = string.Empty;
string clientSecret = string.Empty;
Client client = null;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
context.TryGetFormCredentials(out clientId, out clientSecret);
}
if (context.ClientId == null)
{
//Remove the comments from the below line context.SetError, and invalidate context
//if you want to force sending clientId/secrects once obtain access tokens.
context.Validated();
//context.SetError("invalid_clientId", "ClientId should be sent.");
return Task.FromResult<object>(null);
}
using (AuthRepository _repo = new AuthRepository())
{
client = _repo.FindClient(context.ClientId);
}
if (client == null)
{
context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
return Task.FromResult<object>(null);
}
if (client.ApplicationType == Models.ApplicationTypes.NativeConfidential)
{
if (string.IsNullOrWhiteSpace(clientSecret))
{
context.SetError("invalid_clientId", "Client secret should be sent.");
return Task.FromResult<object>(null);
}
else
{
if (client.Secret != Helper.GetHash(clientSecret))
{
context.SetError("invalid_clientId", "Client secret is invalid.");
return Task.FromResult<object>(null);
}
}
}
if (!client.Active)
{
context.SetError("invalid_clientId", "Client is inactive.");
return Task.FromResult<object>(null);
}
context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());
context.Validated();
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
SecurityUser user = null;
if (allowedOrigin == null) allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
using (AuthRepository _repo = new AuthRepository())
{
user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
string scopes = null;
if (context.Scope.Count > 0)
{
scopes = string.Join(" ", context.Scope.Select(x => x.ToString()).ToArray());
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
// Add the user id as claim here
// Keep the claims number small, the token length increases with each new claim
identity.AddClaim(new Claim("sid", user.Id.ToString()));
// add the client id as claim
if (!string.IsNullOrEmpty(context.ClientId))
{
identity.AddClaim(new Claim("client_id", context.ClientId));
}
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
},
{
"as:scope", (scopes == null) ? string.Empty : scopes
},
{
"userName", context.UserName
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
{
var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
var currentClient = context.ClientId;
// check if the token is created with specified client_id
if (!string.IsNullOrEmpty(currentClient) && !string.IsNullOrEmpty(originalClient))
{
if (originalClient != currentClient)
{
context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
return Task.FromResult<object>(null);
}
}
var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
// Change auth ticket for refresh token requests if needed
// newIdentity.AddClaim(new Claim("newClaim", "newValue"));
var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
context.Validated(newTicket);
return Task.FromResult<object>(null);
}
public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
Client client;
using (AuthRepository _repo = new AuthRepository())
{
client = _repo.FindClient(context.ClientId);
}
var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim("client_id", client.Id));
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
}
});
var ticket = new AuthenticationTicket(oAuthIdentity, props);
context.Validated(ticket);
return base.GrantClientCredentials(context);
}
}
SmJwtFormat.cs
public class SmJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
private const string AudiencePropertyKey = "as:scope";
private readonly string _issuer = string.Empty;
private AuthRepository authRepo;
private SecurityKey signingKey;
private string secret = "P#ssw0rd-7BBF8546-C8C1-44D9-A404-9E1CAF80EC9D-F2FEC38D-2041-499E-9FAA-218C8B1EEC7B";
public SmJwtFormat(string issuer)
{
_issuer = issuer;
authRepo = new AuthRepository();
// Generating the signingKey
string symmetricKeyAsBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret));
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
signingKey = new SymmetricSecurityKey(keyByteArray);
}
public string Protect(AuthenticationTicket data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
// The token audience from the JWT terminology is the same as the token Scope in OAuth terminology.
string scope = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null;
if (string.IsNullOrWhiteSpace(scope)) throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience/scope");
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature);
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
if (scope != null)
{
var scopesList = scope.Split(' ').ToList();
var audClaims = scopesList.Select(s => new Claim("aud", s));
data.Identity.AddClaims(audClaims);
}
var token = new JwtSecurityToken(_issuer, null, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);
return jwt;
}
public AuthenticationTicket Unprotect(string protectedText)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = _issuer,
IssuerSigningKey = signingKey,
};
var handler = new JwtSecurityTokenHandler();
SecurityToken token = null;
// Unpack token
var pt = handler.ReadJwtToken(protectedText);
string t = pt.RawData;
var principal = handler.ValidateToken(t, tokenValidationParameters, out token);
var identity = principal.Identities;
return new AuthenticationTicket(identity.First(), new AuthenticationProperties());
}
}
Here is my resource ASP.NET Core 2.2 API Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthorization();
// identity http://localhost:7814
// resource https://localhost:44337
var key = "P#ssw0rd-7BBF8546-C8C1-44D9-A404-9E1CAF80EC9D-F2FEC38D-2041-499E-9FAA-218C8B1EEC7B";
string symmetricKeyAsBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
var keyByteArray = Convert.FromBase64String(symmetricKeyAsBase64);
var securityKey = new SymmetricSecurityKey(keyByteArray);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = "http://localhost:7814/";
o.RequireHttpsMetadata = false;
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = "http://localhost:7814",
ValidateAudience = true,
ValidAudiences = new List<string>()
{
"api1"
},
//IssuerSigningKey = securityKey
};
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
}
Currently I'm able to generate tokens by posting to http://localhost:7814/oauth2/token with the following parameters:
grant_type=password
username=user1
password=p#ssw0rd
client_id=smLocalhost
client_secret=secret
scope=api1 api2
After that the token can be used to access secured endpoints in the resource API.
I've researched IdentityServer4, OpenIdDict and AspNet.Security.OpenIdConnect.Server, but they seems to be working only with ASP.NET Core.
So after all this stuff, my questions are:
1. How to add OpenID on top of that?
2. Is there a library that I can use?
3. Could you please give me tutorial/advice what can I do to implement
it?
4. How to implement discovery document endpoint (.well-known/openid-configuration) and rotate the public keys for asymmetric token signing?
Thanks in advance!

ASP.NET API OAuth2 Refresh token - Deserialize ticket not working

I'm implementing the OAuth 2 refresh token with ASP.NET API2 and OWIN, the following code is my OAuthAuthorizationOptions
public static OAuthAuthorizationServerOptions AuthorizationServerOptions
{
get
{
if (_AuthorizationServerOptions == null)
{
_AuthorizationServerOptions = new OAuthAuthorizationServerOptions()
{
AuthenticationType = OAuthDefaults.AuthenticationType,
AllowInsecureHttp = true,
TokenEndpointPath = new PathString(AuthSettings.TokenEndpoint),
AuthorizeEndpointPath = new PathString(AuthSettings.AuthorizeEndpoint),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(AuthSettings.TokenExpiry),
Provider = new CustomOAuthAuthorizationServerProvider(AuthSettings.PublicClientId),
// TODO: Remove the dependency with Thinktecture.IdentityModel library here
AccessTokenFormat = new CustomJWTFormat(),
RefreshTokenProvider = new CustomRefreshTokenProvider()
};
}
return _AuthorizationServerOptions;
}
}
Here is my CustomRefreshTokenProvider class
public override Task CreateAsync(AuthenticationTokenCreateContext context)
{
var identifier = context.Ticket.Identity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
if (identifier == null || string.IsNullOrEmpty(identifier.Value))
{
return Task.FromResult<object>(null);
}
var refreshToken = HashHelper.Hash(Guid.NewGuid().ToString("n"));
var tokenIssued = DateTime.UtcNow;
var tokenExpire = DateTime.UtcNow.AddSeconds(AuthSettings.RefreshTokenExpiry);
context.Ticket.Properties.IssuedUtc = tokenIssued;
context.Ticket.Properties.ExpiresUtc = tokenExpire;
context.Ticket.Properties.AllowRefresh = true;
var protectedTicket = context.SerializeTicket();
AuthService.AddUserRefreshTokenSession(
identifier.Value,
refreshToken,
tokenIssued,
tokenExpire,
protectedTicket);
context.SetToken(refreshToken);
return Task.FromResult<object>(null);
}
public override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
var refToken = context.Token;
var protectedTicket = AuthService.GetProtectedTicket(refToken);
if (!string.IsNullOrEmpty(protectedTicket))
{
context.DeserializeTicket(protectedTicket);
}
return Task.FromResult<object>(null);
}
I have used postman to send POST request to the token endpoint as below
Postman refresh token
the server return 400 bad request status code.
I debugged and found that the context.DeserializeTicket(protectedTicket)
throw an Exception
Exception thrown: 'System.Security.Cryptography.CryptographicException' in System.Web.dll
I don't think it is the expiration issue because
the AuthSettings.RefreshTokenExpiry is 30 days from now.
I also tried to add Machine key to my web.config OAuth Refresh Token does not deserialize / invalid_grant
but it still not working.
Does anyone have an idea?
Any solutions will be highly appreciated.
Sorry for the late answered.
I have resolved this issue and end up with a solution that remove entirely Thinktecture.Identity out of my project, since it's somehow conflict with System.IdentityModel.Tokens.JWT.dll
Another solution if you still want to use Thinktecture.Identity is that downgrade System.IdentityModel.Tokens.JWT to v4.0.2.206221351 (this version worked for me, I haven't tested with another version).
Here is the code of CustomJWTFormat.cs
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using MST.Service.Core.Logging;
using System;
using System.Security.Claims;
namespace MST.Service.Core.Auth
{
public class CustomJWTFormat : ISecureDataFormat
{
private byte[] _SymetricKey = null;
public CustomJWTFormat()
{
_SymetricKey = Convert.FromBase64String(AuthSettings.JwtTokenSecret);
}
///
/// Create jwt token
///
///
/// Token string
public string Protect(AuthenticationTicket data)
{
var tokenHandler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();
var now = DateTime.UtcNow;
System.IdentityModel.Tokens.JwtSecurityToken jwtSecurityToken = new System.IdentityModel.Tokens.JwtSecurityToken(
AuthSettings.Issuer,
AuthSettings.JwtAudiences,
data.Identity.Claims,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(AuthSettings.TokenExpiry),
new System.IdentityModel.Tokens.SigningCredentials(
new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(_SymetricKey),
System.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature,
System.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest)
);
var token = tokenHandler.WriteToken(jwtSecurityToken);
return token;
}
public AuthenticationTicket Unprotect(string protectedText)
{
var tokenHandler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();
var validationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
{
RequireExpirationTime = true,
ValidateIssuer = true,
ValidateLifetime = true,
AuthenticationType = OAuthDefaults.AuthenticationType,
ValidIssuers = new string[] { AuthSettings.Issuer },
ValidAudiences = new string[] { AuthSettings.JwtAudiences },
ValidateAudience = true,
ValidateIssuerSigningKey = false,
IssuerSigningKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(_SymetricKey)
};
System.IdentityModel.Tokens.SecurityToken securityToken = null;
ClaimsPrincipal principal = null;
try
{
principal = tokenHandler.ValidateToken(protectedText, validationParameters, out securityToken);
var validJwt = securityToken as System.IdentityModel.Tokens.JwtSecurityToken;
if (validJwt == null)
{
throw new ArgumentException("Invalid JWT");
}
}
catch (Exception ex)
{
LoggerManager.AuthLog.Error($"Parse token error: {ex.ToString()}");
return null;
}
// Validation passed. Return a valid AuthenticationTicket:
return new AuthenticationTicket(principal.Identity as ClaimsIdentity, new AuthenticationProperties());
}
}
}
and JWTBearerAuthenticationOptions (if you host Resource Server and Authorization Server in the same machine)
public static JwtBearerAuthenticationOptions JwtAuthenticationOptions
{
get
{
if (_JwtAuthenticationOptions == null)
{
_JwtAuthenticationOptions = new JwtBearerAuthenticationOptions()
{
//AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
AuthenticationType = OAuthDefaults.AuthenticationType,
AllowedAudiences = new[] { AuthSettings.JwtAudiences },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(AuthSettings.Issuer, AuthSettings.JwtTokenSecret)
}
};
}
return _JwtAuthenticationOptions;
}
}
in Startup.cs just register middleware as usual
app.UseJwtBearerAuthentication(AuthenticationOptions.JwtAuthenticationOptions);

Resources