0

I have an authentication attribute in C#

public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter
{
    public string Realm { get; set; }
    public bool AllowMultiple => false;
    public User User { get; set; }

    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        //authentication stuff
        this.User = GetUserFromDB();
       //more code
    }
.... more code

And I use this to authenticate in a web api controller:

[Authorize]
[JwtAuthentication]
public class AccesosController : ApiController
{
   public IHttpActionResult DoSomethingAuthenticated(){
       //how to get the user from the [JwAuthentication] attribute?
   }
}

How can I get the User property from the attribute in the method? I need this property because it has some other info that I need to process some other info in my method.

I know that In the token I can get the user id and query the object to the database but I don't want to do that because I will repeat code (the user is queried in the attribute) and I need to use the user's information in every method on my app.

I hope I have explained myself and sorry for my bad english

Thanks in advance :)

oware
  • 626
  • 9
  • 19
  • You can also store the additional info about the user in as Claims after you authenticate the user. Claims for the currently authenticated user can be accessed in your action method. – Charanraj Golla Feb 03 '18 at 02:41

1 Answers1

0

You can access the attributes applied to a class using reflection:

User user = GetType().GetCustomAttribute<JwtAuthenicationAttribute>()?.User;

The following will also give you an IEnumerable of the custom attributes on your class:

GetType().GetCustomAttributes()

I would add that using an attribute like this does not seem like a great use case, more on that here

ASutherland
  • 77
  • 1
  • 8