Custom Authentication in Web API 2 with OWIN

0

The theme is as follows. I am working on the authentication system for an API in Web API 2, according to a certain need of the project my OAuthProvider is as follows:

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        string rol = null;
        if (context.Request.Headers.ContainsKey("X-Role"))
        {
            rol = context.Request.Headers.Get("X-Role");
            switch (rol)
            {
                case "user":
                    bool isValidCredentials = await //Logica que verifica credenciales.
                    if (isValidCredentials)
                    {
                        //Crea y prepara el objeto ClaimsIdentity
                        var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                        identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                        var data = new Dictionary<string, string>
                        {
                            {"email", context.UserName}
                        };
                        var properties = new AuthenticationProperties(data);
                        var ticket = new AuthenticationTicket(identity, properties);
                        context.Validated(ticket);
                        return;
                    }
                    else
                    {
                        context.SetError("Invalid user or password.");
                        return;
                    }
                case "things":
                    //Logica para autenticar things.
                    return;
                default:
                    context.SetError("The role is not valid.");
                    return;
            }
        }
        else
        {
            context.SetError("The role header is required.");
            return;
        }
    }

With this code everything is going well and works as it should.

Next I leave the code of the GET method of my driver Customer.

        [Authorize(Roles = "user")]
    [Route("{email}")]
    public async Task<PcCustomer> Get([FromUri]  string email)
    {
        var allData = await CustomerData(email);
        return allData;
    }

The issue is that I need to also need to validate that the email from which the customer's information is being requested is the same for which the token was requested to avoid the consequent security risk. As I can do this, I have the idea that if from CustomerController I have access to the Claimsidentity created in OAuthProvider but I do not know how to do that. How can I implement the described behavior?

    
asked by lavilaso 26.07.2018 в 02:08
source

0 answers