WebAPI return type

Should I always return the same processed JSON object or not

Example:

On the website, the user enters his username and password.

When the user clicks "Submit", he sends a request to /api/logintest/{key}. If the method called by this URL returns a JSON object, for example {errMsg: null} if the user and password match, and {errMsg: "invalid username or password"} if they do not; or should I return and an error message if the user data does not match and do not return the user object in JSON if the user is found?

This is my code.

    [ResponseType(typeof(User))]
    [HttpPost]
    [Route("api/logintest/{key}")]
    public IHttpActionResult LoginTest(LoginForm luser , String key)
    {
        //test the api key
        if(key == "jordanisthebest")
        {
            //we try to get the user by his username and password
            User userReturn = UsersManager.getUserByEmailAndPassword(new User { Email = luser.Email, Password = luser.Password });

            //if the user is null then we return the err message
            if (userReturn == null)
                ModelState.AddModelError("Email", "Bad email or password");

            //if model state is not good we send err msg
            if (!ModelState.IsValid)
                return  Ok(ModelState.getListErrorAndKey(null, typeof(LoginForm)));

            //if all good we return the user
            return Ok(userReturn);
        }

        return NotFound();
    }
+4
source share
3 answers

IMO, , HTTP 401 -

:

//if the user is null then we return the err message
if (userReturn == null)
    return Unauthorized();
+1

, , , , , .

public class AuthenticationFilter : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Your validation logic here.
    }
}

FilterConfig.cs:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new AuthenticationFilter());
    }
}

... !

+1

, , :

{ "authenticated" : true } // or false

, :

{ "authenticated": false, "reason" : "User account was locked" }

RESTful, :

GET /api/users/{userName}/authenticate

" " HTTP 200 JSON .

HTTP 404 , ( API ), HTTP 401, - , .

It’s good practice not to expose the user to why they didn’t specifically authenticate. The more information you return to the user, the more information for hackers who do not even know if they have a valid user account.

+1
source

Source: https://habr.com/ru/post/1662101/


All Articles