Horje
DotNet web Api Token based Authentication Code Example
DotNet web Api Token based Authentication
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using WebApplication.Models;
namespace WebApplication.JwtHelpers {
    public static class JwtHelpers {
        public static IEnumerable < Claim > GetClaims(this UserTokens userAccounts, Guid Id) {
            IEnumerable < Claim > claims = new Claim[] {
                new Claim("Id", userAccounts.Id.ToString()),
                    new Claim(ClaimTypes.Name, userAccounts.UserName),
                    new Claim(ClaimTypes.Email, userAccounts.EmailId),
                    new Claim(ClaimTypes.NameIdentifier, Id.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.UtcNow.AddDays(1).ToString("MMM ddd dd yyyy HH:mm:ss tt"))
            };
            return claims;
        }
        public static IEnumerable < Claim > GetClaims(this UserTokens userAccounts, out Guid Id) {
            Id = Guid.NewGuid();
            return GetClaims(userAccounts, Id);
        }
        public static UserTokens GenTokenkey(UserTokens model, JwtSettings jwtSettings) {
            try {
                var UserToken = new UserTokens();
                if (model == null) throw new ArgumentException(nameof(model));
                // Get secret key
                var key = System.Text.Encoding.ASCII.GetBytes(jwtSettings.IssuerSigningKey);
                Guid Id = Guid.Empty;
                DateTime expireTime = DateTime.UtcNow.AddDays(1);
                UserToken.Validaty = expireTime.TimeOfDay;
                var JWToken = new JwtSecurityToken(issuer: jwtSettings.ValidIssuer, audience: jwtSettings.ValidAudience, claims: GetClaims(model, out Id), notBefore: new DateTimeOffset(DateTime.Now).DateTime, expires: new DateTimeOffset(expireTime).DateTime, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256));
                UserToken.Token = new JwtSecurityTokenHandler().WriteToken(JWToken);
                UserToken.UserName = model.UserName;
                UserToken.Id = model.Id;
                UserToken.GuidId = Id;
                return UserToken;
            } catch (Exception) {
                throw;
            }
        }
    }
}




Csharp

Related
textbox gotfocus wpf Code Example textbox gotfocus wpf Code Example
mvc dotnet core how does the view pass parameters to controler Code Example mvc dotnet core how does the view pass parameters to controler Code Example
How to execute a script after the c# function executed Code Example How to execute a script after the c# function executed Code Example
run a command line from vb.net app Code Example run a command line from vb.net app Code Example
asp net route attribute vs httpget Code Example asp net route attribute vs httpget Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
10