passing a user input variable to another file - c#

Im needing assistance on how to take a user input from a login page, check the Database for the username, and if it exist in the DB, pass it to another file that will pull the information pertaining to that username from the cosmosDB.
Below is the loginPage code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ToDoItems.Core.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
}
async void SignInProcedure(object sender, EventArgs e)
{
User user = new User(Entry_Username.Text, Entry_Password.Text);
if (user.CheckInformation())
{
//await Navigation.PushModalAsync(new CosmosDBService(Entry_Username.Text));
await Navigation.PushAsync(new ToDoItemsPage());
}
else
{
DisplayAlert("Login", "Login Failed", "Okay");
}
}
}
}
And Im trying to, first check the cosmosDB for the user name, then pass the username if it exist to the cosmosDBservice file to get the information associated with the username:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Data;
using System.Diagnostics;
using Microsoft.Azure.Documents.Linq;
using Xamarin.Forms;
using ToDoItems.Core.Pages;
namespace ToDoItems.Core
{
public class CosmosDBService
{
static string queryname;
public CosmosDBService(string logname)
{
// store the parameter for use later;
queryname = logname;
}
static DocumentClient docClient = null;
static readonly string databaseName = "Tasks";
static readonly string collectionName = "Items";
static async Task<bool> Initialize()
{
if (docClient != null)
return true;
try
{
docClient = new DocumentClient(new Uri(APIKeys.CosmosEndpointUrl), APIKeys.CosmosAuthKey);
// Create the database - this can also be done through the portal
await docClient.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseName });
// Create the collection - make sure to specify the RUs - has pricing implications
// This can also be done through the portal
await docClient.CreateDocumentCollectionIfNotExistsAsync(
UriFactory.CreateDatabaseUri(databaseName),
new DocumentCollection { Id = collectionName },
new RequestOptions { OfferThroughput = 400 }
);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
docClient = null;
return false;
}
return true;
}
// <GetToDoItems>
/// <summary>
/// </summary>
/// <returns></returns>
///
public async static Task<List<ToDoItem>> GetToDoItems()
{
var todos = new List<ToDoItem>();
if (!await Initialize())
return todos;
var todoQuery = docClient.CreateDocumentQuery<ToDoItem>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
.Where(name => name.Name == queryname)
.AsDocumentQuery();
while (todoQuery.HasMoreResults)
{
var queryResults = await todoQuery.ExecuteNextAsync<ToDoItem>();
todos.AddRange(queryResults);
}
return todos;
}
// </GetToDoItems>

you are already passing the username to the constructor of CosmosDBService
public void CosmosDBService(string user)
{
...
}
you need to create a class variable to store it
string username;
public void CosmosDBService(string user)
{
// store the parameter for use later
username = user;
...
}
then in your query use that class variable
public async static Task<List<ToDoItem>> GetToDoItems()
{
...
.Where(name => name.Name == username)
...
}

Related

C# System.InvalidOperationException DisplayClass0_0 error while getting token

