Recommended approach for handling non-authenticated sessions on ServiceStack [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've an MVC app, with SS integrated for all BLL that has a shopping basket feature. I want anonymous users to be able to add to basket and then continue shopping with basket details intact when they return - so I feel using the ss-pid for sessionId in redis is the best approach.
Could somebody please confirm if I'm tackling this right, and if so, how do I enable this functionality? (I can't see anyway to use ss-pid by default).
Thanks.

If you want to use the Session Cookies to store Unauthenticated User Info then you'll want to set:
Plugins.Add(new AuthFeature(...) {
GenerateNewSessionCookiesOnAuthentication = false
});
So when the user does authenticate it preserves the existing cookies, otherwise you'll want to set and use your own Cookies which are unaffected when a User Logs in.
The SessionBag is a good solution for this that uses the Users Session Cookies to store session data for UnAuthenticated users, e.g. you can populate a custom POCO with something like:
var unAuthInfo = SessionBag.Get<UnAuthInfo>() ?? new UnAuthInfo();
unAuthInfo.CustomInfo = request.CustomInfo;
SessionBag.Set(unAuthInfo);
Then when a User Authenticates, retrieve the info from the Session Bag and add it on your Typed Custom UserSession using the OnAuthenticated() event, e.g:
public class CustomUserSession : AuthUserSession
{
[DataMember]
public string CustomInfo { get; set; }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session,
IAuthTokens tokens, Dictionary<string, string> authInfo)
{
var unAuthInfo = authService.GetSessionBag().Get<UnAuthInfo>();
if (unAuthInfo != null)
this.CustomInfo = unAuthInfo.CustomInfo;
}
}

Related

Cross-Origin Requests WebApi [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I was reading https://learn.microsoft.com/en-us/aspnet.... about Security to prevent AJAX requests to another domain and makes me wonder, if I enable this, I would be able to make request from my Android Client? Cu'z it seems that anything outside of that domain, can't be requested. Is that it? Thanks!
Would be something like:
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (IUserRepository _repository = new UserRepository(new Data.DataContexts.OAuthServerDataContext()))
{
var user = _repository.Authenticate(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
If you are making the request from another domain then you will need to set up an Access-Control-Allow-Origin header. You can use * if you aren't concerned about security but it's best to specify only the domains you know will need access.
Non-browser-based clients may not necessarily send the Origin header (e.g. Postman) in which case you likely won't need to worry about setting up CORS.
That documentation you linked is a good start. This post provides a good basic example if you want to set up access globally rather than a per-controller basis.

How to access database in asp.net mvc? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In the default asp.net application, I want to access the data of other users. In my database table ASPNETUSERS I have columns such as Id, Email, Password, Gender etc. Now I want to be able to search for a particular Id and get that user's entire details like his/her Email, Password, Gender etc. So how do I do that?
Do I use raw SQL? If so how? (someone on SO mentioned this as a bad idea)
Do I use models or something else? if so how?
This is my ASPNETUSERS Table info. And this is my action in a controller. I want to be able to get an user called "stackoverflow#gmail.com" and send all his details(whatever are there in my table) to the view.
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index(string id = "")
{
//db.someCommand or something to let me get stuff about
//stackoverflow#gmail.com. Could it be db.Database.ExecuteSqlCommand ?
return View("Send All details about my stackoverflow user");
}
Edit: This is what I tried before. I tried to use raw sql and convert it to a string(for testing) and write it to a file on desktop. That way I thought I would at least know that the data in my database is getting passed back to me correctly before I pass it to my view.
This was my line of code that I added just before my action returned.
System.IO.File.WriteAllText(#"C:\Users\Admin\Desktop\log.txt", db.Database.ExecuteSqlCommand("select * from dbo.AspNetUsers").ToString());
I did not get any errors doing so, but I expected my data from the image above to be posted into my file called log.txt on desktop. But I opened log.txt file only to find that "-1" was posted in there.
If you want to get the users from your database, use linq with your ApplicationDBContext object
ApplicationDbContext db = new ApplicationDbContext();
//Manipulate the Where clause to get the conditions you want
IEnumerable<ApplicationUser> users = db.Users.Where(x => x.Email == "stack#overflow.com");
This works with the out of the box ASP.NET individual authentication model (which looks like what you have)

How to make website readonly that link from certain websites. asp.net [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a website where a user logs in, can see his information and edit it. There is also another website, something like a site only for admins, where if I click a link it redirects me to the first website, logged in as that user but I can only read his information not edit it. I am having trouble finding out how to make website 1 both readable only and read/writeable.
I am doing this in Asp.NET mvc using C#.
One method would be to check for authorization in the Razor view.
Psuedocode:
#if(User.IsAuthorizedForEdit()
{
#*your edit view code*#
}
else
{
#*your readonly view code*#
}
This does make for some bloaty Razor. The other (arguably, better) alternative is to direct them to the appropriate view in your controller based on user.
Handy-wavy psuedocode to give you an idea:
public ActionResult ViewProfile(int profileId)
{
var user = GetCurrentUser();//without looking at your code, I can't infer this piece.
var profile = GetProfile(profileId);
if(IsAuthorizedToEdit(user, profileId)
{
return View("edit", profile);
}
else
{
return View("view", profile);
}
}
In theory, you already have a read-only view and an edit view, so the latter would be more reusable.

What's the most professional way for login control in ASP.NET? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Say, we are not using forms authentication or membership. When a user requests for any of the pages of the application, she needs to be redirected to login page.
This way, each page needs to have an authentication check on the Page_Load(). But what if we have over 500 pages.
Any chance to use sth like static classes with static properties or creating your own http handlers?
This is too broad of a question with a few aspects, including :
How to manage a User's Session
How to manage multiple user accounts being logged in
How to perform the login process
Managing a user's state must be independent of anyone else's actions. Therefor, you cannot rely on static properties. This presents the question of "Well, how do I keep track of it without it being static?" One of the answers is to use Session information. For example, during an Ajax request to the server you could do this :
if (HttpContext.Current.Session["LoggedIn"] != null)
{
object oValue = HttpContext.Current.Session["LoggedIn"];
bool bResult;
if (bool.TryParse((string)oValue, out bResult) == true)
return bResult
return false;
}
else
return false;
This solves the first two issues and opens a door to creating a hanlder class that knows YOUR specific session keys and patterns for getting different kinds of values.
As for the third issue you will face - No one can give you a concrete answer. Your design and data structure will determine how you validate and track your users.

should I use an object to handle user search criteria? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a search form that allows users to search real estate listings.
I currently have it set up as a basic html form that posts to a search results page.
On the search results page, I then use raw SQL and query the database and then use a repeater to display the results. I also create session variables on the query so if the user does another search they dont have to fill out the whole search, just edit it.
I was wondering if I should rather create a search class with a search object that gets created and edited with each search. Is this the best practice? or is my method above sufficient?
Thanks!
If there are lots of search parameters then I'd create a class to encapsulate them all and store that in session state, rather than maintaining lots of separate session variables. You might need to decorate this class with the SerializableAttribute depending on how you've got your session state configured, e.g.
[Serializable]
public class SearchOptions
{
public string Foo { get; set; }
public string Bar { get; set; }
}

Categories