.net 5 how to setup authorization using custom provider - c#

in my .net 5 website i have to read user login from header and the call external webservice to check if is authorized and get permission list.
EDIT 3:
GOALS
Read current user from http header setted by corporate single sign-on
Read user permission and info by calling external web services and
keep them daved to prevent extra-calls for every action
let the user be free to access by any page
authorize by default all controller's actions with custom claims
Actual Problem
context.User.Identity.IsAuthenticated in middleware is always false
Actual code
Startup - ConfigureServices
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddControllers(options => { options.Filters.Add<AuditAuthorizationFilter>(); });
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Startup - Configure
app.UseMiddleware<AuthenticationMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
Middleware
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
// Dependency Injection
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, context.Request.Headers["Token"]),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaultsAuthenticationScheme);
var authProperties = new AuthenticationProperties();
await context.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
await _next(context);
}
}
Filter
public class AuditAuthorizationFilter : IAuthorizationFilter, IOrderedFilter
{
public int Order => -1;
private readonly IHttpContextAccessor _httpContextAccessor;
public AuditAuthorizationFilter(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
if (context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new ForbidResult();
}
else
{
string metodo = $"{context.RouteData.Values["controller"]}/{context.RouteData.Values["action"]}";
if (!context.HttpContext.User.HasClaim("type", metodo))
{
context.Result = new ForbidResult();
}
}
}
}
EDIT 2:
my Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddDevExpressControls();
services.AddTransient<ILoggingService, LoggingService>();
services.AddHttpContextAccessor();
services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);
services.ConfigureReportingServices(configurator => {
configurator.UseAsyncEngine();
configurator.ConfigureWebDocumentViewer(viewerConfigurator => {
viewerConfigurator.UseCachedReportSourceBuilder();
});
});
services.AddControllersWithViews().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddControllers(options => { options.Filters.Add(new MyAuthenticationAttribute ()); });
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDevExpressControls();
app.UseExceptionHandlerMiddleware(Log.Logger, errorPagePath: "/Error/HandleError" , respondWithJsonErrorDetails: true);
app.UseStatusCodePagesWithReExecute("/Error/HandleError/{0}");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSerilogRequestLogging(opts => opts.EnrichDiagnosticContext = LogHelper.EnrichFromRequest);
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
EDIT 1:
to adapt original code to .net 5 i made some changes:
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
const string MyHeaderToken = "HTTP_KEY";
string userSSO = null;
if (string.IsNullOrWhiteSpace(context.HttpContext.Request.Headers[MyHeaderToken]))
{
userSSO = context.HttpContext.Request.Headers[MyHeaderToken];
}
if (string.IsNullOrWhiteSpace(userSSO))
{
//filterContext.Result = new unh();
}
else
{
// Create GenericPrincipal
GenericIdentity webIdentity = new GenericIdentity(userSSO, "My");
//string[] methods = new string[0]; // GetMethods(userSSO);
GenericPrincipal principal = new GenericPrincipal(webIdentity, null);
IdentityUser user = new (userSSO);
Thread.CurrentPrincipal = principal;
}
}
but context.HttpContext.User.Identity.IsAuthenticated is false everytimes, even if the previous action set principal
ORIGINAL:
I'using custom attribute to manage this scenario in this way:
public class MyAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter{
public string[] Roles { get; set; }
public void OnAuthentication(AuthenticationContext filterContext)
{
string MyHeaderToken = “SM_USER”;
string userSSO = null;
if (HttpContext.Current.Request.Headers[MyHeaderToken] != null)
{
userSSO = HttpContext.Current.Request.Headers[MyHeaderToken];
Trace.WriteLine(string.Format(“got MyToken: {0}”, userSSO));
}
if (string.IsNullOrWhiteSpace(userSSO))
{
Trace.WriteLine(“access denied, no token found”);
}
else
{
// Create GenericPrincipal
GenericIdentity webIdentity = new GenericIdentity(userSSO, “My”);
string[] methods= GetMethods(userSSO);
GenericPrincipal principal = new GenericPrincipal(webIdentity, methods);
filterContext.HttpContext.User = principal;
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
//check authorizations
}
}
but external webservice returns list of controller/action authorized for users, so i have to test all actions executions to simply check if names is contained in the list.
is there a way to do this without have to write attribute on every actions or every controllers in this way:
[MyAuthentication(Roles = “Admin”)]
pubic class AdminController: Controller
{
}
i know i can use
services.AddMvc(o =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
o.Filters.Add(new AuthorizeFilter(policy));
});
but no idea of how to use this with my custom authorization
i'am also not sure if string[] methods= GetMethods(userSSO) is cached by .net core filterContext.HttpContext.User avoiding multiple calls to external webservice.
Thanks

