How to work with Identity in ASP.NET MVC - asp.net-mvc-2

How to work with Identity in asp.net mvc. How does Identity work with membership provider, and role provider? Thank you!

There really are two problems you are looking at:
Authentication, easily solved by the built - in membership provider or open auth or LDAP or whatever. Standard ASP.NET backings are in effect.
Authorization, the interesting part. Depending on what is going in it might not matter or it could be insanely finely grained. Default would be to ride the rails of the ASP.NET RoleProviders.
At the end of the day, authentication ins ASP.NET MVC2 isn't much different from authentication ASP.NET. Standard fares apply.

I don't think there's anything special. It should "just work". The default template in MVC in fcat creates a bunch of boiler-plate code for you.

It works pretty much the same as in ASP.NET WebForms, but you control access to different parts of your site by decorating actions or controllers with attributes.
Example:
public class HomeController
{
// Does not require any authentication
public ActionResult Index(int id)
{
return View();
}
// Requires login, and that the logged in user is in the "Users"-Role
[Authorize(Roles="Users")]
public ActionResult SemiSecret(int id)
{
return View();
}
// Same as above, but requires user to be in "Admin" Role
[Authorize(Roles="Admin")]
public ActionResult TopSecret(int id)
{
return View();
}
}
on a controller:
// All actions in this controller requires users to log in and be in "Admin" role
[Authorize(Roles="Admin")]
public class AdminController
{
// Controller code goes here ...
}
You can also limit this on a userlevel by using [Authorize(Users="UserName")]
Hope this helps!

Related

.NET Core 3.1 with Identity - How to set CookieAuthenticationOptions dynamically from SQL Database

Spent many hours on this now and no avail, I want the user to have the flexibility to configure the CookieAuthenticationOptions from within the app. Most of the examples given only set the options in configure services on startup, but this is useless given the options are hard coded.
The challenge I have is finding a solution which allows these options to be configured when using the built in identity features, if the app was using cookie authentication without identity then it would probably be easier to figure out.
Two primary objectives:
Load the CookieAuthenticationOptions on startup from the DB table.
If the settings are changed/updated during the lifetime of the app, the cookies that have already been issues would need to be invalidated/forced to be re-created on the next page request so the cookies now have the updated parameters.
So far, my theory right or wrong is to load the options in the configure method below, however when singing in, I check the chrome debugger and find that the options like cookie name have not been set, assuming the app is simply using the default built in options. So how can I achieve objectives above? Note I'm using razor pages and page models for most of the app, also using the built in identity system from the MS user accounts template. Thx
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions<IdentityOptions> identityOptions, IOptions<CookiePolicyOptions> cookiePolicyOptions, IOptions<CookieAuthenticationOptions> cookieOptions)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
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();
// Added to original .net core template.
// Whenever a request is made for a page, serilog is going to log that.
app.UseSerilogRequestLogging();
app.UseRouting();
// Here I am creating a service to access the DB table and pull the options, this does work for other settings in the DB table which i have not included in this example given the focus of the topic is cookies.
using (var scope = app.ApplicationServices.CreateScope())
{
var systemSettings = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().SystemSetting.FirstOrDefault();
if (systemSettings != null)
{
// Cookie Options
cookieOptions.Value.Cookie.Name = systemSettings.CookieName;
cookieOptions.Value.LoginPath = systemSettings.LoginPath;
// I will add the other parameters once I got the above two working...
}
}
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHub<DataHub>("/dataHub");
endpoints.MapControllers(); // Added for use with REST API.
});
}
MS template Login Page Model uses the standard login method:
var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
Not sure if we have different project types or .NET Core version but have you configured your app to use the cookie in ConfigureServices method?
services.ConfigureApplicationCookie(opt =>
{
opt.Cookie.Name = systemSettings.CookieName,
opt.LoginPath = systemSettings.LoginPath
});

Return 401 in a Web API Facebook Login