I need to get token when I register, but it gives me an error
Hello everyone.
I got that error when I was trying to register to my project on Postman:
https://anotepad.com/note/read/tgrka47d
(System.InvalidOperationException: An exception was thrown while attempting to evaluate the LINQ query parameter expression 'value(DataAccess.Concrete.EntityFramework.EfUserDal+<>c__DisplayClass0_0).user.Id'. See the inner exception for more information.)
My UserManager is here:
`
using System.Collections.Generic;
using Business.Abstract;
using Core.Entities.Concrete;
using DataAccess.Abstract;
namespace Business.Concrete
{
public class UserManager : IUserService
{
IUserDal _userDal;
public UserManager(IUserDal userDal)
{
_userDal = userDal;
}
public List<OperationClaim> GetClaims(User user)
{
return _userDal.GetClaims(user);
}
public void Add(User user)
{
_userDal.Add(user);
}
public User GetByMail(string email)
{
return _userDal.Get(u => u.Email == email);
}
}
}
`
My AuthManager is here:
`
using Business.Abstract;
using Business.Constants;
using Core.Entities.Concrete;
using Core.Utilities.Results;
using Core.Utilities.Security.Hashing;
using Core.Utilities.Security.JWT;
using Entities.DTOs;
namespace Business.Concrete
{
public class AuthManager : IAuthService
{
private IUserService _userService;
private ITokenHelper _tokenHelper;
public AuthManager(IUserService userService, ITokenHelper tokenHelper)
{
_userService = userService;
_tokenHelper = tokenHelper;
}
public IDataResult<User> Register(UserForRegisterDto userForRegisterDto, string password)
{
byte[] passwordHash, passwordSalt;
HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt);
var user = new User
{
Email = userForRegisterDto.Email,
FirstName = userForRegisterDto.FirstName,
LastName = userForRegisterDto.LastName,
PasswordHash = passwordHash,
PasswordSalt = passwordSalt,
Status = true
};
_userService.Add(user);
return new SuccessDataResult<User>(user, Messages.UserRegistered);
}
public IDataResult<User> Login(UserForLoginDto userForLoginDto)
{
var userToCheck = _userService.GetByMail(userForLoginDto.Email);
if (userToCheck == null)
{
return new ErrorDataResult<User>(Messages.UserNotFound);
}
if (!HashingHelper.VerifyPasswordHash(userForLoginDto.Password, userToCheck.PasswordHash, userToCheck.PasswordSalt))
{
return new ErrorDataResult<User>(Messages.PasswordError);
}
return new SuccessDataResult<User>(userToCheck, Messages.SuccessfulLogin);
}
public IResult UserExists(string email)
{
if (_userService.GetByMail(email) != null)
{
return new ErrorResult(Messages.UserAlreadyExists);
}
return new SuccessResult();
}
public IDataResult<AccessToken> CreateAccessToken(User user)
{
var claims = _userService.GetClaims(user);
var accessToken = _tokenHelper.CreateToken(user, claims);
return new SuccessDataResult<AccessToken>(accessToken, Messages.AccessTokenCreated);
}
}
}
`
My AuthController is here:
`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Business.Abstract;
using Entities.DTOs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : Controller
{
private IAuthService _authService;
public AuthController(IAuthService authService)
{
_authService = authService;
}
[HttpPost("login")]
public ActionResult Login(UserForLoginDto userForLoginDto)
{
var userToLogin = _authService.Login(userForLoginDto);
if (!userToLogin.Success)
{
return BadRequest(userToLogin.Message);
}
var result = _authService.CreateAccessToken(userToLogin.Data);
if (result.Success)
{
return Ok(result.Data);
}
return BadRequest(result.Message);
}
[HttpPost("register")]
public ActionResult Register(UserForRegisterDto userForRegisterDto)
{
var userExists = _authService.UserExists(userForRegisterDto.Email);
if (!userExists.Success)
{
return BadRequest(userExists.Message);
}
var registerResult = _authService.Register(userForRegisterDto,userForRegisterDto.Password);
var result = _authService.CreateAccessToken(registerResult.Data);
if (result.Success)
{
return Ok(result.Data);
}
return BadRequest(result.Message);
}
}
}
`
My EfUserDal is here:
`
using System.Collections.Generic;
using Core.DataAccess.EntityFramework;
using Core.Entities.Concrete;
using DataAccess.Abstract;
using System.Linq;
namespace DataAccess.Concrete.EntityFramework
{
public class EfUserDal : EfEntityRepositoryBase<User,CarRentalContext>,IUserDal
{
public List<OperationClaim> GetClaims(User user)
{
using (CarRentalContext context = new CarRentalContext())
{
var result = from operationClaim in context.OperationClaims
join userOperationClaim in context.UserOperationClaims
on operationClaim.Id equals userOperationClaim.OperationClaimId
where userOperationClaim.UserId == user.Id
select new OperationClaim {Id = operationClaim.Id, Name = operationClaim.Name};
return result.ToList();
}
}
}
}
`
I need to get a token when I register. How can I fix this?
You picked up the wrong lines from your stacktrace to focus on.
It states the following in the inner exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at DataAccess.Concrete.EntityFramework.EfUserDal.GetClaims(User user) in /home/mert/Desktop/Project/ReCapProject/DataAccess/Concrete/EntityFramework/EfUserDal.cs:line 20
Which means you have a variable on line 20 in your EfUserDal which does not have a value at runtime.
Since the next line mentions ToList, I'm guessing result is null after evaluating the query. Use debugging to see what value each variable in your query is getting before it's evaluated. Probably one of them is null

.NET Core Mediatr Usage not all code paths return a value

