How to update token using refresh token in MVC Client Application? - c#

There are two type of application in my solution
1)Web api application
2)MMC c# application
Here I created web api application which has facility of token authentication.
In this Application username and password validating from SQL server database.
i.e If any user request for web api token that user detail must be present in database table.(In user Table Id,Username,Password column are there with data).
So my web api application connected to database server.
Now I created MVC c# application which consume web api and access the data.
what I do here that when user put credential to mvc app login screen and that credential goes to api and validate them.
Api will give response of data If user credential are correct.
Here I got JSON response from web api and data like "access_token","Expire_time","refresh_token" etc
I stored all these detail in Session object.
So whenever I request for Getdata() from mvc app I passing 'access_token' to api and retuned result data.
I set web api token timeout 2 minutes.(token get deleted after 2 minutes)
So problem goes here that how I can maintain user login session in web api using refresh_token.I do not want to user again get login screen and come back to that screen.
Because every 2 minutes he will get login screen which is not correct solution.
I want some function when api get timeout access_token and mvc application again call refresh_token and continue data transaction.

Whenever your accesstoken is expired you can pass refresh token and can update the access token like this. Hope this will help you.
[AllowAnonymous]
[HttpPost]
public IHttpActionResult GetAccessToken(RefreshTokenModel getRefreshToken)
{
ApiResponse apiResponse = new ApiResponse();
apiResponse.Message = "Your session has expired. Kindly login again.";
try
{
var getHashToken = GenerateHash.GetHash(getRefreshToken.RefreshToken);
var getRefreshTokenDetails = tokenDetailBl.GetRefreshTokenDetail(getHashToken);
if (getRefreshTokenDetails != null && getRefreshTokenDetails.ExpiresUtc > DateTime.UtcNow && !string.IsNullOrEmpty(getRefreshTokenDetails.ProtectedTicket))
{
if (getRefreshTokenDetails.DeviceType == getRefreshToken.DeviceType)
{
var currentTime = DateTime.UtcNow;
var refreshTokenLifeTime = Convert.ToDouble(ConfigurationManager.AppSettings["RefreshTokenExpireTime"]);
var tokenExpiration = Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTime"]);
ApiIdentityManager apiIdentityManager = new ApiIdentityManager();
var tokenData = JsonConvert.SerializeObject(new { Ticket = getRefreshTokenDetails.ProtectedTicket, DeviceId = getRefreshTokenDetails.DeviceId });
var getIdentityToken = apiIdentityManager.GetRefreshToken(tokenData);
// Delete Old Tokens
tokenDetailBl.DeleteAccessTokenByDevice(getRefreshTokenDetails.DeviceId);
var refreshToken = new RefreshToken()
{
RefreshTokenId = GenerateHash.GetHash(getIdentityToken.RefreshToken),
DeviceId = getRefreshTokenDetails.DeviceId,
DeviceType = getRefreshToken.DeviceType,
UserId = getRefreshTokenDetails.UserId,
IssuedUtc = currentTime,
ExpiresUtc = currentTime.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)),
ProtectedTicket = getIdentityToken.Ticket
};
//Save new tokens
tokenDetailBl.SaveAccessToken(new TokenDetail
{
AccessToken = getIdentityToken.AccessToken,
CreatedOn = DateTime.UtcNow,
UserId = getRefreshTokenDetails.UserId,
DeviceId = getRefreshTokenDetails.DeviceId,
DeviceType = getRefreshToken.DeviceType
});
tokenDetailBl.SaveRefreshToken(refreshToken);
//Get token cache.
CachedData cachedData = new CachedData(tokenDetailBl);
var getAllToken = cachedData.GetAccessTokens();
cachedData.UpdateTokenCache(getIdentityToken.AccessToken, getRefreshTokenDetails.UserId + ":" + DateTime.UtcNow.AddMinutes(tokenExpiration).ToFormateDateTimeString());
var getUserDetails = userBl.GetUserDetails(getRefreshToken.UserId);
getUserDetails.DeviceId = getRefreshTokenDetails.DeviceId;
getUserDetails.DeviceType = getRefreshTokenDetails.DeviceType;
getUserDetails.AccessToken = getIdentityToken.AccessToken;
getUserDetails.TokenType = "bearer";
getUserDetails.ExpiresIn = getIdentityToken.ExpiresIn;
getUserDetails.Issued = getIdentityToken.Issued;
getUserDetails.Expires = DateTime.UtcNow.Add(TimeSpan.FromMinutes(tokenExpiration)).ToString("R");
getUserDetails.RefreshToken = getIdentityToken.RefreshToken;
//Dictionary<string, string> tokenResponse = new Dictionary<string, string>();
//tokenResponse.Add("access_token", getIdentityToken.AccessToken);
//tokenResponse.Add("token_type", "bearer");
//tokenResponse.Add("expires_in", getIdentityToken.ExpiresIn);
//tokenResponse.Add("issued", getIdentityToken.Issued);
//tokenResponse.Add("expires", DateTime.UtcNow.Add(TimeSpan.FromMinutes(tokenExpiration)).ToString("R"));
//tokenResponse.Add("refresh_token", getIdentityToken.RefreshToken);
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, getUserDetails));
}
else
{
apiResponse.Message = "Your session has expired. Kindly login again.";
}
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
return ResponseMessage(Request.CreateResponse(HttpStatusCode.Gone, apiResponse));
}
You can use MVC filters to check that your access token is expired or not something like this.
[CacheAuthorize]
[HttpPost]
public IHttpActionResult GetUserList(SearchRequest searchRequest)
and after that code to check validation of access token
public class CacheAuthorizeAttribute : AuthorizeAttribute
{
public CacheAuthorizeAttribute(params string[] roles)
: base()
{
Roles = string.Join(",", roles);
}
public override void OnAuthorization(HttpActionContext actionContext)
{
Dictionary<HttpStatusCode, string> response;
if (SkipAuthorization(actionContext))
{
return;
}
var userSessionManager = new UserCacheManager();
if (userSessionManager.ReValidateSession(out response))
{
base.OnAuthorization(actionContext);
}
else
{
ApiResponse apiResponse = new ApiResponse(response.Values.FirstOrDefault());
actionContext.Response = actionContext.ControllerContext.Request.CreateResponse(response.Keys.FirstOrDefault(), apiResponse);
}
}
/// <summary>
/// Re-validates the user session. Usually called at each authorization request.
/// If the session is not expired, extends it lifetime and returns true.
/// If the session is expired or does not exist, return false.
/// </summary>
/// <returns>true if the session is valid</returns>
public bool ReValidateSession(out Dictionary<HttpStatusCode, string> errorResponse)
{
errorResponse = new Dictionary<HttpStatusCode, string>();
string authToken = this.GetCurrentBearerAuthrorizationToken();
ITokenDetailRepository tokenDetailRepository = new TokenDetailRepository();
ITokenDetailBL tokenDetailBl = new TokenDetailBL(tokenDetailRepository);
CachedData cachedData = new CachedData(tokenDetailBl);
if (!string.IsNullOrEmpty(authToken))
{
var currentUserId = this.GetCurrentUserId();
var getUserTokens = cachedData.GetAccessTokens();
if (!getUserTokens.ContainsKey(authToken))
{
//Get Data from DB
cachedData.GetAccessToken(authToken);
getUserTokens = cachedData.GetAccessTokens();
}
return CheckAccessToken(getUserTokens, authToken, out errorResponse);
}
else
{
errorResponse.Add(HttpStatusCode.Gone, "Access token not found.");
}
return false;
}
private bool CheckAccessToken(Dictionary<string, string> accessTokenDictionary, string authToken, out Dictionary<HttpStatusCode, string> errorResponse)
{
errorResponse = new Dictionary<HttpStatusCode, string>();
var hasToken = accessTokenDictionary.ContainsKey(authToken);
if (hasToken)
{
var getTokenValue = accessTokenDictionary[authToken];
var enCulture = new CultureInfo("en-US");
DateTime tokenAddedDate;
var isCorrectDate = DateTime.TryParseExact(getTokenValue.Split(new char[] { ':' }, 2)[1], "dd-MMM-yyyy,hh:mm tt", enCulture, DateTimeStyles.None, out tokenAddedDate);
if (isCorrectDate)
{
if (tokenAddedDate >= DateTime.UtcNow)
{
return true;
}
else
{
//Check Refresh token expired or not
errorResponse.Add(HttpStatusCode.Unauthorized, "Access token expired.");
}
}
else
{
errorResponse.Add(HttpStatusCode.Gone, "Invalid access token.");
}
}
else
{
errorResponse.Add(HttpStatusCode.Gone, "Invalid access token.");
}
return false;
}

Related

Google.Apis.Auth.OAuth2.Mvc library and refresh token

I'm trying to retrieve the reviews from our business account.
For this I'm using the Google.Apis.Auth.OAuth2.Mvc library for .net https://www.nuget.org/packages/Google.Apis.Auth.MVC/ and following this example https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web-applications-asp.net-mvc.
The library is supposed to use the refresh token automatically but for some reason after 1 hour when the access token expires we lost access to the reviews.
Here is my implementation:
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "xxxxxxxxxxxxxxxxxxxxxxxxx",
ClientSecret = "xxxxxxxxxxxxxxxxxxxxx"
},
Scopes = new string[] { "https://www.googleapis.com/auth/plus.business.manage" },
DataStore = new FileDataStore(System.Web.HttpContext.Current.Server.MapPath("/App_Data/MyGoogleStorage"), true)
//DataStore = new FileDataStore(System.Web.HttpContext.Current.Server.MapPath("/App_Data/Drive.Api.Auth.Store"))
});
public override string GetUserId(Controller controller)
{
return "our email address";
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}
public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)
{
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
AuthorizeAsync(cancellationToken);
if (result.Credential != null)
{
var accessToken = result.Credential.Token.AccessToken;
var client = new RestClient("https://mybusiness.googleapis.com/v4/accounts/116326379071192580211/locations/6608127685860731136/reviews?access_token=" + accessToken);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
GoogleReviewsModel googleReviews = Newtonsoft.Json.JsonConvert.DeserializeObject<GoogleReviewsModel>(response.Content);
return View("Index", googleReviews);
}
else
{
return new RedirectResult(result.RedirectUri);
}
}
public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController
{
protected override Google.Apis.Auth.OAuth2.Mvc.FlowMetadata FlowData
{
get { return new AppFlowMetadata(); }
}
}
The reviews are from our own company so we don't to logins from different users. What I want to achieve is to login the first time with our company logins and then automatically refresh the access token with the refresh token so the reviews are always visible in the website,
Thanks a lot!
EDIT:
After 1 hour the response I get from the following code is this:
var accessToken = result.Credential.Token.AccessToken;
var client = new RestClient("https://mybusiness.googleapis.com/v4/accounts/116326379071192580211/locations/6608127685860731136/reviews?access_token=" + accessToken);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
""message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.\",\n "status": "UNAUTHENTICATED"
result.Credential contains both the access token and the refresh token so it seems to read the file in app_data. But the access code seems to be expired and is not being refreshed at this point and is not asking to login again neither:
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
AuthorizeAsync(cancellationToken);
You are not actually "telling the library" to refresh the access token, you are directly using the token that had been stored, and is now expired. Your code that looks like this:
var accessToken = result.Credential.Token.AccessToken;
should look like this:
var accessToekn = await result.Credential.GetAccessTokenForRequestAsync();
The GetAccessTokenForRequestAsync method will check if the access token needs refreshing and do so when needed.