community, I was following an example of how to make a service that offers Facebook login on my web api but I can not make it work.
The link for the example. I did try the another example and still not working.
Well, in my AccountController I have the method GetExternalLogin and in the line:
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
The method return the error 401. I don't work with OWIN before, but I want in the method call the Facebook Login API. And this don't call the Facebook login page, just return 401.
I copied all the sample code and not worked. What should I do?
The code in the ChallengeResult:
public class ChallengeResult : IHttpActionResult
{
public string LoginProvider { get; set; }
public HttpRequestMessage Request { get; set; }
public ChallengeResult(string loginProvider, ApiController controller)
{
LoginProvider = loginProvider;
Request = controller.Request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
Request.GetOwinContext().Authentication.Challenge(LoginProvider);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
I don't know any thing about OWIN, sorry. I will learn
Returning 401 (Unauthorized) is correct. This is what the External Login provider (Facebook in your case) use to know that have to display the login page.
As I see, you are already following a tutorial, but maybe this one can help you to understand the authentication and authorization process with external providers. This tutorial explains how to authorize with Google and Facebook, but in your case you can skip the Google parts.
I hope this helps.
Hit the same problem, burned the same neurons. After losing enough brain mass, I found the cause in my case: In the query string, I have written Facebook with a small f. When I changed it to a capital F, it started working.
Hope this helps.

Securing Babaganoush Web Api

Loving the Web API and have created some custom ones for our dynamic module. Is there a way we can secure all the web services rather than just the custom ones we have created?
Thanks.
When inheriting from BaseDynamicController<YouCustomModel>, you can override any of the services like this:
public override IEnumerable<YouCustomModel> Get(int take = 0)
{
if (/* Not Authenticated */)
throw new System.Security.SecurityException("Not authorized to access content");
return base.Get(take);
}
In a future release, we are looking to allow this to be controlled from a virtual method: https://babaganoush.uservoice.com/forums/259241-general/suggestions/6255143-secured-web-services-option-for-dynamic-content

MVC2 Login verification with windows Basic authentication

I am using windows basic authentication, if user is verified home controller is displayed. Only user those who belong to "Admin" group are allowed to access this site. so far all works well. I am using below code. I want to log message in database if user tries to login and does not belong to "Admin" group. Any suggestion how to achieve that?
[Authorize(Roles = "Admin")]
public ActionResult Home()
{
..............
return View();
}
Thanks,
You have 2 options, write a custom authorize attribute which logs on failure or create an HTTPModule which detects 401's and logs there. Personally i prefer the custom authorize attribute approach

How to eliminate ReturnUrl from the browser address

Now on unauthorized attempt to access an action my ASP.NET MVC app redirects user to the login page and generates URL shown below:
http://www.mysite.com/Account/Log?ReturnUrl=%2Ftest%2Fsampleaction
So, is there a way to eliminate this string from the URL, but to save it somewhere to be able to redirect user back after login?
I wonder why you would want to do that. Maybe you are sick of misused, excessive URL parameter orgies, and you like the clean RESTful URL style and the elegant way it can be implemented using the new ASP.NET Routing feature.
However, in this case, this is exactly what URL parameters are intended for. It's not bad practice or bad style at all. And there is absolutely no reason to apply SEO witchery to your login page. So why should you make this process less reliable for the user by requiring the session state directly (or indirectly via TempData), or any other workaround?
I would consider to implement my own AuthorizationFilter and do the redirect.
public class AuthorizationFilter : IFilter
{
public bool Perform(ExecuteWhen exec, IEngineContext context,
IController controller, IControllerContext controllerContext)
{
if (context.CurrentUser.IsInRole("Administrator"))
{
return true;
}
context.Response.Redirect("home", "index");
return false;
}
}
Before redirecting to login action store url
TempData["redirect-url"] = "/requested/page/url";
on login action read that value and pass it to login view and put to a hidden field.
I would implement a AuthorizationAttribute
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.HttpContext.Session["ReturnUrl"] = filterContext.HttpContext.Request.UrlReferrer.AbsoluteUri
filterContext.Result = // Your login page controller;
}
}
}
This is not tested but might help you find the answer
Good luck to you, please provide your solution when found.