If you want to apply your custom IAuthenticationFilter globally then you can do the ff:
services.AddControllers(options =>
{
options.Filters.Add(new MyAuthenticationFilter());
});
With this approach, you no longer need to inherit from ActionFilterAttribute and no need to add the [MyAuthentication(Roles = “Admin”)] attributes.
Just ensure that you are allowing anonymous requests to actions that doesn't need authentication and/or authorization.
EDIT 2:
For your updated setup, make sure you do the ff:
Add cookie authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie();
Order of middlewares
app.UseRouting();
app.UseAuthentication();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseAuthorization();
EDIT 1:
i'am also not sure if string[] methods= GetMethods(userSSO) is cached by .net core filterContext.HttpContext.User avoiding multiple calls to external webservice.
The lifetime of the filter depends on how you implemented it, usually it is singleton but you can make it transient by following the approach below:
public class MyAuthorizationFilter : IAuthorizationFilter, IOrderedFilter
{
public int Order => -1; // Ensures that it runs first before basic Authorize filter
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
if (context.HttpContext.Session.IsAvailable
&& context.HttpContext.Session.TryGetValue("_SessionUser", out byte[] _user))
{
SessionUser su = (SessionUser)this.ByteArrayToObject(_user);
GenericPrincipal principal = this.CreateGenericPrincipal(su.IdentityName, su.Type, su.Roles);
context.HttpContext.User = principal;
}
else
{
const string MyHeaderToken = "HTTP_KEY";
string userSSO = null;
if (!string.IsNullOrWhiteSpace(context.HttpContext.Request.Headers[MyHeaderToken]))
{
userSSO = context.HttpContext.Request.Headers[MyHeaderToken];
}
userSSO = "TestUser";
if (string.IsNullOrWhiteSpace(userSSO))
{
//filterContext.Result = new unh();
}
else
{
string identityType = "My";
string[] methods = new string[0]; // GetMethods(userSSO);
// Create GenericPrincipal
GenericPrincipal principal = this.CreateGenericPrincipal(userSSO, identityType, methods);
context.HttpContext.User = principal;
if (context.HttpContext.Session.IsAvailable)
{
SessionUser su = new SessionUser()
{
IdentityName = principal.Identity.Name,
Type = principal.Identity.AuthenticationType,
Roles = methods
};
byte[] _sessionUser = this.ObjectToByteArray(su);
context.HttpContext.Session.Set("_SessionUser", _sessionUser);
}
}
}
}
}
private GenericPrincipal CreateGenericPrincipal(string name, string type, string[] roles)
{
GenericIdentity webIdentity = new GenericIdentity(name, type);
GenericPrincipal principal = new GenericPrincipal(webIdentity, roles);
return principal;
}
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return obj;
}
}
[Serializable]
private class SessionUser
{
public string IdentityName { get; set; }
public string Type { get; set; }
public string[] Roles { get; set; }
}
}
public class MyAuthorizationAttribute : TypeFilterAttribute
{
public MyAuthorizationAttribute()
: base(typeof(MyAuthorizationFilter))
{
}
}
On Startup.cs > Configure call app.UseSession(); immediately after app.UseRouting() so that session will be available during authorization.
The code above will set the current HTTP Context's user and save it on session. Subsequent requests will attempt to use the user stored on the session. This will also make the DI container manage the lifetime of the filter. Read more about it in Filters in ASP.NET Core.
I do not recommend you follow this approach. Please do either cookie or token-based authentication by taking advantage of the authentication middleware in .NET Core.
Once the request reaches the action execution, context.HttpContext.User.Identity.IsAuthenticated will now be true.

Related

Blazor server authentication JWT for SignalR everything but web applications