EWS Connection Giving Unauthorized (401) Error

I have been working on a program that scans an exchange inbox for specific emails from a specified address. Currently the program reads the inbox, downloads the attachment, and moves the email to another folder. However, after about 15 pulls from the EWS server, the connection starts giving a 401 Unauthorized error until I restart the program. The program is setup to login via OAuth as basic auth is disabled by the system administrator. Below is the code that I am using to obtain the exchange connection and read the emails from the inbox.
Exchange Connection Code:
public static async Task<ExchangeService> GetExchangeConnection()
{
var pcaOptions = new PublicClientApplicationOptions
{
ClientId = AppID,
TenantId = TenantID,
};
var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();
var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };
var securePassword = new SecureString();
foreach (char c in Pasword)
securePassword.AppendChar(c);
try
{
var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, Username, securePassword).ExecuteAsync();
ExchangeService exchangeService = new ExchangeService()
{
Credentials = new OAuthCredentials(authResult.AccessToken),
Url = new Uri("https://outlook.office365.com/ews/exchange.asmx"),
};
return exchangeService;
}
catch
{
return null;
}
}
Email Retriever
public static List<Email> RetreiveEmails()
{
ExchangeService exchangeConnection = GetExchangeConnection().Result;
try
{
List<Email> Emails = new List<Email>();
TimeSpan ts = new TimeSpan(0, -5, 0, 0);
DateTime date = DateTime.Now.Add(ts);
SearchFilter.IsGreaterThanOrEqualTo EmailTimeFilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
if (exchangeConnection != null)
{
FindItemsResults<Item> findResults = exchangeConnection.FindItems(WellKnownFolderName.Inbox, EmailTimeFilter, new ItemView(10));
foreach (Item item in findResults)
{
if (item.Subject != null)
{
EmailMessage message = EmailMessage.Bind(exchangeConnection, item.Id);
message.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.TextBody));
Emails.Add(new Email(message.DateTimeReceived, message.From.Name.ToString(), message.Subject, message.TextBody.ToString(), (message.HasAttachments) ? "Yes" : "No", message.Id.ToString()));
}
}
}
exchangeConnection = null;
return Emails;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
}
The error occurs when the email retriever tries to either create the exchange connection or when requesting the emails from the folder. In either case the code will error out and give me 401 unauthorized while using credentials that work for the first dozen times and then fails after so many attempts. I have tried it with multiple different accounts and the issue persists with all of them and I have made sure that the application is authorized to access the exchange inbox. Any suggestions or help is much appreciated.
After doing further tracing regarding the 401 error it resulted in an issue with the token reaching the end of it's 1 hour lifespan. This is due to the original OAuth token having an initial life of 1 hour. This however was able to be fixed by setting up code to automatically refresh the token when needed. Here is the code to address this issue for anyone else who comes across this problem.
Authentication Manager:
class AuthenticationManager
{
protected IPublicClientApplication App { get; set; }
public AuthenticationManager(IPublicClientApplication app)
{
App = app;
}
public async Task<AuthenticationResult> AcquireATokenFromCacheOrUsernamePasswordAsync(IEnumerable<String> scopes, string username, SecureString password)
{
AuthenticationResult result = null;
var accounts = await App.GetAccountsAsync();
if (accounts.Any())
{
try
{
result = await (App as PublicClientApplication).AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException)
{ }
}
if (result == null)
{
result = await (App as PublicClientApplication).AcquireTokenByUsernamePassword(scopes, username, password).ExecuteAsync();
}
return result;
}
}
I am using direct username and password authentication but the line of code can be switched to getting the user authentication via interactive methods as well. The code essentially creates a new instance of the authentication manager with a PublicClientApplication used to initialize it which houses the appID and tenantID. After initializing, you can call the AquireATokenFromCacheOrUsernamePasswordAsync which will attempt to see if there is an account present to get a token against. Next it will attempt to retrieve the previously cached token or refresh the token if it expires in less than 5 minutes. If there is a token available it will return that to the main application. If there isn't a token available, it will acquire a new token using the username and password supplied. Implementation of this code looks something like this,
class ExchangeServices
{
AuthenticationManager Manager = null;
public ExchangeServices(String AppId, String TenantID)
{
var pcaOptions = new PublicClientApplicationOptions
{
ClientId = AppID,
TenantId = TenantID,
};
var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();
Manager = new AuthenticationManager(pca);
}
public static async Task<ExchangeService> GetExchangeService()
{
var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" }
var securePassword = new SecureString();
foreach(char c in Password)
securePassword.AppendChar(c);
var authResult = await Manager.AquireATokenFromCacheOrUsernamePasswordAsync(ewsScopes, Username, securePassword);
ExchangeService exchangeService = new ExchangeService()
{
Credentials = new OAuthCredentials(authResult.AccessToken),
Url = new Uri("https://outlook.office365.com/ews/exchange.asmx");
};
return exchangeService;
}
}
The code above is everything laid out that is needed to create a new authentication manager and use it to get and update new tokens while using EWS services through OAuth. This is the solution that I found to fix the issue described above.

