Regarding Maintenance mode in ASP.NET Core - asp.net

I am working on ASP.NET Core web app with MVC6. I want to implement maintenance mode in my web app such that only certain type of users are allowed to login to web app when it is under maintenance mode. For example all user EXCEPT user with role user are allowed to login. To achieve this functionality I tried following code.
//Sign in user with provided username and password
var res = await _signInManager.PasswordSignInAsync(suser.UserName, user.Password, user.Remember, false);
if (res.Succeeded)
{
//check if web app is under maintenance mode and if it is, then check the role of the user
if (_env.IsEnvironment("Maintenance") && await _userManager.IsInRoleAsync(suser, "user"))
return View("Maintenance"); //if user is in 'user' role redirect to maintenance view
else
{
//else redirect to main page
}
}
The above code is executed when specific user tries to login to web app. The problem with above code is that it won't work when user is already logged in and tries to access the web app. in that case it will be redirected to the main page of web app regardless of maintenance mode. How do Logout already logged in user when they tried to access web app under maintenance mode?

Create an action filter or a middle ware that executes the same check for every request
To read more about filters, check this link https://docs.asp.net/en/latest/mvc/controllers/filters.html

Related

With IdentityServer4 and Twitter sign in is there a way to connect an existing account?

With .Net Core 3.1 and IdentityServer4, I have successfully set up Twitter sign in.
However, if I already created an account with that same email address (independently of Twitter)... when I click login in with Twitter, it then redirects me back to the identity server External Login page with the following message:
You've successfully authenticated with Twitter. Please enter an email address for this site below and click the Register button to finish logging in.
and a textbox with my twitter email address already filled in: [ myemail#mydomain.com ]
When I click Register I get the error message:
User name 'myemail#mydomain.com' is already taken.
This makes some sense... but it would be really nice if I had the option of connecting the Twitter login to the existing account... Is there any way to do this?
Its up to you in the ExternalController.Callback method in IdentityServer to handle the mapping to existing accounts and to create new accounts for new users.
For example, see this code:
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = FindUserFromExternalProvider(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = AutoProvisionUser(provider, providerUserId, claims);
}

How can I combine windows login and anonymous authentication by using AD in asp.net boilerplate (.net mvc)? IIS HTTP Error 404.15

I have followed the instructions like the guide said:
LDAP/Active Directory
and How to use LDAP in ASP.NET Boilerplate (Free Startup Template)
But with no success.
Below is my trial and error:
User Scenario:
Most of the users are from the domain, so those domain users should not see the login page and should be able to auto login the platform.
Some of the users are not domain users, for those who have access to the platform but not belong to the domain should pop out the login page and input username/password to login.
Here is a snap of my authentication code:
If(!HttpConetxt.User.Identity.IsAuthenticated)
{
var domainUserName = System.Web.HttpContext.Current.User.Identity.Name;
var entry = new DirectoryEntry("XXX");
var search = new DirectorySearcher(entry);
search.Filter = "(sameaccountname=)" + domainUserName + ")";
// Check if the user is in domain or not
var result = search.FindOne();
if(result != null)
{
//Domain user, find the mapping user in db and login using the db user
...
}
}
Since the website should support both anonymous and windows authentication, I enabled both authentication method:
And also add [AllowAnonymous] attribute to Login ActionResult.
Per my understanding, the request authentication is performed in global.aspx, So I guess my authentication logic should have something to do with this:
protected void Application_AuthenticateRequest()
{
...
}
But it just seems that I could not put my authentication code in there. Because anyway, I need to use the db user to manage user roles, but in the global.aspx, the UserManager is not even there.
I have tried to add this piece of code into Login ActionResult, but there's a problem: when domain user logs out, it will constantly login as it can not tell if the user is actually logged out or just comes to the website.
So:
Where is the right place to put those authentication code?
How does the Ldap work in this scenario? Does Ldap meet the requirements? I could never get the Ldap work in my project.

Checking ASP.NET Membership Authentication from Browser Extensions using JavaScript

Checking ASP.NET Membership Authentication from Browser Extensions using JavaScript
Hi,
I have a website [Visual Studio 2012 website] that uses ASP.NET Membership with OAuth/OpenID. Now I need to create a browser extension [Using Crossrider.com APIs for Chrome, IE, Safari etc.] which will enable logged in [to my website] users to bookmark a URL from the browser extension on button click and save the URL to a database in my website using JavaScript. The website then can show the bookmarked URL for the logged in user in some DataGrid.
Now my questions are:
1. What's the best approach to do this?
2. How do you check if a user is authenticated or not from the browser extension using JavaScript?
3. How to save the bookmarked URL to the Database in my website for that logged in user?
If I understand you correctly, you want the event handler of extension button to send the URL of the active page to your website. In general, you can achieve this by capturing the URL of the active tab using appAPI.tabs.onTabSelectionChanged and then using appAPI.request.get (or post) to send the data to your website database.
Regarding the user credentials, assuming you are authenticating the user in the extension, you can save the credentials to the local database using appAPI.db.set (get to retrieve the data) and send it as part of the request to save the URL. The following code shows the principle idea:
In the background.js file, implement the button handler and saving the URL to your site:
appAPI.ready(function() {
var activeUrl = null;
// Keep track of the active tab's URL
appAPI.tabs/onTabSelectionChanged(function(tabInfo) {
activeUrl = tabInfo.tabUrl;
});
// Configure the extension's button
appAPI.browserAction.setResourceIcon('icon.png');
appAPI.browserAction.click(function() {
// Send bookmark to your website
appAPI.request.post({
url: <YOUR_WEBSITE_URL>,
postData: {
bookmark: activeUrl,
token: appAPI.db.get('userToken'); // User Credentials
}
});
});
});
In the extension.js file, save user credentials to the extension's database:
appAPI.ready(function($) {
// Your authentication code
...
userToken = ...;
// Save the credentials
appAPI.db.set('userToken', userToken)
});
If you require further assistance and feel that stackoverflow is not the appropriate forum to discuss the specifics, please email our support team (support#crossrider.com).
Disclaimer: I am a Crossrider employee

Facebook Javascript SDK - How to tie with ASP.NET MVC Login?

I have an ASP.NET MVC4 web application, and I would like to use Facebook to authenticate users.
My plan is to have users "Sign Up" with Facebook, and then login using it.
Now this is fine when a user comes to the site and logs in with the Facebook Login button I have setup, which goes through an /Account/FacebookLogin action. In that action I can grab the Auth Token and check it against an SQL database to then authenticate the user with all the extra fields/info I store about them in my database (It's a web based game so Character name etc)...
Now, if the user comes to my site and they are already logged into Facebook, they obviously don't go through that /Account/FacebookLogin action... I simply have access to the auth token through the
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
//alert("User is logged in");
}
else if (response.status === 'not_authorized') {
//alert("User is not authorised");
}
else {
//alert("User is not connected to Facebook");
}
});
My question is... What can I do in the "if connected" code to authorize my user, without sending them into an infinite loop? I tried redirecting them to the /Account/FacebookLogin action and passing in the auth token etc. But the getLoginStatus callback is called on every page... so they get stuck in an infinite loop..
Facebook has given you access to someone's Facebook identity. You might now want to create a user account for that identity. Once that user has an account then you then need to get the user to authenticate themselves with your application (you can use the Facebook identity to do this if you wish to tie yourself to Facebook). You can then authorize that user to undertake certain actions within your application.
In the context of MVC, you could quite simply issue them with a forms authentication token:
var username = response.authResponse.name; // <- check the syntax on this
FormsAuthentication.SetAuthCookie(username, true);
return this.RedirectToAction("Index", "AuthorizedUsersOnlyController");

Pass ASP.NET authentication ticket to & from Appcelerator Mobile App

Looking to integrate a login page in an Appcelerator mobile app with ASP.NET membership.
A particular aspect I am looking at is how to keep the user logged in between mobile app sessions, i.e. after closing and re-opening the mobile app the user is still logged in
Ideally the process would go as follows
User enters login details to mobile app
Mobile app passes details to ASP.NET site
Site signs user in, and returns authentication cookie
Mobile app stores authentication cookie locally
For each mobile app site request, it passes the authentication cookie to the site
User logs out, clear local authentication cookie
Thinking because it is a mobile app, best to return data as a json object, for example,
if (Membership.ValidateUser(username, password)) {
FormsAuthentication.SetAuthCookie(username, true);
var json = new {
success = true,
username = username,
message = "Logged In",
authCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName]
};
return serializer.Serialize(json);
Is this process possible or should I be looking at a different solution?
Thanks for any help
Add this to your login page after the user is validated (after calling Membership.ValidateUser()):
FormsAuthentication.RedirectFromLoginPage(
FormsAuthentication.FormsCookieName, true
);
It's documented here.

Resources