I hope someone could clear up a couple of concepts for me.
I use WinForms and Blazor Server and I desire to send a message to a user.
For that purpose, I've decided to try JWT authentication.
I would also prefer the Blazor server have this JWT authentication built in as per documentation
Blazor server:
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
// Add services to the container.
services.AddCors(option => option.AddPolicy("CorsPolicy", p => p.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod().AllowCredentials()));
//services.AddScoped<AuthenticationStateProvider, MyAuthenticationStateProvider>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters() //Guessing this section is for security of the token - ensures that I'm the one that made it and such.
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateLifetime = false,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("test")),
ValidIssuer = "test",
ValidAudience = "test"
};
options.Events = new()
{
OnMessageReceived = (context) =>
{
var path = context.HttpContext.Request.Path;
if (path.StartsWithSegments("/hubs")) // || path.StartsWithSegments("/token")
{
var accessToken = string.IsNullOrWhiteSpace(context.Request.Query["access_token"]) ? context.Request.Headers["Authorization"] : context.Request.Query["access_token"];
if (!string.IsNullOrWhiteSpace(accessToken))
{
//Real
context.Token = accessToken; //another guess - this is adding the accesstoken to the httpContext so it can be used somewhere else probably.
//Test attach claims to context. I want to be able to do this somewhere else though.
var claims = new Claim[]
{
new(ClaimTypes.Name, "myUserName"),
};
var identity = new ClaimsIdentity(claims);
context.Principal = new(identity);
context.Success();
}
}
return Task.CompletedTask;
},
OnAuthenticationFailed = (context) =>
{
Debug.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
return Task.CompletedTask;
}
};
});
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSignalR()
.AddHubOptions<ChatHub>(options => options.EnableDetailedErrors = true);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapBlazorHub();
app.MapHub<ChatHub>("/hubs/chathub");
app.MapFallbackToPage("/_Host");
Hub:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] //Same as: [Authorize(AuthenticationSchemes = "Bearer")]
public class ChatHub : Hub
{
public Task SendMessageAsync(string user, string message)
{
Debug.WriteLine(Context.UserIdentifier); //null
bool test1 = Context.User.Identity.IsAuthenticated; //false
string test2 = Context?.User?.Identity?.Name; //myUserName
return Clients.User(Context?.User?.Identity?.Name).SendAsync("ReceiveMessage", user, message); //This does then not work ofc.
}
}
Client:
HubConnection connection;
string url = "https://localhost:7041/hubs/chathub";
string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
public Form1()
{
InitializeComponent();
connection = new HubConnectionBuilder()
.WithUrl(url, options =>
{
options.AccessTokenProvider = () => Task.FromResult(token);
})
.WithAutomaticReconnect()
.Build();
}
private async void HubConnectBtn_Click(object sender, EventArgs e)
{
connection.On<string, string>("ReceiveMessage", (user, message) =>
{
this.Invoke(() =>
{
var newMessage = $"{user}: {message}";
MessagesLB.Items.Add(newMessage);
});
});
try
{
await connection.StartAsync();
MessagesLB.Items.Add("Connected!");
}
catch(Exception ex)
{
MessagesLB.Items.Add(ex.Message);
}
}
What I do not understand:
When connecting the Client, how do I pass username and password from the winform to the Blazor server, and how to I get access to the middleware authentication and return a JTW back to the client connection. Do I need to make an API on the Blazor Server, do a call and generate a JWT which I pass here: options.AccessTokenProvider = () => Task.FromResult(token); or is there a more logical way?
I've looked into the AuthenticationStateProvider, but couldn't produce the results I wanted.
Is JWT authentication even intended for this, or is there a better alternative?
I'm using an already existing database filled with users that I'm going to access when this server is looking up if the username and password is correct. Meaning I want a "userService" or something like that which contains all users. For now it's fine to mock users, but I need to know where I can do this and swap it out with a DBconnection/context later on.
Any help would be most appreciated!
EDIT:
After some time I found a approach that did work as I wanted it. By using a custom Authentication scheme I could add a token containing user data from and to user/group which means I have complete control over the communication flow. A great benefit of this is that you never need to have a user database to check the authenticity of the user it self, I solved this by having baked into the token a salt/token value that only me and whom ever other person would integrate with the signalR relay server knows about. The Token then contains licensenumber, department no, user info etc to make it unique when registering.
SERVER SIDE:
public class MyAuthenticationHandler : AuthenticationHandler<MyCustomAuthenticationSchemeOptions>
{
public MyAuthenticationHandler(IOptionsMonitor<MyCustomAuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
TokenModel tokenModel;
if (!Request.Headers.ContainsKey(HeaderNames.Authorization))
{
return Task.FromResult(AuthenticateResult.Fail("Header Not Found."));
}
AuthenticationHeaderValue auth;
if (!AuthenticationHeaderValue.TryParse(Request.Headers.Authorization, out auth))
{
return Task.FromResult(AuthenticateResult.Fail("No authentication header"));
}
if (!auth.Scheme.Equals("Bearer"))
{
return Task.FromResult(AuthenticateResult.Fail("Authentication Scheme was not Bearer"));
}
//var header = Request.Headers[HeaderNames.Authorization].ToString();
//var tokenMatch = Regex.Match(header, MyAuthenticationSchemeConstants.MyToken);
if (!string.IsNullOrWhiteSpace(auth.Parameter))
{
//string[] token = header.Split(" ");
try
{
string parsedToken = Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter));
tokenModel = JsonConvert.DeserializeObject<TokenModel>(parsedToken);
}
catch(Exception ex)
{
Debug.WriteLine("Exception Occured while Deserializing: " + ex);
return Task.FromResult(AuthenticateResult.Fail("TokenParseException"));
}
if(tokenModel != null)
{
List<Claim> claims = new()
{
new Claim(ClaimTypes.Name, tokenModel.Name),
new Claim("Group", tokenModel?.GroupName)
};
if (tokenModel.UserId > 0)
{
claims.Add(new Claim(ClaimTypes.NameIdentifier, tokenModel.UserId.ToString()));
}
var claimsIdentity = new ClaimsIdentity(claims,
nameof(MyAuthenticationHandler));
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(claimsIdentity), this.Scheme.Name);
// pass on the ticket to the middleware
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
return Task.FromResult(AuthenticateResult.Fail("Model is Empty"));
}
}
public class MyCustomAuthenticationSchemeOptions : AuthenticationSchemeOptions
{
}
I also use a UserSerivice (though not necessary) to relay some information like "user not connected", a work in progress. Just a addUser, getID, removeUser from a list of usermodel. This enables me to have the hub like this:
public class ChatHub : Hub
{
IUserService _userService;
public ChatHub(IUserService userService)
{
_userService = userService;
}
public async Task SendMessageAsync(int user, string message)
{
Debug.WriteLine(Context.UserIdentifier); //userID -> Claim.UserIdentifier
bool test1 = Context.User.Identity.IsAuthenticated; //true
string test2 = Context?.User?.Identity?.Name; //myUserName -> Claim.Name
if (_userService.GetById(user) == false)
await Clients.User(Context.UserIdentifier).SendAsync("ReceiveMessage", Context?.User?.Identity?.Name, $"user is not connected");
await Clients.User(user.ToString()).SendAsync("ReceiveMessage", Context?.User?.Identity?.Name, message);
}
public async Task SendMessageToGroupAsync(string groupname, string message)
{
await Clients.OthersInGroup(groupname).SendAsync("ReceiveMessage", groupname, message);
}
public async override Task OnConnectedAsync()
{
//TODO Register Context.UserIdentifier -
int conID = 0;
if(int.TryParse(Context.UserIdentifier, out conID) == true)
{
_userService.AddUser(conID, Context.ConnectionId);
}
await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Claims.First(c => c.Type == "Group").Value);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
int conID = 0;
if (int.TryParse(Context.ConnectionId, out conID) == true)
{
_userService.RemoveUser(conID, Context.ConnectionId); //TODO Should probably be async calls to service.
}
await base.OnDisconnectedAsync(exception); //According to https://github.com/dotnet/aspnetcore/issues/19043 users are removed from all groups by disconnecting. Test/resolve this.
}
}
Then in the program.cs you just add it like usual (the MyAuthenticationSchemeConstants are just the name and a random token value I've chosen for now) :
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
// Add services to the container.
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddAuthentication(options => options.DefaultAuthenticateScheme = MyAuthenticationSchemeConstants.MyAuthenticationSchemeName)
.AddScheme<MyCustomAuthenticationSchemeOptions, MyAuthenticationHandler>( MyAuthenticationSchemeConstants.MyAuthenticationSchemeName, options => { });
UserService _userService = new();
.
.
.
app.UseAuthentication();
app.UseAuthorization();
app.MapBlazorHub();
app.MapHub<ChatHub>("/hubs/chathub");
Client-Side example:
Just a winform with a couple of text fields and buttons using localhost for example purposes, but just swap out the url for a central hub url.
string url = "https://localhost:7185/hubs/chathub";
string token = "";
public Form1()
{
InitializeComponent();
SendBtn.Enabled = false;
//client = new(baseAddress);
}
private void BuildToken()
{
TokenModel tokenModel = new()
{
UserId = Int32.Parse(UserIDTB.Text),
Name = UsernameTB.Text,
GroupName = "Waiter",
EmailAddress = "someEmail#mydomain.com"
};
token = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(tokenModel)));
}
private async void HubConnectBtn_Click(object sender, EventArgs e)
{
BuildToken();
connection = new HubConnectionBuilder()
.WithUrl(url, options =>
{
options.AccessTokenProvider = () => Task.FromResult(token);
})
.WithAutomaticReconnect()
.Build();
connection.On<string, string>("ReceiveMessage", (user, message) =>
{
this.Invoke(() =>
{
var newMessage = $"{user}: {message}";
MessagesLB.Items.Add(newMessage);
});
});
try
{
await connection.StartAsync();
SendBtn.Enabled = true;
HubConnectBtn.Enabled = false;
MessagesLB.Items.Add("Connected!");
}
catch (Exception ex)
{
MessagesLB.Items.Add(ex.Message);
}
}
private async void SendBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(RecieverTB.Text))
{
MessagesLB.Items.Add("Write a recipient");
return;
}
if (string.IsNullOrWhiteSpace(MessageTB.Text))
{
MessagesLB.Items.Add("Write a message");
return;
}
try
{
await connection.InvokeAsync("SendMessageAsync", Int32.Parse(RecieverTB.Text), MessageTB.Text);
}
catch (Exception ex)
{
MessagesLB.Items.Add(ex.Message);
}
}
I hope this can help someone else!
Side note - if anyone has an input on how I can pass the Task.FromResult text to my clients that would be great!
I use signalr and jwt and my startup is a little different:
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWT: ValidAudience"],
ValidIssuer = Configuration["JWT: ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT: SecretKey"]))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/api/hubs/")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
As you see you just have to set context.Token. But the token that signalr sends is obtained from the api through the authentication process. As you said, you authenticate sending a post request to a route on your api which could be something like this:
[HttpPost("authenticate")]
public async Task<ActionResult<AuthenticateResponse>> Post([FromBody]
AuthenticateRequest request)
{
AuthenticateResponse response = new AuthenticateResponse();
var result = await signInManager.PasswordSignInAsync(request.User,
request.Password, true, false);
if (result.Succeeded)
{
var user = await userManager.FindByNameAsync(request.User);
string[] roles = (await userManager.GetRolesAsync(user)).ToArray();
response.UserId = user.Id;
response.UserName = user.UserName;
response.Roles = roles;
response.Token = Helpers.TokenService.CreateToken(user, roles,
configuration);
}
else response.Error = "Authentication Error";
return Ok(response);
}
Here is the TokenService:
public static class TokenService
{
private const double EXPIRE_HOURS = 10;
public static string CreateToken(ApplicationUser user, string[] roles,
IConfiguration configuration)
{
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
foreach (var userRole in roles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
}
var authSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:
SecretKey"]));
var token = new JwtSecurityToken(
issuer: configuration["JWT: ValidIssuer"],
audience: configuration["JWT: ValidAudience"],
expires: DateTime.Now.AddHours(EXPIRE_HOURS),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey,
SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
And you have to derive your ApplicationdbContext from IdentityDbContext

GetRouteData always null using AspNetCore.OData 7.2.1

I am trying to secure an OData api using .net Core 2.2 and AspNetCore.OData 7.2.1, with a basic authentication handler.
I need to handler multi tenant urls, and retrieve from the uri the token that will then be used in the authorization handler to determine if a user is authorized.
To do so I use the IHttpContextAccessor but this works only with standard api, and not with OData.
OData does not like EndpointRouting and I had to disable it as shown below, but in this case then how can I access the RouteData to take the tenant token?
Is there an alternative approach? Below the code you can use to try this out.
Startup.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
services.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOData();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Needed to be able to get RouteData from HttpContext through the IHttpContextAccessor
app.UseEndpointRouting();
// Needed to secure the application using the standard Authorize attribute
app.UseAuthentication();
// OData entity model builder
var builder = new ODataConventionModelBuilder(app.ApplicationServices);
builder.EntitySet<Value>(nameof(Value) + "s");
app.UseMvc();
app.UseOData("odata", "{tenant}/odata", builder.GetEdmModel());
// Alternative configuration which is affected by the same problem
//
// app.UseMvc(routeBuilder =>
// {
// // Map OData routing adding token for the tenant based url
// routeBuilder.MapODataServiceRoute("odata", "{tenant}/odata", builder.GetEdmModel());
//
// // Needed to allow the injection of OData classes
// routeBuilder.EnableDependencyInjection();
// });
}
BasicAuthenticationHandler.cs
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public BasicAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IHttpContextAccessor httpContextAccessor)
: base(options, logger, encoder, clock)
{
_httpContextAccessor = httpContextAccessor;
}
public string GetTenant()
{
var httpContext = _httpContextAccessor?.HttpContext;
var routeData = httpContext?.GetRouteData(); // THIS RESULTS ALWAYS IN NULL ROUTE DATA!
return routeData?.Values["tenant"]?.ToString();
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("Missing Authorization Header");
try {
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':');
var username = credentials[0];
var password = credentials[1];
var tenant = GetTenant();
if (string.IsNullOrEmpty(tenant))
{
return AuthenticateResult.Fail("Unknown tenant");
}
if(string.IsNullOrEmpty(username) || username != password)
return AuthenticateResult.Fail("Wrong username or password");
}
catch (Exception e)
{
return AuthenticateResult.Fail("Unable to authenticate");
}
var claims = new[] {
new Claim("Tenant", "tenant id")
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
Response.Headers["WWW-Authenticate"] = "Basic realm=\"Oh my OData\", charset=\"UTF-8\"";
await base.HandleChallengeAsync(properties);
}
}
Value.cs
public class Value
{
public int Id { get; set; }
public string Name { get; set; }
}
ValuesController.cs
[Authorize]
public class ValuesController : ODataController
{
private List<Value> _values;
public ValuesController()
{
_values = new List<Value>
{
new Value {Id = 1, Name = "A1"},
new Value {Id = 2, Name = "A2"},
new Value {Id = 3, Name = "A3"},
new Value {Id = 4, Name = "A4"},
new Value {Id = 5, Name = "A5"},
new Value {Id = 6, Name = "A6"},
new Value {Id = 7, Name = "A7"},
new Value {Id = 11, Name = "B1"},
new Value {Id = 12, Name = "B2"},
new Value {Id = 13, Name = "B3"},
new Value {Id = 14, Name = "B4"},
new Value {Id = 15, Name = "B5"},
new Value {Id = 16, Name = "B6"},
new Value {Id = 17, Name = "B7"}
};
}
// GET {tenant}/odata/values
[EnableQuery]
public IQueryable<Value> Get()
{
return _values.AsQueryable();
}
// GET {tenant}/odata/values/5
[EnableQuery]
public ActionResult<Value> Get([FromODataUri] int key)
{
if(_values.Any(v => v.Id == key))
return _values.Single(v => v.Id == key);
return NotFound();
}
}
EDIT:
Added sample code in working application to reproduce the issue and test solutions: https://github.com/norcino/so-58016881-OData-GetRoute
OData does not like EndpointRouting and I had to disable it as shown below, but in this case then how can I access the RouteData to take the tenant token?
As you know, OData doesn't work fine with ASP.NET Core 2.2 EndPoint Routing. For more details at present, see https://github.com/OData/WebApi/issues/1707
var routeData = httpContext?.GetRouteData(); // THIS RESULTS ALWAYS IN NULL ROUTE DATA!
The reason why you always get a null route data is that the Authentication middleware runs before the Router middleware takes effect. In other words, you won't get route data before the Router middleware is invoked.
To walk around it, just create a router and make it runs before the Authentication middleware.
How to fix
Make sure you've disabled the EnableEndpointRouting:
services.AddMvc(
options => options.EnableEndpointRouting = false
)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Remove the line of app.UseEndpointRouting():
// OData doesn't work fine with ASP.NET Core 2.2 EndPoint Routing, See https://github.com/OData/WebApi/issues/1707
// app.UseEndpointRouting();
Set up a Router before Authentication so that you can get the Route Data within AuthenticationHandler later:
// configure Routes for OData
app.UseRouter(routeBuilder =>{
var templatePrefix="{tenant}/odata";
var template = templatePrefix + "/{*any}";
routeBuilder.MapMiddlewareRoute(template, appBuilder =>{
var builder = new ODataConventionModelBuilder(app.ApplicationServices);
builder.EntitySet<Value>(nameof(Value) + "s");
appBuilder.UseAuthentication();
appBuilder.UseMvc();
appBuilder.UseOData("odata", templatePrefix, builder.GetEdmModel());
});
});
// ... add more middlewares if you want other MVC routes
app.UseAuthentication();
app.UseMvc(rb => {
rb.MapRoute("default","{controller=Home}/{action=Index}/{id?}");
});
Demo
Send a request to the Values API
GET https://localhost:5001/msft/odata/values
Authorization: Basic dGVzdDp0ZXN0
And then we'll get the route data as below:

