Click here to Skip to main content
14,734,526 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

what is the best way to access secure a WebService with JWT Bearer Token from a Website if both running on different servers ?

What I have tried:

Hi,

i`m new in Web programming. I just create a Webservice and it worked as well with JWT Bearer Token. 
Now i set up a Asp.Net Core Website which use an own Identity Authentication. 

At the moment i realize the Token in Webservice as follow:

<pre lang="c#">public IActionResult Login(string username, string pass)
        {
            UserModel login = new UserModel();
            login.UserName = username;
            login.Password = pass;
            IActionResult response = Unauthorized();

            var user = AuthenticateUser(login);

            if(user != null)
            {
                var tokenStr = GenerateJSONWebToken(user);
                response = Ok(new { token = tokenStr });
            }
            
            return response;
        }


and this is the Token Creation:

private string GenerateJSONWebToken(UserModel userinfo)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,userinfo.UserName),
                new Claim(JwtRegisteredClaimNames.Email,userinfo.EmailAddress),
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())

            };

            var token = new JwtSecurityToken(
                issuer: _config["Jwt:Issuer"],
                audience: _config["Jwt:Issuer"],
                claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: credentials);

            var encodetoken = new JwtSecurityTokenHandler().WriteToken(token);
            return encodetoken;
        }


Now i have hardcoded the username and password for the token in Website Startup.cs as follow:


var client = new RestClient(Startup.URLWebservice);
            var request = new RestRequest("api/Login?username=test&pass=123", Method.GET);
            var deserial = new JsonDeserializer();
            var response = client.Execute(request);
            Token = deserial.Deserialize<Dictionary<string, string>>(response);


What is the best pattern to make this scenario safe ? First of all i think there should`nt be username and password hardcoded ? The better way could be that the webservice only send the token to an authenticated user from the website - but how can i achieve this ?

Hope anybody can help me !?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900