SignalR with custom Authentication and authorization - c#

The bounty expires in 4 days. Answers to this question are eligible for a +400 reputation bounty.
Arian wants to draw more attention to this question.
I have Three applications.
1)Windows Application
2)Asp.net web form
3)Asp.net MVC
I have a Authentication and Authorization system that implemented using a web service. In simple form the underlying tables are like:
User Table:
Id UserName Password
---------------------------------
Role Table;
Id RoleName
---------------------------------
UserRole
UserId RoleId
---------------------------------
Now I want to implement a chat capability for these apps. My problem is I don't know how to integrate SignalR with my custom authentication. Consider this scenario that a user wants to send a message to another user:
public async Task SendMessage(string user1, string user2, string message)
this method works find in first glance. But how can I prevent this scenario:
if user3 knows user1 username and create a request and send a message from user1 to user2?
Since I can't change my auth service to user Asp.net Identity and integrate it with SignalR How can I be sure that the logged in user send the message and no one can do impersonation?
Could any body help me to get the correct idea and plan?
Thanks

Related

Implementing social login in asp.net core 2.2 with custom db tables without using identity

I am trying to implement social login features in asp.net core 2.2 without using default feature as given here. I couldn't find any where that shows implementation without using default identity.
I have already implemented custom login mechanism to handle user authentication, i.e. there is a user table that stores emailid and its password. When user login it will validate from user table entry. In the same way I want to implement social logins like facebook, twitter, linkedin, microsoft, github etc.
Once user signin using any of these social options there email will be stored in user table with their valid token.
I am able to triggered social login using this article but not able to redirect back to correct action method. Its redirecting back to same action method "IActionResult Google" from where its originated. I couldn't understand "ExternalLoginCallback".
I need to get the response returned by the social login and to retrieve user details.
public IActionResult Google(string provider)
{
provider = "Google";
//Issue a challenge to external login middleware to trigger sign in process
return new ChallengeResult(provider);
}
[AllowAnonymous]
[HttpGet(nameof(ExternalLoginCallback))]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
//Here we can retrieve the claims
var result = await HttpContext.AuthenticateAsync("CookieAuthenticationDefaults.AuthenticationScheme");
return null;
}
The basic idea is your can use AddOAuth or AddOpenIdConnect middleware to trigger the social logins .
For example , if using OAuth 2 flow , you can use AddOAuth extension to make consume the identity provider like facebook , microsoft .... you can acquire access token which could get the current user's basic profile information , in OnCreatingTicket callback function , you can query your local database , link/create the external user in your database , and finally create authentication ticket for user sign-in . For example :
https://www.jerriepelser.com/blog/authenticate-oauth-aspnet-core-2/
That is similar if using OpenID Connect , the difference is you can directly get user's information in ID token :
services.AddAuthentication()
.AddCookie()
.AddOpenIdConnect();
You can click here and here code samples .
You can config multi authentication schema for different providers based on your requirements.

ASP.NET Web API with Bearer authentication. How to get/add/update unique user data?

Currently I am about to develop my first REST web API!
I'm currently designing how the system will work yet I am a little confused how things are going to work.
Primarily, a mobile app will consume the Web API, but it must be secure!
For example I wouldn't want an un-authed request handled at all. (Apart from a user registering)
I have found that I can use SSL + Bearer tokens to achieve this user authentication. I am comfortable with this and have tested to see how this would work. And it's suitable.
The problem arises when I wish to retrieve the user details.
In my system a user would log in to the mobile app which would request the token from the server. If all is good, I can log the user into the app. Great! Now, I need to get the information stored about this user to present to them. i.e. name, email, reward points etc...
I am unfamiliar with how to add extra user data AND retrieve it with the Web API. I understand that the token can be used to uniquly identify a user. but how can I extend this data?
Currently I have not much more than a blank WebAPI project with the bearer token authentication implemented. Still using the Entity framework. How can I add more fields of data to a user record?
Furthermore, how can I update these records? For example, a user has gained some reward points, how can update the user data for this?
One final question, Is this suitable for retaining per user data? i.e. can I link other data to a userID or something similar?
Apologies for sounding over-curious, I am very new to MVC
The below code in the IdentityModel.cs would seem like the appropriate place to add user data, but how do I add to this? for example adding a field for reward points? then how would I update upon it?
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
}
How I would do it:
Create ActionFilter that would validate token, it would use your custom class that would leverage DI, it would obviously get the user ID as well
Now that you know that user is authenticated and you know the user ID just do your regular CRUD based on this user ID
Note: Remember to also validate the payload, since if I send you PUT: /user/887/points {points: 999} I could potentially gain unlimited points.
It's not necessary to use ASP .NET Identity for implementing security in your web API project.
If you use Identity you will have to stick on to "ApplicationUser" and Identity tables for user management where you won't be able to complete your requirement.
A solution is to handle user management with your own custom table and implement security using OWIN middleware classes available for .NET, ie, you need to write code for generating and validating tokens rather than using Identity.