Building an integration test for an AspNetCore API that uses IdentityServer 4 for Auth

I've built a simple AspNetCore 2.2 API that uses IdentityServer 4 to handle OAuth. It's working fine but I'd now like to add integration tests and recently discovered this. I used it to build some tests which all worked fine - as long as I didn't have the [Authorize] attribute on my controllers - but obviously that attribute needs to be there.
I came across this stackoverflow question and from the answers given there I tried to put a test together but I'm still getting an Unauthorized response when I try to run tests.
Please note: I really don't know what details I should be using when I'm creating the client.
What should the allowed scopes be? (Should they match the real
scopes)
Also when building the IdentityServerWebHostBuilder
What should I pass to .AddApiResources? (Maybe a dumb question but
does it matter)
If anyone can guide me it would be greatly appreciated.
Here is my test:
[Fact]
public async Task Attempt_To_Test_InMemory_IdentityServer()
{
// Create a client
var clientConfiguration = new ClientConfiguration("MyClient", "MySecret");
var client = new Client
{
ClientId = clientConfiguration.Id,
ClientSecrets = new List<Secret>
{
new Secret(clientConfiguration.Secret.Sha256())
},
AllowedScopes = new[] { "api1" },
AllowedGrantTypes = new[] { GrantType.ClientCredentials },
AccessTokenType = AccessTokenType.Jwt,
AllowOfflineAccess = true
};
var webHostBuilder = new IdentityServerWebHostBuilder()
.AddClients(client)
.AddApiResources(new ApiResource("api1", "api1name"))
.CreateWebHostBuilder();
var identityServerProxy = new IdentityServerProxy(webHostBuilder);
var tokenResponse = await identityServerProxy.GetClientAccessTokenAsync(clientConfiguration, "api1");
// *****
// Note: creating an IdentityServerProxy above in order to get an access token
// causes the next line to throw an exception stating: WebHostBuilder allows creation only of a single instance of WebHost
// *****
// Create an auth server from the IdentityServerWebHostBuilder
HttpMessageHandler handler;
try
{
var fakeAuthServer = new TestServer(webHostBuilder);
handler = fakeAuthServer.CreateHandler();
}
catch (Exception e)
{
throw;
}
// Create an auth server from the IdentityServerWebHostBuilder
HttpMessageHandler handler;
try
{
var fakeAuthServer = new TestServer(webHostBuilder);
handler = fakeAuthServer.CreateHandler();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
// Set the BackChannelHandler of the 'production' IdentityServer to use the
// handler form the fakeAuthServer
Startup.BackChannelHandler = handler;
// Create the apiServer
var apiServer = new TestServer(new WebHostBuilder().UseStartup<Startup>());
var apiClient = apiServer.CreateClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
var user = new User
{
Username = "simonlomax#ekm.com",
Password = "Password-123"
};
var req = new HttpRequestMessage(new HttpMethod("GET"), "/api/users/login")
{
Content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"),
};
// Act
var response = await apiClient.SendAsync(req);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
My Startup class:
public class Startup
{
public IConfiguration Configuration { get; }
public static HttpMessageHandler BackChannelHandler { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
ConfigureAuth(services);
services.AddTransient<IPassportService, PassportService>();
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
}
protected virtual void ConfigureAuth(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = Configuration.GetValue<string>("IdentityServerAuthority");
options.Audience = Configuration.GetValue<string>("IdentityServerAudience");
options.BackchannelHttpHandler = BackChannelHandler;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
app.UseExceptionMiddleware();
}
}
Edit:
The below suggestion was one problem. The original source-code failed due to an exception by trying to build WebHostBuilder twice. Secondly the configuration-file was only present in the API project, not in the test-project, thats why authority wasn't set as well.
Instead of doing this
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = Configuration.GetValue<string>("IdentityServerAuthority");
options.Audience = Configuration.GetValue<string>("IdentityServerAudience");
options.BackchannelHttpHandler = BackChannelHandler;
});
You have to do something like this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = Configuration.GetValue<string>("IdentityServerAuthority");
options.JwtBackChannelHandler = BackChannelHandler;
});
You can find a sample here.
Hope that helps, worked for me!
A solution which doesn't affect production code:
public class TestApiWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup : class
{
private readonly HttpClient _identityServerClient;
public TestApiWebApplicationFactory(HttpClient identityServerClient)
{
_identityServerClient = identityServerClient;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureServices(
s =>
{
s.AddSingleton<IConfigureOptions<JwtBearerOptions>>(services =>
{
return new TestJwtBearerOptions(_identityServerClient);
});
});
}
}
and its usage is:
_factory = new WebApplicationFactory<Startup>()
{
ClientOptions = {BaseAddress = new Uri("http://localhost:5000/")}
};
_apiFactory = new TestApiWebApplicationFactory<SampleApi.Startup>(_factory.CreateClient())
{
ClientOptions = {BaseAddress = new Uri("http://localhost:5001/")}
};
The TestJwtBearerOptions just proxies requests to identityServerClient. The implementation you can find here:
https://gist.github.com/ru-sh/048e155d73263912297f1de1539a2687
If you don't want to rely on a static variable to hold the HttpHandler, I've found the following to work. I think it's a lot cleaner.
First create an object that you can instantiate before your TestHost is created. This is because you won't have the HttpHandler until after the TestHost is created, so you need to use a wrapper.
public class TestHttpMessageHandler : DelegatingHandler
{
private ILogger _logger;
public TestHttpMessageHandler(ILogger logger)
{
_logger = logger;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
_logger.Information($"Sending HTTP message using TestHttpMessageHandler. Uri: '{request.RequestUri.ToString()}'");
if (WrappedMessageHandler == null) throw new Exception("You must set WrappedMessageHandler before TestHttpMessageHandler can be used.");
var method = typeof(HttpMessageHandler).GetMethod("SendAsync", BindingFlags.Instance | BindingFlags.NonPublic);
var result = method.Invoke(this.WrappedMessageHandler, new object[] { request, cancellationToken });
return await (Task<HttpResponseMessage>)result;
}
public HttpMessageHandler WrappedMessageHandler { get; set; }
}
Then
var testMessageHandler = new TestHttpMessageHandler(logger);
var webHostBuilder = new WebHostBuilder()
...
services.PostConfigureAll<JwtBearerOptions>(options =>
{
options.Audience = "http://localhost";
options.Authority = "http://localhost";
options.BackchannelHttpHandler = testMessageHandler;
});
...
var server = new TestServer(webHostBuilder);
var innerHttpMessageHandler = server.CreateHandler();
testMessageHandler.WrappedMessageHandler = innerHttpMessageHandler;

