ChatGPT解决这个技术问题 Extra ChatGPT

User Authentication in ASP.NET Web API

This topic has been incredibly confusing for me. I am a rookie in HTTP apps but need to develop an iPhone client that consumes JSON data from somewhere. I chose Web API from MS because it seemed easy enough but when it comes to authenticating users, things get quite frustrating.

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

This is not a question but a request for an example of how to do this exactly. I have looked at the following pages:

Making your ASP.NET Web API's Secure

Basic Authentication With ASP.NET Web API

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

Anyone willing to write a nice simple example or point me in the right direction, please?

Thanks.

I have answered kind of the same question on this: stackoverflow.com/questions/11775594/…
For Web Api with asp.net, you can just use the cookie and formsauthentication module as you would with an mvc app (if you want to). So in your web api code you can then check the principal to see if the user is logged-in, for example (same as before).
Also look at my answer for stackoverflow.com/questions/11775594/…
I strongly recommend many folks read asp.net/web-api/overview/security/… article.

J
Jon Schneider

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

That's because you are getting confused about these two concepts:

Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions: Who is the user? Is the user really who he/she represents himself to be?

Who is the user?

Is the user really who he/she represents himself to be?

Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions: Is user X authorized to access resource R? Is user X authorized to perform operation P? Is user X authorized to perform operation P on resource R?

Is user X authorized to access resource R?

Is user X authorized to perform operation P?

Is user X authorized to perform operation P on resource R?

The Authorize attribute in MVC is used to apply access rules, for example:

 [System.Web.Http.Authorize(Roles = "Admin, Super User")]
 public ActionResult AdministratorsOnly()
 {
     return View();
 }

The above rule will allow only users in the Admin and Super User roles to access the method

These rules can also be set in the web.config file, using the location element. Example:

  <location path="Home/AdministratorsOnly">
    <system.web>
      <authorization>
        <allow roles="Administrators"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

However, before those authorization rules are executed, you have to be authenticated to the current web site.

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

From here, we could split the problem in two:

Authenticate users when consuming the Web API services within the same Web application This would be the simplest approach, because you would rely on the Authentication in ASP.Net This is a simple example: Web.config Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using: if (ModelState.IsValid) { if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model);

Cross - platform authentication This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc) For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net. If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service. For more info, take a loot to the following articles: http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/ http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/

http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/

http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/


Wow! That's what I call an answer. So, to conclude. I am planning in doing the following: 1. Create an account controller with a Login method that receives the user name and password over HTTPS and returns the login result and the token. 2. The client stores the token and sends it as a header (no HTTPS anymore) in the request which is validated by the web server. Is that a good approach? Then my final doubt is how to control token tampering and expiration. Is this possible?
@Jupaol I think I speak for many Web API developers, I cannot use Forms Authentication because I do not have a website and clients are not using a browser, nor can I use Integrated authentication because users can be anywhere in the world on any device (hence the Web API), so what do I use?
I don't understand why this answer get so many upvote. It's not about ASP.NET Web API but about ASP.NET MVC.
I'd like to reiterate B413's comment and point out that this question specifically asks for Web API
Is this the most up-voted 'wrong' answer on SO? The answer doesn't actually talk about web api which is very different from a mvc web application! Like @B413 I am totally shocked!
E
Edward Brey

If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.

void EnsureAuthenticated(string role)
{
    string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
    if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
    if (role != null && !Roles.IsUserInRole(parts[0], role))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}

From the client side, this helper creates a HttpClient with the authentication header in place:

static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
    return client;
}

Just wanted to comment that I was looking for a simply way to use the industry standard to pass credentials in the header. This example showed the basics from both the server and the client side and was all I needed.
P
ProfNimrod

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

Where from does response.access_token come from. Are u setting it from c# code..?
The 'response' object is returned by the 'token' method.
I haven't looked into roles. This approach just gives you an access-token so you can call WebApi methods decorated with the [Authorize] tag. Presuambly, when you call any of those methods you could check for roles. stackoverflow.com/questions/19689570/mvc-5-check-user-role might help.
And where in this solution do you actually authenticate your user?
The /token endpoint is created automatically for any new Web API project. The code behind this is where the user is authenticated. It's a bit more complicated if you've added a Web API controller to an existing MVC project.