Readdy Write  
0,00 €
Your View Money
Views: Count
Self 20% 0
Your Content 60% 0

Users by Links 0
u1*(Content+Views) 10% 0
Follow-Follower 0
s2*(Income) 5% 0

Count
Followers 0
Login Register as User

Web Api Client-Server 20180704: Part 6) Webserver Token-Controller

04.07.2018 (👁8141)


Platform: Asp.Net Core 2

WebApi, Webserver

Sprache: C#

api/TokenController.cs

Api Token Controller

Der Token-Controller vergibt zu Beginn einer Api Client Verbindung einen User-Token.

Der Aufbau beginnt mit einer User-Passwort Übertragung und prüft die Angeben gegenüber der Datenbank. Danach wird ein User-Spezifischer Token erstellt, welcher in den Claims Angaben zum User enthält, welche bei weiteren Datenübertragungen im Header übertragen werden...

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

 

//< using >

using System.Text;                      //*Encoding

using Microsoft.IdentityModel.Tokens;   //*SymmetricSecurityKey

using System.Security.Claims;           //*Claims for JWT Token

using System.IdentityModel.Tokens.Jwt;  //*JwtRegisteredClaimNames

using Microsoft.Extensions.Primitives;  //StringValues

//</ using >

 

namespace Freelance.Controllers.api

{

    //*when open an api-Connection, first call /api/token and get a valid token to work with the api data

    [Produces("application/json")]

    public class TokenController : Controller

    {

        //--------------< Class: TokenController >---------------------

        //*min 16 chars

        

 

 

        [Route("api/get_InitToken")]

        [HttpGet]

        public IActionResult Get_Init_Token()

        {

            //--------< Get_Init_Token >--------

            string stringToken = create_UserToken(null);    //*optional values null

            return Ok(stringToken);

            //--------</ Get_Init_Token() >--------

        }

 

 

        [Route("api/get_usertoken")]

        [HttpGet]

        public IActionResult Get_UserToken()    //*parameters in header

        {

            //-------------< Get_UserToken() >------------- 

            //*Create a Usertoken if parameters are correct.

 

 

            string username = "";

            string password = "";

 

            //----< get User and Password >----

            //*from Basic Authorization header

            if (Request.Headers.TryGetValue("Authorization"out StringValues authToken))

            {

                //< get authenication string >

                string authHeader = authToken.First();

                string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();

                Encoding encoding = Encoding.UTF8; 

                string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

                //</ get authenication string >

 

                //< get user and password >

                //*like myUser:myPassword

                int seperatorIndex = usernamePassword.IndexOf(':');

                username = usernamePassword.Substring(0, seperatorIndex);

                password = usernamePassword.Substring(seperatorIndex + 1);

                //</ get user and password >

            }

            else

            {

                return BadRequest("Missing Authorization Header.");

            }

            //----</ get User and Password >----

 

 

            //*check here against user and password

            if (check_login_user_password(username,password) == true)

            {

                //< login ok >

                string sToken = create_UserToken(username);

                return Content(sToken);

                //</ login ok >

            }

            else

            {

                //< login failed >

                return BadRequest();

                //</ login failed >

            }

 

            //-------------</ Get_UserToken() >------------- 

        }

 

 

 

 

        #region Helper-Methods

        //-----------------< region: Helper-Methods >---------------

        public string create_UserToken(string sUsername="")

        {        

            //-------------< create_UserToken() >-------------

            ///*creates a jwt Token with optional User-Information

            Claim[] claims = null;

            if (sUsername !=null )

            {

                //< add User-Information >

                claims =new Claim[] {

                    new Claim(ClaimsIdentity.DefaultNameClaimType, sUsername),                

                };

                //</ add User-Information >

            }

 

            //--< Create a Token >--

            JwtSecurityToken jwtToken = new JwtSecurityToken(

                issuer: Website_Constants.api_Issuer,    //ASP.NET Core web application

                audience: Website_Constants.api_Audience, //client app

                claims: claims,

                notBefore: DateTime.Now,

                expires: DateTime.Now.AddDays(1),

                signingCredentials: new SigningCredentials(Website_Constants._secretKey, SecurityAlgorithms.HmacSha256)

            );

            //--</ Create a Token >--

 

            //< convert to String >

            string stringToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            //</ convert to String >

 

            //< out >

            return stringToken;

            //</ out >

            //-------------</ create_UserToken() >-------------

        }

 

 

        private bool check_login_user_password(string sUsername, string sPassword)

        {

            //-------------< check_login_user_password() >-------------

            if(sPassword == Website_Constants.api_Password)

            { return true; }

            else

            {

                return false;

            }

            //-------------</ check_login_user_password() >-------------

        }

        //-----------------</ region: Helper-Methods >---------------

        #endregion / Helper-Methods

 

        //--------------</ Class: TokenController >---------------------

    }

}