Is it good practice to consume Login functionality from .NET Core API by storing tokens in HttpContext.Session?

I have created a .NET Core 2.0 Restful API, which has login functionality enabled with openiddict and JWS tokens. I also have a .NET Core Web App that consumes the API. Currently I am using HttpContext.Session on the client side to store and get the tokens in order to login the users. Since I am fairly new to .NET Core I wanted to ask if this is a good way to implement login functionality and if not how should I do it?
WebAPI AuthorizationController
[HttpPost("~/connect/token"), Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
{
Debug.Assert(request.IsTokenRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
if (request.IsPasswordGrantType())
{
var user = await _userManager.FindByNameAsync(request.Username);
var userRole = await _userManager.GetRolesAsync(user);
var loginRole = request.GetParameters().ElementAt(3).Value;
if (user == null || userRole.ElementAt(0) != loginRole)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The username/password couple is invalid."
});
}
// Validate the username/password parameters and ensure the account is not locked out.
var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure: true);
if (!result.Succeeded)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The username/password couple is invalid."
});
}
// Create a new authentication ticket.
var ticket = await CreateTicketAsync(request, user);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported."
});
}
WebApp AccountController
[HttpPost]
public IActionResult Login(LoginViewModel vm)
{
if (ModelState.IsValid)
{
using (HttpClient httpClient = new HttpClient())
{
Dictionary<string, string> tokenDetails = null;
var fullUrl = _appSettings.Value.Apis.GSRTCApi.Url + _appSettings.Value.Apis.GSRTCApi.LoginEndpoint;
HttpClient client = new HttpClient
{
BaseAddress = new Uri(fullUrl)
};
var login = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", vm.Email},
{"password", vm.Password},
{"role", vm.Role}
};
var response = client.PostAsync("Token", new FormUrlEncodedContent(login)).Result;
if (response.IsSuccessStatusCode)
{
tokenDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
if (tokenDetails != null && tokenDetails.Any())
{
var tokenNo = tokenDetails.ElementAt(2).Value;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);
HttpContext.Session.SetString("Username", vm.Email);
HttpContext.Session.SetString("Token", tokenNo);
//return RedirectToAction("Index", "Dashboard");
return Json(Url.Action("Index", "Dashboard"));
}
}
}
}
return PartialView("../Account/_Login", vm);
}

