vidgarga
vidgarga

Reputation: 330

In net core use a service within your own class and call the class using new class()

I have created a class to validate my own token. Within this class I need to use a service, which I have previously added in the startup.cs with services.AddScoped. how can I do it ?

x.SecurityTokenValidators.Add(new DynamicKeyJwtValidationHandler());

Inside the DynamicKeyJwtValidationHandler class I need to use a service.

public class DynamicKeyJwtValidationHandler : JwtSecurityTokenHandler, ISecurityTokenValidator
    {
        public SecurityKey GetKeyForClaimedId(string claimedId)
        {
            throw new NotImplementedException();
        }

        public override ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            ClaimsPrincipal cp = new ClaimsPrincipal();
            validatedToken = null;
            try
            {
                cp = base.ValidateToken(token, validationParameters, out validatedToken);
            } catch (Exception) {}

            return cp;
        }
    }

Upvotes: 1

Views: 403

Answers (1)

Samuel Middendorp
Samuel Middendorp

Reputation: 662

Use dependency injection in the constructor of the class

public class DynamicKeyJwtValidationHandler : JwtSecurityTokenHandler, ISecurityTokenValidator
    {
        private readonly YourService _service
        public DynamicKeyJwtValidationHandler(YourService service){
             _service = service
        }
        public SecurityKey GetKeyForClaimedId(string claimedId)
        {
            throw new NotImplementedException();
        }

        public override ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            ClaimsPrincipal cp = new ClaimsPrincipal();
            validatedToken = null;
            try
            {
                cp = base.ValidateToken(token, validationParameters, out validatedToken);
            } catch (Exception) {}

            return cp;
        }
    }

Upvotes: 1

Related Questions