In my API, I am trying to use MediatR; so in my controller code, I wrote:
[HttpPost("AdminLogin")
public async Task<ActionResult<Admin>> GetContractById(Admin admin)
{
var response = await _mediator.Send(new UserLoginRequest(admin));
if (response.HasError)
{
return BadRequest(response);
}
return Ok(response);
}
Then in my UserLoginRequest.cs I wrote this code:
using MediatR;
using SinavAlemiPanel.Domain.Models;
using SinavAlemiPanel.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SinavAlemiPanel.Application.Requests.UserRequests
{
public class UserLoginRequest :IRequest<BaseResponse<Admin>>
{
private Admin admin;
public UserLoginRequest(Admin admin)
{
this.admin = admin;
}
public Admin UserCredentials { get; set; }
}
public sealed class UserLoginRequestHandlers : IRequestHandler<UserLoginRequest, BaseResponse<Admin>>
{
private readonly IUserService _userService;
public UserLoginRequestHandlers(IUserService userService)
{
_userService = userService;
}
public async Task<BaseResponse<Admin>> Handle(UserLoginRequest request, CancellationToken cancellationToken)
{
await Task.Run(() =>
{
return _userService.Login(request.UserCredentials);
});
}
}
}
And in my service I have:
using Dapper;
using SinavAlemiPanel.Domain.Models;
using SinavAlemiPanel.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace SinavAlemiPanel.Infrastructure.Services
{
public class UserService : IUserService
{
private readonly IBaseService _baseService;
private readonly DBConnection _db;
public UserService(IBaseService baseService)
{
_baseService = baseService;
}
public Admin Login(Admin admin)
{
Admin result = new Admin();
var dynamicParams = new DynamicParameters();
var conn = _baseService.GetConnection(_db.GetConnString());
try
{
dynamicParams.Add("#username", admin.Username, DbType.String, ParameterDirection.Input);
dynamicParams.Add("#pass", admin.Password, DbType.String, ParameterDirection.Input);
result = SqlMapper.Query<Admin>(conn, "dbo.SP_Admin_Login #username, #pass", dynamicParams).SingleOrDefault();
conn.Close();
if (result != null && result.Id > 0)
{
result.Accesses = (result != null && result.Id > 0) ? Accesses(result.Id) : new List<Access>();
}
return result;
}
catch(Exception ex)
{
return result;
}
}
public List<Access> Accesses(int refAdmin)
{
List<Access> result = new List<Access>();
var dynamicParams = new DynamicParameters();
var conn = _baseService.GetConnection(_db.GetConnString());
try
{
dynamicParams.Add("#refAdmin", refAdmin, DbType.Int32, ParameterDirection.Input);
result = SqlMapper.Query<Access>(conn, "dbo.SP_Admin_Accesses #refAdmin", dynamicParams).ToList();
conn.Close();
return result;
}
catch (Exception e)
{
return result;
}
}
}
}
My problem is that the code doesn't accept in request handle, I get this error:
Error CS0161
'UserLoginRequestHandlers.Handle(UserLoginRequest, CancellationToken)': not all code paths return a value
I am new in C# so I couldn't detect the error. How can I solve this issue?
Thanks in advance
You are missing a return statement in the Handle method, but adding it alone won't fix the compilation you need to translate Admin returned by _userService.Login to BaseResponse<Admin>. Also since _userService.Login is a sync method - no need for Task.Run and assync-await - use Task.FromResult instead. Something like this (assiming the existence of corresponding BaseResponse ctor):
public Task<BaseResponse<Admin>> Handle(UserLoginRequest request, CancellationToken cancellationToken)
{
var admin = _userService.Login(request.UserCredentials);
return Task.FromResult(new BaseResponse<Admin>(admin)); // no need for Task.Run and async-await cause Login is synchronous method
}
The another approach is to create your service as async:
public async Task<Admin> Login(Admin admin)
And you need a corresponding constructor in your BaseResponse class:
public async Task<BaseResponse<Admin>> Handle(UserLoginRequest request, CancellationToken cancellationToken)
{
Admin admin = await _userService.Login(request.UserCredentials);
return new BaseResponse<Admin>(admin);
}
BaseResponse example:
public class BaseResponse<T>
{
private T Response;
public BaseResponse(T response)
{
Response = response;
}
}

ASP.Net MVC C#: Failed to acquire token silently as no token was found in the cache. Call method AcquireToken

I am attempting to retrieve Azure AD user profile data via the Microsoft Graph API. I have set up a small Visual Studio MVC app using code examples from various sources, primarily Microsoft. In my ignorance, I thought this would be a fairly simple process.
I have browsed other similar cases on SO and have attempted to make use of suggestions from others but to no avail. I have been troubleshooting this issue for four days and would greatly appreciate any assistance.
// UserProfileController.cs
-- contains the calling method: var graphToken = await AuthenticationHelper.GetGraphAccessToken();
//
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using SSO_Test.Models;
using SSO_Test.Utils;
using System.Net.Http.Headers;
namespace SSO_Test.Controllers
{
[Authorize]
public class UserProfileController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private string clientId = ConfigurationManager.AppSettings["ClientId"];
private string appKey = ConfigurationManager.AppSettings["ClientSecret"];
private string aadInstance = ConfigurationManager.AppSettings["AADInstance"];
private string graphResourceID = "https://graph.microsoft.com";
// GET: UserProfile
public async Task<ActionResult> Index()
{
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
try
{
var graphToken = await AuthenticationHelper.GetGraphAccessToken();
var authenticationProvider = new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
return Task.FromResult(0);
});
var graphClient = new GraphServiceClient(authenticationProvider);
var user = await graphClient.Me.Request().GetAsync();
return View(user);
}
catch (AdalException ex)
{
// Return to error page.
ViewBag.Message = ex.Message;
return View("Error");
}
// if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
catch (Exception)
{
return View("Relogin");
}
}
public void RefreshSession()
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/Home" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
}
//AuthenticationHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using SSO_Test.Models;
namespace SSO_Test.Utils
{
public static class AuthenticationHelper
{
public static async Task<string> GetGraphAccessToken()
{
var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
// create auth context
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureAdAuthority, new ADALTokenCache(signInUserId));
//added check point for verification purposes
System.Diagnostics.Debug.WriteLine("Check point #1");
//GOOD TO THIS POINT
var result = await authContext.AcquireTokenSilentAsync(SettingsHelper.AzureAdGraphResourceURL, clientCredential, userIdentifier);
//ERROR MESSAGE: "Failed to acquire token silently as no token was found in the cache. Call method AcquireToken"
System.Diagnostics.Debug.WriteLine("Check point #2");
//app never reaches the second check point
return result.AccessToken;
}
}
}
//ADALTokenCache.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Security;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace SSO_Test.Models
{
public class ADALTokenCache : TokenCache
{
private ApplicationDbContext db = new ApplicationDbContext();
private string userId;
private UserTokenCache Cache;
public ADALTokenCache(string signedInUserId)
{
// associate the cache to the current user of the web app
userId = signedInUserId;
this.BeforeAccess = BeforeAccessNotification;
this.AfterAccess = AfterAccessNotification;
this.BeforeWrite = BeforeWriteNotification;
// look up the entry in the database
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
// place the entry in memory
this.DeserializeAdalV3((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache"));
}
// clean up the database
public override void Clear()
{
base.Clear();
var cacheEntry = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
db.UserTokenCacheList.Remove(cacheEntry);
db.SaveChanges();
}
// Notification raised before ADAL accesses the cache.
// This is your chance to update the in-memory copy from the DB, if the in-memory version is stale
void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
if (Cache == null)
{
// first time access
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
}
else
{
// retrieve last write from the DB
var status = from e in db.UserTokenCacheList
where (e.webUserUniqueId == userId)
select new
{
LastWrite = e.LastWrite
};
// if the in-memory copy is older than the persistent copy
if (status.First().LastWrite > Cache.LastWrite)
{
// read from from storage, update in-memory copy
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
}
}
this.DeserializeAdalV3((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache"));
}
// Notification raised after ADAL accessed the cache.
// If the HasStateChanged flag is set, ADAL changed the content of the cache
void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if state changed
if (this.HasStateChanged)
{
Cache = new UserTokenCache
{
webUserUniqueId = userId,
//cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"),
cacheBits = MachineKey.Protect(this.SerializeAdalV3(), "ADALCache"),
LastWrite = DateTime.Now
};
// update the DB and the lastwrite
db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified;
db.SaveChanges();
this.HasStateChanged = false;
}
}
void BeforeWriteNotification(TokenCacheNotificationArgs args)
{
// if you want to ensure that no concurrent write take place, use this notification to place a lock on the entry
}
public override void DeleteItem(TokenCacheItem item)
{
base.DeleteItem(item);
}
}
}
//ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SSO_Test.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<UserTokenCache> UserTokenCacheList { get; set; }
}
public class UserTokenCache
{
[Key]
public int UserTokenCacheId { get; set; }
public string webUserUniqueId { get; set; }
public byte[] cacheBits { get; set; }
public DateTime LastWrite { get; set; }
}
}
As you can see, I have noted in the GetGraphAccessToken() method the error message:
"Failed to acquire token silently as no token was found in the cache.
Call method AcquireToken".
I was able to isolate the AcquireTokenSilentAsync() method as the culprit by bracketing it with a pair of Debug.Writeline statements, the first which ran successfully and the second which did not. This was verified by reviewing the contents of the VS Output window, as follows:
Check point #1
Exception thrown:
'Microsoft.IdentityModel.Clients.ActiveDirectory.AdalSilentTokenAcquisitionException'
in mscorlib.dll
The program '[13980] iisexpress.exe' has exited with code -1
(0xffffffff).
I really want this thing to work and I would much prefer utilizing the Graph SDK approach as opposed to using a REST API.
Again, I have been banging my head against the wall for four-plus days. My head is okay but the wall is in bad shape.
Thanks in advance.
If AcquireTokenSilent fails, it means that there is no token in the cache so you have to go get one via AcquireToken as in this.
You've tagged the question with "B2C" but is looks like you are using Azure AD?
There are a full set of Authentication Providers for the standard set of OAuth flows that are now available so you don't have to use the DelegatedAuthenticationProvider any more. https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth There are docs about how to chose the right Auth provider based on scenario here https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS

Websockets using OWIN

All the examples using Microsoft WebSockets over a web-api that I've seen so far use IIS, the implementation is on the get method the HTTP connection is upgraded to a websocket and an instance of websocket handler is passed to the HTTPContext
public HttpResponseMessage Get() {
if (HttpContext.Current.IsWebSocketRequest) {
var noteHandler = new NoteSocketHandler();
HttpContext.Current.AcceptWebSocketRequest(noteHandler);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
What am trying to achieve is to do the same on an OWIN pipeline. The problem am facing is the connection is being upgraded to use Websockets but it is not utilizing my websocket handler. Where am I going wrong? Please suggest.
Controller utilizing OwinContext (Followed the example WebSockets in Nancy using OWIN),
public HttpResponseMessage Get() {
IOwinContext owinContext = Request.GetOwinContext();
WebSocketAccept acceptToken = owinContext.Get<WebSocketAccept>("websocket.Accept");
if (acceptToken != null) {
var requestHeaders = GetValue<IDictionary<string, string[]>>(owinContext.Environment, "owin.RequestHeaders");
Dictionary<string, object> acceptOptions = null;
string[] subProtocols;
if (requestHeaders.TryGetValue("Sec-WebSocket-Protocol", out subProtocols) && subProtocols.Length > 0) {
acceptOptions = new Dictionary<string, object>();
// Select the first one from the client
acceptOptions.Add("websocket.SubProtocol", subProtocols[0].Split(',').First().Trim());
}
acceptToken(acceptOptions, async wsEnv => {
var wsSendAsync = (WebSocketSendAsync)wsEnv["websocket.SendAsync"];
var wsRecieveAsync = (WebSocketReceiveAsync)wsEnv["websocket.ReceiveAsync"];
var wsCloseAsync = (WebSocketCloseAsync)wsEnv["websocket.CloseAsync"];
var wsCallCancelled = (CancellationToken)wsEnv["websocket.CallCancelled"];
//should I pass the handler to an event?
var handler = new NoteSocketHAndler();
});
} else {
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
Handler Code:
using System;
using Socket = Microsoft.Web.WebSockets;
using Newtonsoft.Json;
public class NoteSocketHandler : Socket.WebSocketHandler {
private static Socket.WebSocketCollection connections = new Socket.WebSocketCollection();
public NoteSocketHandler() {
}
public override void OnOpen() {
connections.Add(this);
}
public override void OnClose() {
connections.Remove(this);
}
public override void OnMessage(string message) {
ChatMessage chatMessage = JsonConvert.DeserializeObject<ChatMessage>(message);
foreach (var connection in connections) {
connection.Send(message);
}
}
}
I finally figured out how to resolve the issue. You can find the code below, also I've written a basic app which uses websockets on OWIN.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin;
namespace NoteApp.WebService.Controller {
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NoteApp.WebService.Handler;
using WebSocketAccept = System.Action<
System.Collections.Generic.IDictionary<string, object>, // WebSocket Accept parameters
System.Func< // WebSocketFunc callback
System.Collections.Generic.IDictionary<string, object>, // WebSocket environment
System.Threading.Tasks.Task>>;
using WebSocketCloseAsync = System.Func<
int, // closeStatus
string, // closeDescription
System.Threading.CancellationToken, // cancel
System.Threading.Tasks.Task>;
using WebSocketReceiveAsync = System.Func<
System.ArraySegment<byte>, // data
System.Threading.CancellationToken, // cancel
System.Threading.Tasks.Task<
System.Tuple< // WebSocketReceiveTuple
int, // messageType
bool, // endOfMessage
int>>>; // count
// closeStatusDescription
using WebSocketReceiveResult = System.Tuple<int, bool, int>;
using WebSocketSendAsync = System.Func<
System.ArraySegment<byte>, // data
int, // message type
bool, // end of message
System.Threading.CancellationToken, // cancel
System.Threading.Tasks.Task>;
public class NoteController : ApiController {
public HttpResponseMessage Get() {
IOwinContext owinContext = Request.GetOwinContext();
WebSocketAccept acceptToken = owinContext.Get<WebSocketAccept>("websocket.Accept");
if (acceptToken != null) {
var requestHeaders = GetValue<IDictionary<string, string[]>>(owinContext.Environment, "owin.RequestHeaders");
Dictionary<string, object> acceptOptions = null;
string[] subProtocols;
if (requestHeaders.TryGetValue("Sec-WebSocket-Protocol", out subProtocols) && subProtocols.Length > 0) {
acceptOptions = new Dictionary<string, object>();
// Select the first one from the client
acceptOptions.Add("websocket.SubProtocol", subProtocols[0].Split(',').First().Trim());
}
acceptToken(acceptOptions, ProcessSocketConnection);
} else {
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
private async Task ProcessSocketConnection(IDictionary<string, object> wsEnv) {
var wsSendAsync = (WebSocketSendAsync)wsEnv["websocket.SendAsync"];
var wsCloseAsync = (WebSocketCloseAsync)wsEnv["websocket.CloseAsync"];
var wsCallCancelled = (CancellationToken)wsEnv["websocket.CallCancelled"];
var wsRecieveAsync = (WebSocketReceiveAsync)wsEnv["websocket.ReceiveAsync"];
//pass the sendasync tuple and the cancellation token to the handler. The handler uses the sendasync method to send message. Each connected client has access to this
var handler = new NoteSocketHandler(wsSendAsync, CancellationToken.None);
handler.OnOpen();
var buffer = new ArraySegment<byte>(new byte[100]);
try {
object status;
while (!wsEnv.TryGetValue("websocket.ClientCloseStatus", out status) || (int)status == 0) {
WebSocketReceiveResult webSocketResultTuple = await wsRecieveAsync(buffer, CancellationToken.None);
int count = webSocketResultTuple.Item3;
handler.OnMessage(Encoding.UTF8.GetString(buffer.Array, 0, count));
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
throw ex;
}
handler.OnClose();
await wsCloseAsync((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
}
T GetValue<T>(IDictionary<string, object> env, string key) {
object value;
return env.TryGetValue(key, out value) && value is T ? (T)value : default(T);
}
}
}

Creating Owin Auth Provider that Exchanges a Custom Token for a .Net Auth Cookie

I am trying to create an SSO like solution between 2 .Net applications
.Net app 1 has a custom token generator and endpoints to validate tokens that returns user information.
.Net application 2 is protected using Owin and was a typical standalone app and a user would directly login using a password and username.
I created (based on Passion for Coding Blog and Github) a custom Owin provider that would look for a token either in a Authorization header or as a query parameter from a link that a user would click a link from .Net App 1 and send to the .Net App 2 the token in the query string as at GET (I know this is not secure we are eventually going to use OpenID for what it’s worth we just need this for a demo). I am able to get the token validate it and create an Identity and authenticate I just cant get the provider to create a .Net Auth Cookie so that subsequent requests are authenticated and not given a 401 error.
Handler File:
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace SomeOAuth
{
// Created by the factory in the someAuthenticationMiddleware class.
class SomeAuthenticationHandler : AuthenticationHandler<SomeAuthenticationOptions>
{
private const string HandledResponse = "HandledResponse";
private readonly ILogger _logger;
private readonly string _challenge;
/// <summary>
/// Creates a new OpenIdConnectAuthenticationHandler
/// </summary>
/// <param name="logger"></param>
public SomeAuthenticationHandler(ILogger logger, string challenge)
{
_logger = logger;
_challenge = challenge;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
// ASP.Net Identity requires the NameIdentitifer field to be set or it won't
// accept the external login (AuthenticationManagerExtensions.GetExternalLoginInfo)
string requestToken = null;
string authorization = Request.Headers.Get("Authorization");
if (!string.IsNullOrEmpty(authorization))
{
if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
requestToken = authorization.Substring("Bearer ".Length).Trim();
}
}
if (string.IsNullOrEmpty(requestToken))
{
string accessTokenParam = Request.Query.Get("access_token");
if (!string.IsNullOrEmpty(accessTokenParam))
{
requestToken = accessTokenParam;
}
}
if (!string.IsNullOrEmpty(requestToken))
{
using (var client = new HttpClient())
{
try
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://testserver/API/Auth/Authenticate");
var s = new StringContent("{\"oauthtoken\":\"" + requestToken + "\"}", Encoding.UTF8, "application/json");
// var ts = s.ToString();
request.Content = new StringContent("{\"oauthtoken\":\"" + requestToken + "\"}", Encoding.UTF8, "application/json");
System.Diagnostics.Debug.WriteLine("Request:");
System.Diagnostics.Debug.WriteLine(request.ToString());
if (request.Content != null)
{
System.Diagnostics.Debug.WriteLine(await request.Content.ReadAsStringAsync());
}
System.Diagnostics.Debug.WriteLine("");
var response = await client.SendAsync(request);
if (response.StatusCode != HttpStatusCode.OK)
{
return null;
}
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var userId = payload.Value<string>("username");
//need to get the useid of the user as well as the name and role
var identity = new ClaimsIdentity("Some");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "fakeuser", null, "Some"));
/*
identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName + " " + user.LastName));
identity.AddClaim(new Claim(ClaimTypes.Email, user.ContactInfo.Email));
identity.AddClaim(new Claim(ClaimTypes.Sid, user.Guid.ToString()));
*/
identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Some"));
AuthenticationProperties properties = CreateProperties("fakeusername", "");
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
return ticket;
}
catch (Exception e)
{
Console.WriteLine("asdf e = " + e.Message);
}
return null;
}
}
else
{
return null;
}
}
/// <summary>
/// Handles SignIn
/// </summary>
/// <returns></returns>
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode == 401)
{
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge == null)
{
return null;
}
}
return Task.FromResult<object>(null);
}
public override Task<bool> InvokeAsync()
{
return InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
AuthenticationTicket ticket = await AuthenticateAsync();
if (ticket != null)
{
string value;
if (ticket.Properties.Dictionary.TryGetValue(HandledResponse, out value) && value == "true")
{
return true;
}
if (ticket.Identity != null)
{
Request.Context.Authentication.SignIn(ticket.Properties, ticket.Identity);
}
// Redirect back to the original secured resource, if any.
if (!string.IsNullOrWhiteSpace(ticket.Properties.RedirectUri))
{
Response.Redirect(ticket.Properties.RedirectUri);
return true;
}
}
return false;
}
private static AuthenticationTicket GetHandledResponseTicket()
{
return new AuthenticationTicket(null, new AuthenticationProperties(new Dictionary<string, string>() { { HandledResponse, "true" } }));
}
public AuthenticationProperties CreateProperties(string userName, string Roles)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName },
{"roles",Roles}
};
return new AuthenticationProperties(data);
}
}
}
Middleware file:
using Microsoft.Owin;
using Microsoft.Owin.Security.Infrastructure;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Logging;
namespace SomeOAuth
{
// One instance is created when the application starts.
public class SomeeAuthenticationMiddleware : AuthenticationMiddleware<SomeAuthenticationOptions>
{
private readonly ILogger _logger;
private readonly string _challenge = "Bearer";
public SomeAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, SomeAuthenticationOptions options)
: base(next, options)
{
_logger = app.CreateLogger<SomeAuthenticationMiddleware>();
}
// Called for each request, to create a handler for each request.
protected override AuthenticationHandler<SomeAuthenticationOptions> CreateHandler()
{
return new SomeAuthenticationHandler(_logger, _challenge);
}
}
}
Options file:
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomeOAuth
{
public class SomeAuthenticationOptions : AuthenticationOptions
{
public SomeAuthenticationOptions(string userName, string userId)
: base(OAuthDefaults.AuthenticationType)
{
UserName = userName;
UserId = userId;
}
public string Challenge { get; set; }
public string UserName { get; set; }
public string UserId { get; set; }
}
}
Extensions File:
using Microsoft.Owin.Extensions;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomeOAuth
{
public static class SomeAuthenticationExtensions
{
public static IAppBuilder UseSomeeAuthentication(this IAppBuilder app, SomeAuthenticationOptions options)
{
if (app == null)
{
throw new ArgumentNullException("app");
}
app.Use(typeof(SomeAuthenticationMiddleware), app, options);
app.UseStageMarker(PipelineStage.Authenticate);
return app;
}
}
}
Startup File
using System;
using CoreLX.Palms.VS.Web.Services;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin.Security.Providers.OpenID;
using Microsoft.Owin.Security.OAuth;
using Owin;
using SomeOAuth;
using CoreLX.Palms.LS.Web.Common.Models.User;
namespace CoreLX.Palms.VS.Web
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager> (ApplicationSignInManager.Create);
//app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
//{
// AccessTokenProvider = new SomeTokenProvider(),
// Provider = new SomeOAuthBearerAuthenticationProvider("access_token")
//});
app.UseSomeAuthentication(new SomeAuthenticationOptions("testuser", "9"));
// Use a cookie to temp store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = new TimeSpan(0, 3, 0, 0),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
OnApplyRedirect = ctx =>
{
// don't redirect to login page for webapi/ajax requests
// http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/
if (!IsWebApiRequest(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
});
app.UseOpenIDAuthentication("http://me.yahoo.com/", "Yahoo");
}
private static bool IsWebApiRequest(IOwinRequest request)
{
// hack for check if it's webapi requesr
if (request.Path.StartsWithSegments(new PathString("/api")))
{
return true;
}
// checks if it's ajax request
IReadableStringCollection query = request.Query;
if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest"))
{
return true;
}
IHeaderDictionary headers = request.Headers;
return ((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest"));
}
}
}
I have also tried to just use the custom providers for the standard provided
OAuthBearerAuthenticationProvider
Here is the code for the plugins/providers that I tried I don't have a preference as long as there are no 401 errors:
Provider
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SomeOAuth
{
public class SomeOAuthBearerAuthenticationProvider : IOAuthBearerAuthenticationProvider
{
readonly string _parameterName;
public SomeOAuthBearerAuthenticationProvider(string parameterName)
{
_parameterName = parameterName;
}
public Task ApplyChallenge(OAuthChallengeContext context)
{
return Task.FromResult<object>(null);
}
public Task RequestToken(OAuthRequestTokenContext context)
{
string token = context.Token;
if(string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(_parameterName))
{
token = context.Request.Query.Get(_parameterName);
}
if (!string.IsNullOrEmpty(token))
{
context.Token = token;
}
return Task.FromResult<object>(null);
}
public Task ValidateIdentity(OAuthValidateIdentityContext context)
{
context.Validated();
return Task.FromResult<object>(null);
}
}
}
And the AccessTokenProvider
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json.Linq;
using System;
//using Newtonsoft.Json.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace SomeOAuth
{
public sealed class SomeTokenProvider : AuthenticationTokenProvider
{
public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
using (var client = new HttpClient())
{
try
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://someserver/API/Auth/Authenticate");
var s = new StringContent("{\"oauthtoken\":\"" + context.Token + "\"}", Encoding.UTF8, "application/json");
// var ts = s.ToString();
request.Content = new StringContent("{\"oauthtoken\":\"" + context.Token + "\"}", Encoding.UTF8, "application/json");
System.Diagnostics.Debug.WriteLine("Request:");
System.Diagnostics.Debug.WriteLine(request.ToString());
if (request.Content != null)
{
System.Diagnostics.Debug.WriteLine(await request.Content.ReadAsStringAsync());
}
System.Diagnostics.Debug.WriteLine("");
var response = await client.SendAsync(request);
if (response.StatusCode != HttpStatusCode.OK)
{
return;
}
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var userId = payload.Value<string>("username");
//need to get the useid of the user as well as the name and role
var identity = new ClaimsIdentity("Some");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "someuser", null, "Some"));
/*
identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName + " " + user.LastName));
identity.AddClaim(new Claim(ClaimTypes.Email, user.ContactInfo.Email));
identity.AddClaim(new Claim(ClaimTypes.Sid, user.Guid.ToString()));
*/
identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Some"));
context.SetTicket(new AuthenticationTicket(identity, new AuthenticationProperties()));
}
catch (Exception e)
{
Console.WriteLine("asdf e = " + e.Message);
}
}
}
}
}
You're registering the middleware in the wrong order. The owin middleware model works through the auth middleware placing an instruction (AuthenticationResponseGrant) in the owin dictionary before returning to the previous middleware. If that previous middleware is the external cookie middleware it will issue a cookie. There's more detail in my blog post. So switch those two lines:
// Use a cookie to temp store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseSomeAuthentication(new SomeAuthenticationOptions("testuser", "9"));
There's also another issue. The AuthenticationType of the identity must mach the one of the cookie middleware. The UseExternalSignInCookie method internally calls app.SetDefaultSignInAsAuthenticationType so when you create the new ClaimsIdentity you shouldn't use Some as authentication type but rather convey the result of app.GetDefaultSignInAsAuthenticationType() through the SignInAsAuthenticationType on the options class. The call to app.GetDefaultSignInAsAuthenticationType() is typically done in the middleware constructor.

Categories

Resources