IdentityServer3 and external login through OpenIDConnect

In ASP.NET MVC app, I am trying to implement authentication against external OIDC service. For my testing I am using IdentityServer3 (https://identityserver.github.io/Documentation/) and public OIDC demo server: https://mitreid.org/
I cloned this sample from GitHub: https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/MVC%20Authentication
Then added the following code to register the public OIDC server as external login provider:
private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
{
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "<AuthTypeName>",
Authority = "https://mitreid.org/",
Caption = "MIT Test Server",
ClientId = "<Client Id>",
ClientSecret = "<Client Secret>",
RedirectUri = "https://localhost:44319/", //NOT SURE WHAT TO PUT HERE
ResponseType = "code",
Scope = "openid email profile",
SignInAsAuthenticationType = signInAsType
});
}
The code works, i get the option to login via external OIDC server. The browser redirects to the external server login page and when login and password is entered, the consent page is shown. However, after the browser navigates back to https://localhost:44319/ the user is not authenticated - User.Identity.IsAuthenticated is false.
Question: What should be correct value of RedirectUri property? Does OpenIdConnect middleware have capability to parse the authantication info passed in from external server or it must be coded manually? Is there any sample code how to do this?
I was studying the code and debugging quite a few hours (I am new to this) and I learned that:
This problem is related to OpenIdConnect OWIN Middleware implemented by Microsoft (https://github.com/aspnet/AspNetKatana/tree/dev/src/Microsoft.Owin.Security.OpenIdConnect).
The middleware from Microsoft expect that the OIDC server sends the message using HTTP POST, but the MIT server does HTTP GET
The middleware from Microsoft expect that there is id token along with code in the message obtained from OIDC server, but the MIT server sends only the code.
Looks like the RedirectUri can be any path under /identity because the middleware method AuthenticateCoreAsync() is hit on every request and it does compare request path to configured Options.CallbackPath (which is set from RedirectURI)
So I just had to implement the standard authorization code flow - exchange the code for id token, get claims, create authentication ticket and redirect to IdentityServer /identity/callback endpoint. When I've done this, everything started working. IdentityServer is awesome!
I inherited new set of classes from OpenIdConnect middleware and did override some methods. The key method is async Task<AuthenticationTicket> AuthenticateCoreAsync() in OpenIdConnectAuthenticationHandler. I pasted the code below in case it would help to someone.
public class CustomOidcHandler : OpenIdConnectAuthenticationHandler
{
private const string HandledResponse = "HandledResponse";
private readonly ILogger _logger;
private OpenIdConnectConfiguration _configuration;
public CustomOidcHandler(ILogger logger) : base(logger)
{
_logger = logger;
}
/// <summary>
/// Invoked to process incoming authentication messages.
/// </summary>
/// <returns>An <see cref="AuthenticationTicket"/> if successful.</returns>
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
// Allow login to be constrained to a specific path. Need to make this runtime configurable.
if (Options.CallbackPath.HasValue && Options.CallbackPath != (Request.PathBase + Request.Path))
return null;
OpenIdConnectMessage openIdConnectMessage = null;
if (string.Equals(Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
openIdConnectMessage = new OpenIdConnectMessage(Request.Query);
if (openIdConnectMessage == null)
return null;
ExceptionDispatchInfo authFailedEx = null;
try
{
return await CreateAuthenticationTicket(openIdConnectMessage).ConfigureAwait(false);
}
catch (Exception exception)
{
// We can't await inside a catch block, capture and handle outside.
authFailedEx = ExceptionDispatchInfo.Capture(exception);
}
if (authFailedEx != null)
{
_logger.WriteError("Exception occurred while processing message: ", authFailedEx.SourceException);
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the notification.
if (Options.RefreshOnIssuerKeyNotFound && authFailedEx.SourceException.GetType() == typeof(SecurityTokenSignatureKeyNotFoundException))
Options.ConfigurationManager.RequestRefresh();
var authenticationFailedNotification = new AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
{
ProtocolMessage = openIdConnectMessage,
Exception = authFailedEx.SourceException
};
await Options.Notifications.AuthenticationFailed(authenticationFailedNotification).ConfigureAwait(false);
if (authenticationFailedNotification.HandledResponse)
return GetHandledResponseTicket();
if (authenticationFailedNotification.Skipped)
return null;
authFailedEx.Throw();
}
return null;
}
private async Task<AuthenticationTicket> CreateAuthenticationTicket(OpenIdConnectMessage openIdConnectMessage)
{
var messageReceivedNotification =
new MessageReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
{
ProtocolMessage = openIdConnectMessage
};
await Options.Notifications.MessageReceived(messageReceivedNotification).ConfigureAwait(false);
if (messageReceivedNotification.HandledResponse)
{
return GetHandledResponseTicket();
}
if (messageReceivedNotification.Skipped)
{
return null;
}
// runtime always adds state, if we don't find it OR we failed to 'unprotect' it this is not a message we
// should process.
AuthenticationProperties properties = GetPropertiesFromState(openIdConnectMessage.State);
if (properties == null)
{
_logger.WriteWarning("The state field is missing or invalid.");
return null;
}
// devs will need to hook AuthenticationFailedNotification to avoid having 'raw' runtime errors displayed to users.
if (!string.IsNullOrWhiteSpace(openIdConnectMessage.Error))
{
throw new OpenIdConnectProtocolException(
string.Format(CultureInfo.InvariantCulture,
openIdConnectMessage.Error,
"Exception_OpenIdConnectMessageError", openIdConnectMessage.ErrorDescription ?? string.Empty,
openIdConnectMessage.ErrorUri ?? string.Empty));
}
// tokens.Item1 contains id token
// tokens.Item2 contains access token
Tuple<string, string> tokens = await GetTokens(openIdConnectMessage.Code, Options)
.ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(openIdConnectMessage.IdToken))
openIdConnectMessage.IdToken = tokens.Item1;
var securityTokenReceivedNotification =
new SecurityTokenReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context,
Options)
{
ProtocolMessage = openIdConnectMessage,
};
await Options.Notifications.SecurityTokenReceived(securityTokenReceivedNotification).ConfigureAwait(false);
if (securityTokenReceivedNotification.HandledResponse)
return GetHandledResponseTicket();
if (securityTokenReceivedNotification.Skipped)
return null;
if (_configuration == null)
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled)
.ConfigureAwait(false);
// Copy and augment to avoid cross request race conditions for updated configurations.
TokenValidationParameters tvp = Options.TokenValidationParameters.Clone();
IEnumerable<string> issuers = new[] {_configuration.Issuer};
tvp.ValidIssuers = tvp.ValidIssuers?.Concat(issuers) ?? issuers;
tvp.IssuerSigningTokens = tvp.IssuerSigningTokens?.Concat(_configuration.SigningTokens) ?? _configuration.SigningTokens;
SecurityToken validatedToken;
ClaimsPrincipal principal =
Options.SecurityTokenHandlers.ValidateToken(openIdConnectMessage.IdToken, tvp, out validatedToken);
ClaimsIdentity claimsIdentity = principal.Identity as ClaimsIdentity;
var claims = await GetClaims(tokens.Item2).ConfigureAwait(false);
AddClaim(claims, claimsIdentity, "sub", ClaimTypes.NameIdentifier, Options.AuthenticationType);
AddClaim(claims, claimsIdentity, "given_name", ClaimTypes.GivenName);
AddClaim(claims, claimsIdentity, "family_name", ClaimTypes.Surname);
AddClaim(claims, claimsIdentity, "preferred_username", ClaimTypes.Name);
AddClaim(claims, claimsIdentity, "email", ClaimTypes.Email);
// claims principal could have changed claim values, use bits received on wire for validation.
JwtSecurityToken jwt = validatedToken as JwtSecurityToken;
AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, properties);
if (Options.ProtocolValidator.RequireNonce)
{
if (String.IsNullOrWhiteSpace(openIdConnectMessage.Nonce))
openIdConnectMessage.Nonce = jwt.Payload.Nonce;
// deletes the nonce cookie
RetrieveNonce(openIdConnectMessage);
}
// remember 'session_state' and 'check_session_iframe'
if (!string.IsNullOrWhiteSpace(openIdConnectMessage.SessionState))
ticket.Properties.Dictionary[OpenIdConnectSessionProperties.SessionState] = openIdConnectMessage.SessionState;
if (!string.IsNullOrWhiteSpace(_configuration.CheckSessionIframe))
ticket.Properties.Dictionary[OpenIdConnectSessionProperties.CheckSessionIFrame] =
_configuration.CheckSessionIframe;
if (Options.UseTokenLifetime)
{
// Override any session persistence to match the token lifetime.
DateTime issued = jwt.ValidFrom;
if (issued != DateTime.MinValue)
{
ticket.Properties.IssuedUtc = issued.ToUniversalTime();
}
DateTime expires = jwt.ValidTo;
if (expires != DateTime.MinValue)
{
ticket.Properties.ExpiresUtc = expires.ToUniversalTime();
}
ticket.Properties.AllowRefresh = false;
}
var securityTokenValidatedNotification =
new SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context,
Options)
{
AuthenticationTicket = ticket,
ProtocolMessage = openIdConnectMessage,
};
await Options.Notifications.SecurityTokenValidated(securityTokenValidatedNotification).ConfigureAwait(false);
if (securityTokenValidatedNotification.HandledResponse)
{
return GetHandledResponseTicket();
}
if (securityTokenValidatedNotification.Skipped)
{
return null;
}
// Flow possible changes
ticket = securityTokenValidatedNotification.AuthenticationTicket;
// there is no hash of the code (c_hash) in the jwt obtained from the server
// I don't know how to perform the validation using ProtocolValidator without the hash
// that is why the code below is commented
//var protocolValidationContext = new OpenIdConnectProtocolValidationContext
//{
// AuthorizationCode = openIdConnectMessage.Code,
// Nonce = nonce
//};
//Options.ProtocolValidator.Validate(jwt, protocolValidationContext);
if (openIdConnectMessage.Code != null)
{
var authorizationCodeReceivedNotification = new AuthorizationCodeReceivedNotification(Context, Options)
{
AuthenticationTicket = ticket,
Code = openIdConnectMessage.Code,
JwtSecurityToken = jwt,
ProtocolMessage = openIdConnectMessage,
RedirectUri =
ticket.Properties.Dictionary.ContainsKey(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey)
? ticket.Properties.Dictionary[OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey]
: string.Empty,
};
await Options.Notifications.AuthorizationCodeReceived(authorizationCodeReceivedNotification)
.ConfigureAwait(false);
if (authorizationCodeReceivedNotification.HandledResponse)
{
return GetHandledResponseTicket();
}
if (authorizationCodeReceivedNotification.Skipped)
{
return null;
}
// Flow possible changes
ticket = authorizationCodeReceivedNotification.AuthenticationTicket;
}
return ticket;
}
private static void AddClaim(IEnumerable<Tuple<string, string>> claims, ClaimsIdentity claimsIdentity, string key, string claimType, string issuer = null)
{
string subject = claims
.Where(it => it.Item1 == key)
.Select(x => x.Item2).SingleOrDefault();
if (!string.IsNullOrWhiteSpace(subject))
claimsIdentity.AddClaim(
new System.Security.Claims.Claim(claimType, subject, ClaimValueTypes.String, issuer));
}
private async Task<Tuple<string, string>> GetTokens(string authorizationCode, OpenIdConnectAuthenticationOptions options)
{
// exchange authorization code at authorization server for an access and refresh token
Dictionary<string, string> post = null;
post = new Dictionary<string, string>
{
{"client_id", options.ClientId},
{"client_secret", options.ClientSecret},
{"grant_type", "authorization_code"},
{"code", authorizationCode},
{"redirect_uri", options.RedirectUri}
};
string content;
using (var client = new HttpClient())
{
var postContent = new FormUrlEncodedContent(post);
var response = await client.PostAsync(options.Authority.TrimEnd('/') + "/token", postContent)
.ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
// received tokens from authorization server
var json = JObject.Parse(content);
var accessToken = json["access_token"].ToString();
string idToken = null;
if (json["id_token"] != null)
idToken = json["id_token"].ToString();
return new Tuple<string, string>(idToken, accessToken);
}
private async Task<IEnumerable<Tuple<string, string>>> GetClaims(string accessToken)
{
string userInfoEndpoint = Options.Authority.TrimEnd('/') + "/userinfo";
var userInfoClient = new UserInfoClient(new Uri(userInfoEndpoint), accessToken);
var userInfoResponse = await userInfoClient.GetAsync().ConfigureAwait(false);
var claims = userInfoResponse.Claims;
return claims;
}
private static AuthenticationTicket GetHandledResponseTicket()
{
return new AuthenticationTicket(null, new AuthenticationProperties(new Dictionary<string, string>() { { HandledResponse, "true" } }));
}
private AuthenticationProperties GetPropertiesFromState(string state)
{
// assume a well formed query string: <a=b&>OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey=kasjd;fljasldkjflksdj<&c=d>
int startIndex = 0;
if (string.IsNullOrWhiteSpace(state) || (startIndex = state.IndexOf("OpenIdConnect.AuthenticationProperties", StringComparison.Ordinal)) == -1)
{
return null;
}
int authenticationIndex = startIndex + "OpenIdConnect.AuthenticationProperties".Length;
if (authenticationIndex == -1 || authenticationIndex == state.Length || state[authenticationIndex] != '=')
{
return null;
}
// scan rest of string looking for '&'
authenticationIndex++;
int endIndex = state.Substring(authenticationIndex, state.Length - authenticationIndex).IndexOf("&", StringComparison.Ordinal);
// -1 => no other parameters are after the AuthenticationPropertiesKey
if (endIndex == -1)
{
return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex).Replace('+', ' ')));
}
else
{
return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex, endIndex).Replace('+', ' ')));
}
}
}
public static class CustomOidcAuthenticationExtensions
{
/// <summary>
/// Adds the <see cref="OpenIdConnectAuthenticationMiddleware"/> into the OWIN runtime.
/// </summary>
/// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
/// <param name="openIdConnectOptions">A <see cref="OpenIdConnectAuthenticationOptions"/> contains settings for obtaining identities using the OpenIdConnect protocol.</param>
/// <returns>The updated <see cref="IAppBuilder"/></returns>
public static IAppBuilder UseCustomOidcAuthentication(this IAppBuilder app, OpenIdConnectAuthenticationOptions openIdConnectOptions)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (openIdConnectOptions == null)
throw new ArgumentNullException(nameof(openIdConnectOptions));
return app.Use(typeof(CustomOidcMiddleware), app, openIdConnectOptions);
}
}
and in Startup.cs
public class Startup
{
....
public void Configuration(IAppBuilder app)
{
....
private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
{
app.UseCustomOidcAuthentication(
new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "<name>",
Authority = "<OIDC server url>",
Caption = "<caption>",
ClientId = "<client id>",
ClientSecret = "<client secret>",
// might be https://localhost:44319/identity/<anything>
RedirectUri = "https://localhost:44319/identity/signin-customoidc",
ResponseType = "code",
Scope = "openid email profile address phone",
SignInAsAuthenticationType = signInAsType
}
);
}
....
}
....
}

