Add message in Oauth reply

Asked

Viewed 52 times

1

I created a web api with token validation that works correctly, my problem is: I would like to put a message after the mandatory information, I leave attached an example image(I would like to add that "validated") and also my code. inserir a descrição da imagem aqui Grateful!

namespace BRWAdmPanel.Services

public class ProviderDeTokensDeAcesso : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        if (UserSecurity.Login(context.UserName, context.Password))
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            context.Validated(identity);

        }
        else
        {
            context.SetError("acesso inválido", "As credenciais do usuário não conferem....");
            return;
        }
    }
}

Adding other parts of the code for better understanding:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        //config da webapi
        var config = new HttpConfiguration();
        //config de rota
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );
        //ativando CORS
        app.UseCors(CorsOptions.AllowAll);
        //ativando a geração de token
        AtivarGeracaoTokenAcesso(app);
        //ativando webapi
        app.UseWebApi(config);

    }
    private void AtivarGeracaoTokenAcesso(IAppBuilder app)
    {
        var opcoesConfiguracaoToken = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new ProviderDeTokensDeAcesso()
        };
        app.UseOAuthAuthorizationServer(opcoesConfiguracaoToken);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

Last part:

 public static bool Login(string login, string password)
    {

        MD5 md5Hash = MD5.Create();
        // Converter a String para array de bytes, que é como a biblioteca trabalha.
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(password));

        // Cria-se um StringBuilder para recompôr a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop para formatar cada byte como uma String em hexadecimal
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        using (BRWAdmPanelEntities entities = new BRWAdmPanelEntities())
        {
            password = sBuilder.ToString();
            return entities.OHEM.Any(user =>
           user.pager.Equals(login, StringComparison.OrdinalIgnoreCase)
           && user.U_BRWPassword == password);
        }
    }
}
  • It has to be with put in the part of the code referring to the construction of the token that is not that code at least as far as I know is in the return of that data. Where is all the code?

  • Good morning Virgilio, thanks for responding, I will update with all the token generation code, as I am beginner did not understand very well where is this part of construction but I hope I can send you the correct ones.

1 answer

0


To make the change you need it is necessary to be using the method TokenEndpointResponse next to context.AdditionalResponseParameters.Add as in the example below:

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
    context.AdditionalResponseParameters.Add("chave", "valor");

    return Task.FromResult<object>(null);
}

In the above example the variable context owns the property Identity, that inside it has a list of Claims, so you may be accessing it to do something like fetch a data through the id stored inside the Claims.

context.Identity.Claims.Single(c => c.Type == "sub").Value

In the example above you can get the value stored inside the sub.

  • Perfect! worked the way I wanted, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.