ASP.NET Web API User Activation by Administrator

I have a requirement to prevent users from logging in to my ASP.NET Web API 2.0 Identity 3.0 backed website until an administrative account "activates" a user's confirmed registered ApplicationUser account.
I have implemented the EmailConfirmed logic to validate that the ApplicationUser account was registered with a working email address. Now I'm looking for an appropriate place to implement a check against the ApplicationUser.Activated property, that I have added, with behavior that prevents a login unless it has been set to true.
I've dug a little bit into the OAuthAuthorizationServerProvider class but I think I'm going to have to really take some time and understand OAuth 2.0 to get anywhere in there. Could anyone make a suggestion as to how and where to implement a test against an Activated property like this?
PS - I'm using bearer token authentication if that was not obvious.
Do one thing when user click on activation link which you send to the user .after click on that link redirect to page where you show one message "You are successfully resgistered" and on the page load you call to database and set activate column is true and put timer on that page and redirect user to login page.during login you can check the user status with email and password .if status is true that mean its registered user.
hope it will help.

How to authorize user in WCF service

I have WCF Service where user can add a simple message. Before service put message to database, I need to authorize user, like here:
[OperationContract]
[WebGet(UriTemplate = "/GetMessages/{SessionToken}/{UserPassword}/{UserGLKNumber}")]
Messages GetMessages(string SessionToken, string UserPassword, string UserGLKNumber);
It's obvious that this solution is not good (sending in url user password and number). So, what is other approach?
What is important - I have a client written in Java/PHP/Obj-C (simple, small application) - anyway not in C#.
Write Login method and use ASP.NET auth cookie (forms based authentication), see this. Or use Basic authentication and let client to authenticate by http standard way.
You have to distinguish between Authentication (who is it) and Authorization (what can he do than). For the first you have a variety of options where Windows (the logon credentials of the user) or Basic (username + password) are most straightforward. This is just a manner of configuration on the service side.
On the other hand, authorization can be done on identity (which user is it) or by role (which roles apply to this user). The latter is possible "in code" with if/else constructs but also with attributes on the method [PrincipalPermission(SecurityAction.Demand, Role="Administrator")]. This specifies that you "demand" that the user accessing the method has the "role" administrator (something you specify yourself).
To supply roles to the identity you need some sort of role provider, obviously it is not something the user can provider. Therefore you can use the ASP.NET RoleProvider or a Secure Token Service that stands in between.
You can read more about it here: http://msdn.microsoft.com/en-us/library/ff405740.aspx

How to create users and store them in a database and link them to windows authentication logins

What I want:
An intranet application where only people who are logged in can see the application... and an Admin and Member role.
1:
I have created an MVC 5.0 web application (for intranet).
It has a Home view with a home controller...
I have an Admin view with an admin controller.
The home page has a link (well it's not a link yet but whatever) on it that is conditional:
#if(User.IsInRole("Admin")){
<li>Admin</li> #*Will be link to admin controller action*#
}
I would like to create 1 user with role of "Admin" and allow him/her to then create new users (assigning them to Windows authentication logins) with a username and a new role of either "Admin" or "Member"...
2:
Next, I want to make it so that the users with Admin role can do all of the stuff denoted in my SQL database with the roles that be-fit them.
For example,
John only has read and write access to some of the tables ("Member")
But Jack and Jill have read and write access to all of the tables ("Admin").
John cannot see the Admin link on the Home view, but Jill can.
The Admin controller action is locked down to only allow users with "Admin" as the role, not "Member"...
The Core question (with 1 and 2 in mind):
I realise that there are two sets of authentication here, one for windows authentication for the application itself, and then one for the database, but I have a funny feeling they should be linked in some way. I have read quite a bit of material but am consistently confused with it, coming from a Web Form authentication skill set, It's my first intranet application... bit confused.
What I've done so far:
I have currently got Windows Authentication enabled, and I can successfully use the application and call upon:
#User.Identity.Name
to find out who I am...
Side Notes:
I would like to understand in what context the Authorize parameters are to be used eg.
[Authorize(Roles="Admin")]

Categories

Resources