How to sign in user on .NET Core server after authentication on Mobile App

I'm having troubles .NET Core Web API app authentication.
I want to:
1) Authenticate user with Google on Mobile App (currently iOS)
2) Using this authentication, create user record in database using AspNetCore.Identity and Entity Framework Core
3) Using same authentication, call Google Calendar API from .NET Core server
So far I figured out how to implement 1 and 3, but can't wrap my head around number 2.
My understanding is that to sign in user authenticated with third-party, due to documentation, you need to use SignInManager instance method ExternalLoginSignInAsync. It takes two arguments:
login provider (should be simple stirng as "Google") and unique provider key. My problem is that I can't find anywhere where can I get one.
Here is the list of all things I receive from Google Sign In result on mobile app:
Here is the method I try to call in.
// POST api/signup
[HttpPost]
public async Task<bool> Post([FromBody]string authorizationCode, [FromBody]string userId)
{
var tokenFromAuthorizationCode = await GetGoogleTokens(userId, authorizationCode);
var result = await signInManager.ExternalLoginSignInAsync(
"Google", tokenFromAuthorizationCode.IdToken, false);
if (result.Succeeded)
return true;
var externalLoginInfo = new ExternalLoginInfo(
ClaimsPrincipal.Current, "Google", tokenFromAuthorizationCode.IdToken, null);
return await SignInUser(externalLoginInfo);
}
private async Task<bool> SignInUser(ExternalLoginInfo info)
{
var newUser = new AppUser { Email = "test#test.com", UserName = "TestUser" };
var identResult = await userManager.CreateAsync(newUser);
if (identResult.Succeeded)
{
identResult = await userManager.AddLoginAsync(newUser, info);
if (identResult.Succeeded)
{
await signInManager.SignInAsync(newUser, false);
return true;
}
}
return false;
}
private async Task<TokenResponse> GetGoogleTokens(string userId, string authorizationCode)
{
TokenResponse token;
try
{
// TODO: Save access and refresh token to AppUser object
token = await authFlow.Flow.ExchangeCodeForTokenAsync(
userId, authorizationCode, "http://localhost:60473/signin-google", CancellationToken.None);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return token;
}
My question is: is it a correct path if you're building authentication via REST API, and if so, where could I get Google's provider key?
Thanks in advance.
Well apparently, provider key is just user id from Google.
Here is the solution that worked for me:
[HttpPost]
public async Task<AppUser> Post([FromBody]GoogleSignInCredentials credentials)
{
// 1. get user id from idToken
var oauthService = new Oauth2Service(new BaseClientService.Initializer { ApiKey = "{your api key}" });
var tokenInfoRequest = oauthService.Tokeninfo();
tokenInfoRequest.IdToken = credentials.IdToken;
var userInfo = await tokenInfoRequest.ExecuteAsync();
// 2. get access_token and refresh_token with new id and authorization code
var tokenFromAuthorizationCode = await GetGoogleTokens(userInfo.UserId, credentials.AuthorizationCode);
// 3. check if user exists
var result = await _signInManager.ExternalLoginSignInAsync(
"Google", userInfo.UserId, false);
if (result.Succeeded)
return await _userManager.FindByEmailAsync(userInfo.Email);
// 4. create user account
var externalLoginInfo = new ExternalLoginInfo(
ClaimsPrincipal.Current, "Google", userInfo.UserId, null);
// 5. fetch user
var createdUser = await SignInUser(externalLoginInfo, userInfo.Email);
if (createdUser != null)
{
createdUser.GoogleAccessToken = tokenFromAuthorizationCode.AccessToken;
createdUser.GoogleRefreshToken = tokenFromAuthorizationCode.RefreshToken;
var updateResult = await _userManager.UpdateAsync(createdUser);
if (updateResult.Succeeded)
return createdUser;
return null;
}
return null;
}
private async Task<AppUser> SignInUser(ExternalLoginInfo info, string email)
{
var newUser = new AppUser { Email = email, UserName = email };
var identResult = await _userManager.CreateAsync(newUser);
if (identResult.Succeeded)
{
identResult = await _userManager.AddLoginAsync(newUser, info);
if (identResult.Succeeded)
{
await _signInManager.SignInAsync(newUser, false);
return await _userManager.FindByEmailAsync(email);
}
}
return null;
}
private async Task<TokenResponse> GetGoogleTokens(string userId, string authorizationCode)
{
return await _authFlow.Flow.ExchangeCodeForTokenAsync(
userId, authorizationCode, "http://localhost:60473/signin-google", CancellationToken.None);
}

Categories