Home > front end >  I have written below code, I need to change the response like-
I have written below code, I need to change the response like-

Time:06-07

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            using (UserAuthentication objUser = new UserAuthentication())
            {
                //var user = db.ApiUsers.Where(o => o.UserName == context.UserName && o.UserPasswd == context.Password).FirstOrDefault();
                var user = objUser.ValidateUser(context.UserName, context.Password);
                if (user == "false")
                {
                    context.SetError("invalid_grant", "Username or password is incorrect"); 
                    if(context.ErrorDescription == "Username or password is incorrect")
                    {
                        
                    }
                    context.Response.StatusCode = 200;                   
                  
                    return;
                }
                else
                {                   
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    await Task.Run(() => context.Validated(identity));
                }
            }
        }

   

Output: { "error": "invalid_grant", "error_description": "Username or password is incorrect" }

The output should like: { "Message": "invalid_grant", "Message_Description": "Username or password is incorrect" }

CodePudding user response:

You can create your own formatted class and mapping like this:

public class FormattedError
{
    public string Message { get; set; }
    [JsonPropertyName("Message_Description")]
    public string Description { get; set; }
}

public static class OAuthGrantResourceOwnerCredentialsContextExtensions
{
    public static FormattedError ToFormattedError(this OAuthGrantResourceOwnerCredentialsContext context)
    {
        return new FormattedError()
        {
            Message = context.Error,
            Description = context.ErrorDescription,
        };
    }
}

And in a place where you a have context with error you can get formatted error:

var formattedError = context.ToFormattedError();

CodePudding user response:

The answer of Dmytro Krivoruchenko is not good enough.

The error object is serialized in the class 'OAuthAuthorizationServerHandler.cs' git file line 716.

The constants present in the 'OAuthConstants.cs' class are used for serialization. git file line 21.

You would have to create your own Authorization Handler to be able to modify the error response.

  • Related