Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access my current user using IdentityServer4?

I'm trying to build a SPA web app + IdentityServer4 + ASPNET Core + ASPNET Core Identity. I've followed the quickstarts on the Identityserver documentation and its really great. I'm more interested the quickstart Identity Server Quickstart with JS Client

I've followed it and so far so good. Now I've added some fields and related tables to my User, like so:

app_user

This is the Solution Explorer

solution_explorer

I would like to create a page that displays my user and its related tables/fields. (Basically, my question is, how do I access my current user and expose an API for my JS client to consume)

How do I achieve that? (All described points below I just read it online and I'm not sure how to implement it)

  • Should I store my user in a session? Then access it from there?
  • Should I use the connect/userinfo endpoint?

Please advise.

like image 755
Boy Pasmo Avatar asked Mar 11 '23 21:03

Boy Pasmo


1 Answers

The idea of IdentityServer is to separate concept of User Identity. In simple words, it means that your web API shouldn't/wouldn't have access to the database where users are stored.

Everything related to the user identity that is nessaccary in web API should be included in access token granted by IdentityServer. ( For example in claims)

In your example you can remove Points and Wallets fields from ApplicaionUser and create addition table for storing them, like this:

public class UserInfo
{
    public string UserSubject { get; set; }
    public int Points { get; set; }
    public ICollection<Wallet> Wallets { get; set; }
}

If you need something related to User Identity you can get it from claims like this:

[Authorize]
public ActionResult SomeAction()
{
    var identity = (ClaimsIdentity)User.Identity;
    IEnumerable<Claim> claims = identity.Claims;
    ...
}

If you need Points and/or Wallets of a user, you can get sub claim from these claims and query your database for it.

It also means that you need to store Points and Wallets by user subject.

like image 102
bot_insane Avatar answered Mar 24 '23 14:03

bot_insane