/// <summary> /// Parses a string into an instance of JwtSecurityToken. /// /// If the 'jwtToken' is in JWE Compact Serialization format, only the protected header will be deserialized. Use ParseToken() to obtain the payload. /// /// JwtSecurityToken see: https://docs.microsoft.com/en-us/dotnet/api/system.identitymodel.tokens.jwt.jwtsecuritytoken?view=azure-dotnet /// </summary> /// <param name="input">Parameters for the token parsing.</param> /// <returns>JwtSecurityToken</returns> public static dynamic ReadToken([PropertyTab] ReadTokenInput input) { if (input == null) { return(null); } var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); return(handler.ReadJwtToken(input.JWTToken)); }
public static void ReadToken(string jwtToken) { // To Read Claims on Api Controller //var jwt = Request.Headers.Authorization.Parameter; var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); System.IdentityModel.Tokens.Jwt.JwtSecurityToken token = handler.ReadJwtToken(jwtToken); IEnumerable <Claim> claims = token.Claims.ToList(); string id = token.Claims.FirstOrDefault(x => x.Type == "id").Value; string role = token.Claims.FirstOrDefault(x => x.Type == "role").Value; string Compcode = token.Claims.FirstOrDefault(x => x.Type == "Compcode").Value; string Bracode = token.Claims.FirstOrDefault(x => x.Type == "Bracode").Value; }
public static ClaimsPrincipal ValidateJwtToken(string jwtToken) { var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true }; var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(jwtToken)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials( securityKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(signingCredentials); var payload = new JwtPayload { { "access_token", response }, { "scope", "Read Data Write Data" }, //{ "created","1510553155114"}, //{"jti","2640942c-892c-409a-9ca8-959a538c2128"}, }; var secToken = new JwtSecurityToken(header, payload); var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var tokenString = handler.WriteToken(secToken); var readToken = handler.ReadJwtToken(generatedToken); var rawHeader = readToken.RawHeader; var headers = Base64UrlEncoder.Decode(rawHeader); var myClaims = readToken.Claims; var claims = Base64UrlEncoder.Decode(myClaims.ToString()); //var payload = header + "." + claims; //var signature = Base64UrlEncoder.Decode(HMACSHA256(payload, CLIENT_SECRET)); //var encodedJWT = payload + "." + signature; return(null); }
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "AB Project API", Version = "v1" }); }); IdentityBuilder builder = services.AddIdentityCore <User>(opt => { opt.Password.RequireDigit = false; opt.Password.RequiredLength = 4; opt.Password.RequireNonAlphanumeric = false; opt.Password.RequireUppercase = false; }); builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services); builder.AddEntityFrameworkStores <DataContext>(); builder.AddRoleValidator <RoleValidator <Role> >(); builder.AddRoleManager <RoleManager <Role> >(); builder.AddSignInManager <SignInManager <User> >(); // builder.AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, // ValidIssuer = Configuration.GetSection("AppSettings:Issuer").Value, ValidAudience = Configuration.GetSection("AppSettings:Issuer").Value, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AppSettings:Key").Value)), }; //Audience = "...", //Authority = "...", options.Events = new JwtBearerEvents { OnTokenValidated = context => { // Add the access_token as a claim, as we may actually need it var accessToken = context.SecurityToken as JwtSecurityToken; //ClaimsPrincipal currentUser = _contextAccessor.HttpContext.User ; //var jwt = "(the JTW here)"; var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var token = handler.ReadJwtToken(accessToken.RawData); if (accessToken != null) { ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity; if (identity != null) { //identity.AddClaim(new Claim("access_token", accessToken.RawData)); foreach (var claim in token.Claims) { if (!identity.HasClaim(claim.Type, claim.Value)) { identity.AddClaim(claim); } } } } return(Task.CompletedTask); } }; }); services.AddAuthorization(options => { options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); options.AddPolicy("ModeratePhotoRole", policy => policy.RequireRole("Admin", "Moderator")); options.AddPolicy("VipOnly", policy => policy.RequireRole("VIP")); }); services.AddMvc(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(opt => { opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = X - Forwarded - Host | ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; // Only loopback proxies are allowed by default. // Clear that restriction because forwarders are enabled by explicit // configuration. options.KnownNetworks.Clear(); options.KnownProxies.Clear(); }); services.AddCors(); services.AddAutoMapper(typeof(IRepositoryBase <>).Assembly); services.AddAutoMapper(typeof(IUserService).Assembly); services.AddHttpContextAccessor(); //services.AddClaimsPrincipalFactory<CustomClaimsPrincipalFactory>(); //services.AddScoped<IUserClaimsPrincipalFactory<User>, CustomUserClaimsPrincipalFactory>(); //services.AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>(); //services.AddAutoMapper(typeof(DatingRepository).Assembly); //services.AddTransient<Seed>(); //Newly Added by Ibrahim Zakariyau services.AddScoped(typeof(IRepositoryBase <>), typeof(RepositoryBase <>)); services.AddScoped <IAccessLevelService, AccessLevelService>(); services.AddScoped <ICommodityService, CommodityService>(); services.AddScoped <IFarmerVarificationStatusService, FarmerVarificationStatusService>(); services.AddScoped <IFarmOwnershipTypeService, FarmOwnershipTypeService>(); services.AddScoped <IGenderService, GenderService>(); services.AddScoped <IIDTypeService, IDTypeService>(); services.AddScoped <ILgaService, LgaService>(); services.AddScoped <IMaritalStatusService, MaritalStatusService>(); services.AddScoped <INationalityService, NationalityService>(); services.AddScoped <IStateService, StateService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IFarmerService, FarmerService>(); services.AddScoped <IEOPService, EOPService>(); services.AddScoped <IEOPTypeService, EOPTypeService>(); services.AddScoped <IEOPUnitService, EOPUnitService>(); services.AddScoped <IInventoryService, InventoryService>(); //TO be remove services.AddScoped <LogUserActivity>(); }