I am developing an admin dashboard panel, I have created an intro page for the dashboard which users can log in there
I have four types of user, Admin, SiteManager, PI, and EndUser
After successfully login into the dashboard!
I also Use an Admin Area for something named "Content Management" which is only accessible for the Admin
but when I try to navigate to this content management, it redirects me to the login ( Authorization redirect loops), but the user is already logged in (because I put If condition if the user role is Admin this content management shows)
I am using the individual authentification and scaffold the identity
ASP .Net core 3.1
I don't know how to solve this redirect issue!
in below I put some snip code
[Authorize(Roles =SD.SuperAdmin)]
[Area("Admin")]
public class HMController : Controller
{
private readonly ApplicationDbContext _context;
public HMController(ApplicationDbContext context)
{
_context = context;
}
note: the proposed if the condition is in _layout page
and the Admin Area uses another layout(not _layout)!
Also, I have already checked the Sqlserver the roles and the user are created and functional!
the _layout code:
#if (User.IsInRole(SD.SuperAdmin) || User.IsInRole(SD.ManagerUser))
{
...
#if (User.IsInRole(SD.SuperAdmin))
{
..
}
...
}
If you check for logged user at Login Action and there route user by role.
You solve this problem
if (User.Identity.IsAuthenticated)
{
if (GetUserType() == "Admin")
return Redirect("Admin/Index");
else if (GetUserType() == "Context")
return Redirect("Context/Index");
}
For example:
If admin logged system then if admin click not authorized page then redirect Account/Login.
Account/Login page is check to user login
If user logged then redirect user homepage
Related
I am using FosUserBundle in Symfony 3.4. I want to redirect users based on their roles. For example, if the role is Client, the user will be redirected to the clients page. If the user is an Admin, then the user will be redirected to the admin dashboard page. How can I do this with FosUserBundle?
Redirect them both to a controller named indexAction() and Redirect them in the controller based on the role. Something like this:
/**
* #Route("/secure-area", name="homepage")
*/
public function indexAction()
{
if($this->getUser()->hasRole('ROLE_ADMIN'))
return $this->redirect($this->generateUrl('admin_area'));
elseif($this->getUser()->hasRole('ROLE_USER'))
return $this->redirect($this->generateUrl('client_area'));
throw new \Exception(AccessDeniedException::class);
}
EDIT:
You should set the default_target_path to the path above
Created a mvc5 app with Identity2,using google login (pretty much the empty app, with google stuff turned on)
How do I set it up to use session cookies, so they expire when the browser closes.
The app will be used by students who may hot swap seats, so i need the login to expire when the browser closes.
I read an SO article that implies this is the default, but when i close the browser, and go back to the site, it remembers the google login.
Edit
Sorry to burst everyone bubble, but this isn't a duplicate.
It reproduced in Chrome after the settings in the supposed "answer" are changed, and it also reproduces in IE... This is an Asp.net Identity 2 +Google login issue, not a Chrome issue.
Edit
Adding Startup Auth file for Setup Help
using System;
using System.Configuration;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentPortalGSuite.Models;
namespace StudentPortalGSuite
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes( 30 ),
regenerateIdentity: ( manager, user ) => user.GenerateUserIdentityAsync( manager )
)
},
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// per https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on - EWB
//dev-jcsn email
app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions()
{
ClientId = "...",
ClientSecret = "..."
} );
//});
}
}
}
EDIT
The use case I'm trying to fix is, since our app is used in a classroom, that student A Closes his/her browser instead of logging out, and then next user tries to login. As it stands they are autologged into user A's account.
I'd also be up for a way to 100% log out the user when redirected to the login page, but all the ways I've tried that aren't working.
Maybe you can catch the window close event on page and call logout method
$(window).on("beforeunload", function() {
//ajax call to a post controller that logs the user out
})
Calling this at the top of the LogIn controller Method solved the issue.
Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ApplicationCookie );// https://stackoverflow.com/questions/28999318/owin-authentication-signout-doesnt-seem-to-remove-the-cookie - stralos s answer
Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ExternalCookie );
I am creating a single page application with angularJs, aspnet and thinktecture. I have created a login screen in thinktecture (as localhost:44304) for customer login and after successful login, it redirects to customer portal like https://localhost:44302.
when I run the customer app then it redirected to thinktecture login screen and after a login success, it come back to customer portal.
Now issue is that any customer can register a request by using registration page which is placed on the customer portal and we are redirecting it from thinktecture login screen as shown
When I click on "here" link then redirect me again same login screen.
I added the code as below in startup.cs for customer poratal.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
string thinkTectureUrl = ConfigurationManager.AppSettings["ThinkTectureUrl"].ToString();
string loginSuccessUrl = ConfigurationManager.AppSettings["LoginSuccessUrl"].ToString();
string clientSecret = ConfigurationManager.AppSettings["ClientSecret"].ToString();
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
ClientId = "Provista.CustomerPortal.WebApp.External",
Authority = thinkTectureUrl,
RedirectUri = loginSuccessUrl,
ResponseType = "id_token",
Scope = "openid email",
SignInAsAuthenticationType = "Cookies",
ClientSecret = clientSecret.Sha256()
});
I searched on google and stackoverflow a lot but didn't get a reliable link that help me to solve this.
Please reply as soon as possible if any one have any idea.
You might have global authorization filter which redirects unauthenticated users to identity server. Probably in Global.asax
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
Requests to your 'Register User controller' also treated by this filter and redirect to identity server will happen.
To override global filter and allow unauthenticated users to your Register User controller use [AllowAnonymous] attribute in your 'Register User controller'.
I have two domains ,on our internal network:-
DomainA
DomainB
Both domains can communicate with each other’s, but they do NOT trust each other.
So currently I have deployed my asp.net MVC web application inside domainA on IIS, but I need users who are on DomainB Active directory to be able to login to the asp.net mvc using their domainB AD credentials . I am open to both windows authentication and form authentication inside my asp.net mvc .
But the only requirement that came from the client is that they want users who access the asp.net mvc intranet application from their machine on domainB, to be able to lo-gin to the system without having a login page; they can either:-
enter the username and password through the browser pop-up,
or to sign in automatically.
So can anyone advice what are the approaches I can follow, to achieve this?
Thanks
EDIT
I have read the following article http://msdn.microsoft.com/en-us/library/ff650307.aspx, about how i can authenticate asp.net mvc users from multiple domains, so inside my asp.net mvc i did the following :-
I added the following to my web.config:-
<system.web>
<membership>
<providers>
<add name="TestDomain1ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="TestDomain1ConnectionString" connectionUsername="ad-domainA.intra\it360ad.user" connectionPassword="$$$$$" />
</providers>
</membership>
&
<add name="TestDomain1ConnectionString" connectionString="LDAP://ad-domainA.intra/CN=Users,DC=ad-domainA,DC=intra" />
and i added the following Account.controller:-
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
MembershipProvider domainProvider;
domainProvider = Membership.Providers["TestDomain1ADMembershipProvider"];
// Validate the user with the membership system.
if (domainProvider.ValidateUser(model.UserName, model.Password))
{
// If there is a RequestUrl query string attribute, the user has
// been redirected to the login page by forms authentication after
// requesting another page while not authenticated.
if (Request.QueryString["ReturnUrl"] != null)
{
// RedirectFromLoginPage sets the authorization cookie and then
// redirects to the page the user originally requested.
// Set second parameter to false so cookie is not persistent
// across sessions.
FormsAuthentication.RedirectFromLoginPage(
model.UserName, false);
}
else
{
// If there is no RequestUrl query string attribute, just set
// the authentication cookie. Provide navigation on the login page
// to pages that require authentication, or user can use browser
// to navigate to protected pages.
// Set second parameter to false so cookie is not persistent
// across sessions.
FormsAuthentication.SetAuthCookie(model.UserName, false);
}
}
else
{
// Response.Write("Invalid UserID and Password");
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
////////////
//if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
//{
return RedirectToLocal(returnUrl);
//}
// If we got this far, something failed, redisplay form
}
But currently when the user try to login , he will get always the following message
•The user name or password provided is incorrect.
so can you advice if my code is correct ?
You have to deploy a SSO solution like Active Directory Federation Services on a server that is joined to DomainB.
Then implement authentication in your application (for example, WS-Federation Passive Requestor) that targets that SSO solution and standard Windows Authentication that targets DomainA.
I developed an application using symfony2, I want to know how to write preExecute() function symfony2 for following case:
when I log-in into the system; it redirect me on user profile section when I log-out from same screen, It killed session and redirect me on login screen, but when I hit browser's back button then it will redirect me on profile screen, which shows me all user information but when I click for next process from same screen then I redirect me on login page.
I just want to add preExecute function like symfony1.4 for this case, so I checked session and if it is null then it will redirect me on login page if I hit browser's back button when I alrady log-out from the system.
I already added following code in profileController.php files,
public function indexAction() {
$session = $this->get('request')->getSession();
$userId = $session->get('id');
if ($userId == 0 || $userId == '') {
return $this->redirect($this->generateUrl('_security_login'));
} else {
//my code
}
}
//logout action
public function dologoutAction(){
$this->get('security.context')->setToken(null);
$this->get('request')->getSession()->invalidate();
$this->container->get('request')->getSession('session')->clear();
return $this->redirect($this->generateUrl('_security_login'));
}
if there is any other way to handle this case then please help me for the same.
Thank you.
Just require the ROLE_USER role on the profile action and the firewall will do the redirect-to-the-login-form-and-then-redirect-back stuff:
/**
* #Secure("ROLE_USER")
*/
public function profileAction()
{
// ...
}
For more information read the Security chapter of the Symfony book.