ASP.NET MVC authentication using http header - asp.net

In my ASP.NET MVC 4 application I need to authenticate the user using an existing http header value which contains the username.
It works using form authentication : the user is redirected to a login page when he is not authenticated yet. The controller of the login page check the httpHeader value and connect the user using FormsAuthentication.SetAuthCookie(username,false) and redirect the user to the main page of my application.
But I want to avoid this redirection and directly try to authenticate the user when the event 'user not authenticated' is fired.
Axes :
FormsAuthentication_OnAuthenticate
Override AuthorizeAttribute
AuthenticateRequest

If i understood you correctly then you just need to set currentPrincipal with username
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(user, "Basic"), new string[] {});
So from now it will work and you can access user as well User.Identity.Name

Related

Change the Identity Login's success url instead /Home/Index in .NET core

I have developed a .NET core 2.2 project using Individual (Identity Authentication). After login is successful from /Identity/Account/Login application routes to /Home/Index
But I want that after login is successful the page should Redirect to /Dashboard/Index , another view in my project. How should I implement this?
You'll need to scaffold in the Login page (if you haven't already) and change it in the code behind. However, that's just the default if no returnUrl is provided. Normally, the user will be prompted to login because they've attempted to go to some area that requires authorization, such as /Dashboard/Index in your scenario. If they navigate to /Dashboard/Index and are redirected to the login page to authenticate, then they will be redirected back to /Dashboard/Index once they're logged in.
In .NET Core 5 What I have done is I have scaffolded Identity and and checked overridden Login/register pages. It creates a class file where you can update your code like this.
The generated file location is : Areas\Identity\Pages\Account\Login.cshtml.cs
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/Dashboard/Index"); // Change the default login redirect url to Dashboard/Index
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

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.

How to set Azure Authentication custom login return url?

I followed this article https://azure.microsoft.com/en-us/blog/announcing-app-service-authentication-authorization/ to set up Azure authentication for my MVC app. First I turned on Azure AD provider. In the Authentication / Authorization settings, I selected "Allow request(no Action)" for "Action to take when request is not authenticated" because I only need users to login for certain controller actions.
Then I added a custom FilterAttribute to check if one action needs authentication as in https://stackoverflow.com/a/26652816/1837339. In the OnAuthenticationChallenge function, I had this code to redirect to login page:
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
if (filterContext.Result is HttpUnauthorizedResult) {
filterContext.Result = new RedirectResult("~/.auth/login/aad");
}
}
All of this works, except after user finished authentication, it is redirected back to mysite/.auth/login/done page saying "You have successfully signed in" and a button to return to my site's base url.
What I want is the redirection goes back to the user's original url, so I think I need somehow set the return url for the login redirect. But I couldn't find any documentation about this. Anyone could give any advice?
You can use the post_login_redirect_url query string parameter to do this.
For example, if you want to automatically navigate the user to /welcome.html after logging in, you can set your login redirect to ~/.auth/login/aad?post_login_redirect_url=/welcome.html, and the user will be redirected to this page instead of the generic welcome page.
Thank you.
This really helped.
The below worked ok for me:
return RedirectToAction(string.Format("login/{0}?post_login_redirect_url=/Home/LoginCallBack", provider), ".auth");
provider can be one the strings: google, twitter, microsoftaccount,aad,facebook.
Also each provider must be configured on your project at the Azure Portal.
redirect url may be any uri on your project

How set Authorization attribute role MVC4 to the user?

I'm trying to use the Authorize attribute on MVC 4 application,
[Authorize(Roles = "Administrator, Super-User")]
public JsonResult Remove(int id)
{
.
.
.
}
I know that only the roles "Administrator" and "Super-User" roles are authorized to execute the method Remove, but how I can set the role to the actual User of the application?
The answer is - somehow, so that HttpContext.Current.User is set and the IsInRole method returns true.
The easiest way to do this would be to follow one of built-in mechanisms of authentication/authorization: Forms authentication or Windows authentication.
The former requires that the request carries a valid forms cookie issued by the server. The latter requires that the request principal can be authenticated in the domain controller.
You are however free to implement a custom authentication module.
If you are just starting to learn this, probably you'd like to use Forms Authentication for this. Just let your users log in, issue the cookie and the cookie will automatically be carried by subsequent ajax request (assuming your server code is called from within javascript client-side ajax call).
You can Add the current user to a role using
Roles.AddUsersToRole(new string[]{HttpContext.Current.User.Identity.Name}, "Admin");
Roles class is available in System.Web.Security namespace.
if you want to add users and Roles
-Open your solution in Visual Studio
goto project->ASP.NET configuration->Security Tab
You can add a user to roles using a Role Provider.
var rolesProvider = (SimpleRoleProvider)Roles.Provider;
Check the role exists
if (!rolesProvider.RoleExists("SuperUser"))
{
rolesProvider.CreateRole("SuperUser");
}
Check if the user is in the role already, if not, add the user to the role
if (! rolesProvider.IsUserInRole("JohnSmith", "SuperUser"))
{
rolesProvider.AddUsersToRoles(new[] {"JohnSmith"}, new[] {"SuperUser"});
}

How to implement alternative login for asp.net forms authentication?

I have an existing website using forms authentication with Sql provider. Now i am trying to integrate with another website and use their authentication mechanism. I am already able to validate a user and trying to silently login the user into my application. Here is the code for "silent" login:
if (user != null) // logged in!
{
IPrincipal principal = new MyPrincipal(user);
FormsAuthentication.SetAuthCookie(user.ScreenName, true);
HttpContext.Current.User = principal;
Response.Redirect("~/Default.aspx");
}
and it works with the exception that Forms Authentication overrides the HttpContext.Current.User by the time i make it "default.aspx". Is there a way to bypass forms role and membership providers?
If you are using a custom principal, the custom principal must be established on every request to the web server; it's not persisted. Adding code to reload it in global.asax would resolve it. Others have created an HTTP module to do this too.
HTH.

Resources