How to authenticate facebook web api in asp.net core 2

I'm currently building my very first mobile app in Xamarin.Forms. The app has a facebook login and after the user has been logged in I'm storing the facebook token because I want to use it as a bearer-token to authenticate any further requests against an API.
The API is a .NET core 2.0 project and I am struggling to get the authentication working.
In my Xamarin.Forms app the facebook token is set as bearer-token with the following code;
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", UserToken);
As far as I know, this properly sets the bearer token in the headers of the request.
I've talked to a colleague of mine about this and he told me to take a look at Identityserver4 which should support this. But for now, I've decided not to do that since for me, at this moment, it is overhead to implement this. So I've decided to stay with the idea to use the facebook token as bearer token and validate this.
So the next step for me is to find a way to authenticate the incoming bearer token with Facebook to check if it is (still) valid.
So I've configured the startup for my API projects as following;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddFacebook(o =>
{
o.AppId = "MyAppId";
o.AppSecret = "MyAppSecret";
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//Enable authentication
app.UseAuthentication();
//Enable support for default files (eg. default.htm, default.html, index.htm, index.html)
app.UseDefaultFiles();
//Configure support for static files
app.UseStaticFiles();
app.UseMvc();
}
}
But when I'm using postman to do a request and test if everything is working I'm receiving the following error;
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
What am I doing wrong here?
EDIT:
In the mean time if been busy trying to find a solution for this. After reading a lot on Google it seems thatadding an AuthorizationHandler is the way to go at the moment. From there on I can make request to facebook to check if the token is valid. I've added the following code to my ConfigureServices method;
public void ConfigureServices(IServiceCollection services)
{
//Other code
services.AddAuthorization(options =>
{
options.AddPolicy("FacebookAuthentication", policy => policy.Requirements.Add(new FacebookRequirement()));
});
services.AddMvc();
}
And I've created a FacebookRequirement which will help me handling the policy;
public class FacebookRequirement : AuthorizationHandler<FacebookRequirement>, IAuthorizationRequirement
{
private readonly IHttpContextAccessor contextAccessor;
public FacebookRequirement(IHttpContextAccessor contextAccessor)
{
this.contextAccessor = contextAccessor;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, FacebookRequirement requirement)
{
//var socialConfig = new SocialConfig{Facebook = new SocialApp{AppId = "MyAppId", AppSecret = "MyAppSecret" } };
//var socialservice = new SocialAuthService(socialConfig);
//var result = await socialservice.VerifyFacebookTokenAsync()
var httpContext = contextAccessor.HttpContext;
if (httpContext != null && httpContext.Request.Headers.ContainsKey("Authorization"))
{
var token = httpContext.Request.Headers.Where(x => x.Key == "Authorization").ToList();
}
context.Succeed(requirement);
return Task.FromResult(0);
}
}
The problem I'm running into now is that I don't know where to get the IHttpContextAccessor. Is this being injected somehow? Am I even on the right path to solve this issue?
I ended up creating my own AuthorizationHandler to validate incoming requests against facebook using bearer tokens. In the future I'll probably start using Identityserver to handle multiple login types. But for now facebook is sufficient.
Below is the solution for future references.
First create an FacebookRequirement class inheriting from AuthorizationHandler;
public class FacebookRequirement : AuthorizationHandler<FacebookRequirement>, IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, FacebookRequirement requirement)
{
var socialConfig = new SocialConfig { Facebook = new SocialApp { AppId = "<FacebookAppId>", AppSecret = "<FacebookAppSecret>" } };
var socialservice = new SocialAuthService(socialConfig);
var authorizationFilterContext = context.Resource as AuthorizationFilterContext;
if (authorizationFilterContext == null)
{
context.Fail();
return Task.FromResult(0);
}
var httpContext = authorizationFilterContext.HttpContext;
if (httpContext != null && httpContext.Request.Headers.ContainsKey("Authorization"))
{
var authorizationHeaders = httpContext.Request.Headers.Where(x => x.Key == "Authorization").ToList();
var token = authorizationHeaders.FirstOrDefault(header => header.Key == "Authorization").Value.ToString().Split(' ')[1];
var user = socialservice.VerifyTokenAsync(new ExternalToken { Provider = "Facebook", Token = token }).Result;
if (!user.IsVerified)
{
context.Fail();
return Task.FromResult(0);
}
context.Succeed(requirement);
return Task.FromResult(0);
}
context.Fail();
return Task.FromResult(0);
}
}
Add the following classes which will contain the configuration an represent the user;
public class SocialConfig
{
public SocialApp Facebook { get; set; }
}
public class SocialApp
{
public string AppId { get; set; }
public string AppSecret { get; set; }
}
public class User
{
public Guid Id { get; set; }
public string SocialUserId { get; set; }
public string Email { get; set; }
public bool IsVerified { get; set; }
public string Name { get; set; }
public User()
{
IsVerified = false;
}
}
public class ExternalToken
{
public string Provider { get; set; }
public string Token { get; set; }
}
And last but not least, the SocialAuthService class which will handle the requests with facebook;
public class SocialAuthService
{
private SocialConfig SocialConfig { get; set; }
public SocialAuthService(SocialConfig socialConfig)
{
SocialConfig = socialConfig;
}
public async Task<User> VerifyTokenAsync(ExternalToken exteralToken)
{
switch (exteralToken.Provider)
{
case "Facebook":
return await VerifyFacebookTokenAsync(exteralToken.Token);
default:
return null;
}
}
private async Task<User> VerifyFacebookTokenAsync(string token)
{
var user = new User();
var client = new HttpClient();
var verifyTokenEndPoint = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name", token);
var verifyAppEndpoint = string.Format("https://graph.facebook.com/app?access_token={0}", token);
var uri = new Uri(verifyTokenEndPoint);
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
dynamic userObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content);
uri = new Uri(verifyAppEndpoint);
response = await client.GetAsync(uri);
content = await response.Content.ReadAsStringAsync();
dynamic appObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content);
if (appObj["id"] == SocialConfig.Facebook.AppId)
{
//token is from our App
user.SocialUserId = userObj["id"];
user.Email = userObj["email"];
user.Name = userObj["name"];
user.IsVerified = true;
}
return user;
}
return user;
}
}
This will validate the Facebook token coming from the request as bearer token, with Facebook to check if it's still valid.

