ASP.NET CORE WEBAPI Custom Filter <> Bearer Token

Anonymous
2023-09-23T04:54:58.3533333+00:00

Seeing this article http://dotnet-concept.com/Tutorials/2020/1/5800875/Web-API-Tutorial-Csharp-Part-3-Implementing-basic-Bearer-authentication-in-Web-API-application

I created a custom filter CustomAuthenticationAttribute , I am trying use Custom filter in VisitsController.cs

Get but I am facing error.

https://github.com/KalyanAllam/VisitsApi

    // GET: api/Visits
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Visit>>> GetVisits()
        {
          if (_context.Visits == null)
          {
              return NotFound();
          }
            return await _context.Visits.ToListAsync();
        }

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,505 questions
0 comments No comments
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,601 Reputation points Microsoft Vendor
    2023-09-25T07:14:29.3366667+00:00

    Hi @Dotnet Engineer,

    According to the github codes you have shared, I found you follow the asp.net web api article to use the AuthorizationFilterAttribute which will not work inside asp.net core.

    Inside asp.net core, normally. we will use authentication middleware with the Asp.net Core web api with JWT authentication or else.

    If you still want to use CustomAuthenticationAttribute, I suggest you could consider using the IAuthorizationFilter.

    Details, you could refer to below codes:

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //check access and put your own logic to get the username and password
            if (IsAuthorizedUser("test", "pass"))   
            {
                //all good, add optional code if you want. Or don't
                // Create a new claim
                var customClaim = new Claim("CustomClaimType", "CustomClaimValue");
    
                // Add the claim to the user's identity
                ((ClaimsIdentity)context.HttpContext.User.Identity).AddClaim(customClaim);
    
            }
            else
            {
                //DENIED!
                //return "ChallengeResult" to redirect to login page (for example)
                context.Result = new UnauthorizedObjectResult("Unauth");
            }
        }
    

    If you want to read the claim inside the controller, you could refer to below codes:

            public async Task<ActionResult<IEnumerable<Visit>>> GetVisits()
            {
                //if (_context.Visits == null)
                //{
                //    return NotFound();
                //}
                //  return await _context.Visits.ToListAsync();
                //get the claim value
              var re =   Request.HttpContext.User.Claims.Where(x => x.Type == "CustomClaimType").FirstOrDefault().Value;
    
                return new List<Visit>() { new Visit {  Visitid=1 } };
            }
    

    Result:1


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


3 additional answers

Sort by: Most helpful
  1. Krew Noah 500 Reputation points
    2023-09-23T10:07:00.7566667+00:00

    Based on the information available from the provided URLs, here is how you can secure the API using JWT:

    1. Install JWT Libraries: In the VisitsApi project, install the necessary JWT libraries using NuGet, such as System.IdentityModel.Tokens.Jwt.
    2. Configure JWT: In the Startup.cs file of the VisitsApi project, configure JWT authentication in the ConfigureServices method by adding authentication services and specifying JWT as the default scheme.
    3. Generate Tokens: Create a method to generate JWT tokens. This method should take user credentials, validate them, and return a JWT token upon successful validation.
    4. Protect API Endpoints: Decorate the API endpoints in the VisitsController with the [Authorize] attribute to ensure that they are secured and can only be accessed with a valid JWT token.
    5. Client Side Changes: In the PatientPortal project, modify the Visitsnew controller to include code for obtaining a JWT token from the VisitsApi and attach this token to the HTTP headers for subsequent API requests.
    6. Test: Finally, test the secured API endpoints using tools like Postman by including the generated JWT token in the Authorization header.

    Please note that the actual implementation might require additional steps and adjustments based on the specific requirements and existing codebase.

    0 comments No comments

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  3. Bruce (SqlWork.com) 64,001 Reputation points
    2023-09-23T15:49:31.0833333+00:00

    You don’t specify the authentication needs for the api. Does it want a user token, or an application token? That is, is the user authorized to call the api, or is the application.

    also you need an authentication server. We you planning on a commercial like azure, aws or google, or hosting one?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.