Cross-Origin Requests WebApi [closed] - c#

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.

Related

Server response best practice [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 1 year ago.
Improve this question
I'm developing a RESTFUL web server that have some API REST used by android clients. It's the first time I've done API REST so i followed several guides to made it. Now when client make a GET request to get something, the server return the data in JSON, but not additionals information. Now that I'm making the android application I understand that this type of managment isn't good because i can't handle the errors like 401, 404, etc from application to show errors to the user (I use retrofit 2 with coroutines).
Can someone explain me the best method to make the responses from the server? I understand that I have to make a generic class like Response that have a Code and an Error_Message, and I have to extend this class for all my responses to add the data required from the client. But after that how I handle the response from my application? I can't make two different classes (one for errors and one for success responses).
Can someone help me?
The type of solution you propose, is not REST. A common practice in the past was to use only 200 success responses and POST everything. REST APIs by convention use the status codes to convey a meaning. You should also always think of error 500, because this will happen and your application should handle it.
You also might be interested in this: Microsoft best-practices api-design
I understand that this type of managment isn't good because i can't handle the errors like 401, 404, etc from application to show errors to the user
I don't see why you can't do that. There is perfectly good code to handle the requests.
#Override
public void onResponse(Call<YourModel> call, Response<YourModel> response) {
// All the 20x responses
if (response.isSuccessful()) {
} else if (response.code() == 401) {
} else {
}
}
You can also use an interceptor, if you are using OkHttp Check here for interceptor code

How to send messages with Firebase admin SDK [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 2 years ago.
Improve this question
Nuget used:
FireBaseAdmin v1.9.2
I'm trying to use firebase admin to send push notification to fcm.
I read the documentation but can't find any other good source to figure out how to use it properly.
I can't figure out where to add the serverkey and senderid.
I made a methode for sending push notifications.
Has anyone an example i could follow or any other documentation?
public override async Task<string> Send(List<String> tokens, string title, string body)
{
var message = Message()
{
Tokens = tokens,
Notification = new Notification()
{
Title = title,
Body = body
}
};
return await FirebaseMessaging.DefaultInstance.SendAsync(message).ConfigureAwait(false);
}
When i debug this code the response is null from SendAsync.
It might be because i didn't give it the serverkey and senderId but then i would expect an error like serverKeyNotFound.
Server key and sender ID parameters are not used in the Admin SDK. You just need to instantiate a FirebaseApp with some GoogleCredential as shown in https://firebase.google.com/docs/admin/setup.
On top of that your code seems to be syntactically incorrect. There's no Tokens property available in the Message class. You need MulticastMessage class for that. So I'd expect the above code to fail compilation.

Recommended approach for handling non-authenticated sessions on ServiceStack [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 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;
}
}

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.

Categories