ASP.NET Core Web API Authentication

I'm struggling with how to set up authentication in my web service.
The service is build with the ASP.NET Core web api.
All my clients (WPF applications) should use the same credentials to call the web service operations.
After some research, I came up with basic authentication - sending a username and password in the header of the HTTP request.
But after hours of research, it seems to me that basic authentication is not the way to go in ASP.NET Core.
Most of the resources I found are implementing authentication using OAuth or some other middleware. But that seems to be oversized for my scenario, as well as using the Identity part of ASP.NET Core.
So what is the right way to achieve my goal - simple authentication with username and password in a ASP.NET Core web service?
Now, after I was pointed in the right direction, here's my complete solution:
This is the middleware class which is executed on every incoming request and checks if the request has the correct credentials. If no credentials are present or if they are wrong, the service responds with a 401 Unauthorized error immediately.
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
string authHeader = context.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
if(username == "test" && password == "test" )
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
}
The middleware extension needs to be called in the Configure method of the service Startup class
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMvc();
}
And that's all! :)
A very good resource for middleware in .Net Core and authentication can be found here:
https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/
You can implement a middleware which handles Basic authentication.
public async Task Invoke(HttpContext context)
{
var authHeader = context.Request.Headers.Get("Authorization");
if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
var token = authHeader.Substring("Basic ".Length).Trim();
System.Console.WriteLine(token);
var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
var credentials = credentialstring.Split(':');
if(credentials[0] == "admin" && credentials[1] == "admin")
{
var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, "Basic");
context.User = new ClaimsPrincipal(identity);
}
}
else
{
context.Response.StatusCode = 401;
context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
}
await _next(context);
}
This code is written in a beta version of asp.net core. Hope it helps.
To use this only for specific controllers for example use this:
app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)),
builder =>
{
builder.UseMiddleware<AuthenticationMiddleware>();
});
I think you can go with JWT (Json Web Tokens).
First you need to install the package System.IdentityModel.Tokens.Jwt:
$ dotnet add package System.IdentityModel.Tokens.Jwt
You will need to add a controller for token generation and authentication like this one:
public class TokenController : Controller
{
[Route("/token")]
[HttpPost]
public IActionResult Create(string username, string password)
{
if (IsValidUserAndPasswordCombination(username, password))
return new ObjectResult(GenerateToken(username));
return BadRequest();
}
private bool IsValidUserAndPasswordCombination(string username, string password)
{
return !string.IsNullOrEmpty(username) && username == password;
}
private string GenerateToken(string username)
{
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, username),
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
};
var token = new JwtSecurityToken(
new JwtHeader(new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
SecurityAlgorithms.HmacSha256)),
new JwtPayload(claims));
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
After that update Startup.cs class to look like below:
namespace WebAPISecurity
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", jwtBearerOptions =>
{
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
ValidateIssuer = false,
//ValidIssuer = "The name of the issuer",
ValidateAudience = false,
//ValidAudience = "The name of the audience",
ValidateLifetime = true, //validate the expiration and not before values in the token
ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}
And that's it, what is left now is to put [Authorize] attribute on the Controllers or Actions you want.
Here is a link of a complete straight forward tutorial.
http://www.blinkingcaret.com/2017/09/06/secure-web-api-in-asp-net-core/
I have implemented BasicAuthenticationHandler for basic authentication so you can use it with standart attributes Authorize and AllowAnonymous.
public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authHeader = (string)this.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':', StringComparison.OrdinalIgnoreCase);
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
//you also can use this.Context.Authentication here
if (username == "test" && password == "test")
{
var user = new GenericPrincipal(new GenericIdentity("User"), null);
var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
else
{
return Task.FromResult(AuthenticateResult.Fail("No valid user."));
}
}
this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
return Task.FromResult(AuthenticateResult.Fail("No credentials."));
}
}
public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
public BasicAuthenticationMiddleware(
RequestDelegate next,
IOptions<BasicAuthenticationOptions> options,
ILoggerFactory loggerFactory,
UrlEncoder encoder)
: base(next, options, loggerFactory, encoder)
{
}
protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
{
return new BasicAuthenticationHandler();
}
}
public class BasicAuthenticationOptions : AuthenticationOptions
{
public BasicAuthenticationOptions()
{
AuthenticationScheme = "Basic";
AutomaticAuthenticate = true;
}
}
Registration at Startup.cs - app.UseMiddleware<BasicAuthenticationMiddleware>();. With this code, you can restrict any controller with standart attribute Autorize:
[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller
and use attribute AllowAnonymous if you apply authorize filter on application level.
As rightly said by previous posts, one of way is to implement a custom basic authentication middleware. I found the best working code with explanation in this blog:
Basic Auth with custom middleware
I referred the same blog but had to do 2 adaptations:
While adding the middleware in startup file -> Configure function, always add custom middleware before adding app.UseMvc().
While reading the username, password from appsettings.json file, add static read only property in Startup file. Then read from appsettings.json. Finally, read the values from anywhere in the project. Example:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public static string UserNameFromAppSettings { get; private set; }
public static string PasswordFromAppSettings { get; private set; }
//set username and password from appsettings.json
UserNameFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("UserName").Value;
PasswordFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("Password").Value;
}
You can use an ActionFilterAttribute
public class BasicAuthAttribute : ActionFilterAttribute
{
public string BasicRealm { get; set; }
protected NetworkCredential Nc { get; set; }
public BasicAuthAttribute(string user,string pass)
{
this.Nc = new NetworkCredential(user,pass);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"].ToString();
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(auth.Substring(6)))
.Split(':');
var user = new {Name = cred[0], Pass = cred[1]};
if (user.Name == Nc.UserName && user.Pass == Nc.Password) return;
}
filterContext.HttpContext.Response.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
filterContext.Result = new UnauthorizedResult();
}
}
and add the attribute to your controller
[BasicAuth("USR", "MyPassword")]
In this public Github repo
https://github.com/boskjoett/BasicAuthWebApi
you can see a simple example of a ASP.NET Core 2.2 web API with endpoints protected by Basic Authentication.
ASP.NET Core 2.0 with Angular
https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login
Make sure to use type of authentication filter
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

Categories

Resources