asp.net core - Adding bearer token to dependency injection -
i have identity server 4 setup , mvc client redirects identity server , can authenticate user.
now if want call me api can following. have pass access token method calls api.
controller
public class usercontroller : controller { public iactionresult index() { var accesstoken = await httpcontext.authentication.gettokenasync("access_token"); var user = _userservice.get(accesstoken); return view(); } }
service
public async task<user> get(string accesstoken) { var result = await _baseurl.appendpathsegment("/v1/user/get").withoauthbearertoken(accesstoken).getjsonasync<user>(); return result; }
what prefer add access token dependency injection pipeline can use global in class , not have worry passing around every call.
public class userservice { private readonly string _bearertoken {get;set;} public userservice(ioptions<usersettings> usersettings) { _bearertoken = usersettings.value.bearertoken; } public async task<user> get(string accesstoken) { var result = await _baseurl.appendpathsegment("/v1/user/get").withoauthbearertoken(_bearertoken ).getjsonasync<user>(); return result; } }
i'm not entirely sure if right way of doing it? if i'm not sure how. thought maybe part of ontokenvalidated event.
app.useopenidconnectauthentication(new openidconnectoptions { // other settings here events = new openidconnectevents { ontokenvalidated = context => { var accesstoken = context.securitytoken jwtsecuritytoken; if (accesstoken != null) { // on here add accesstoken ioptions<usersettings> } return task.completedtask; } }, }
is ontokenvalidated event right place it? maintain token between page loads or there other place should doing this? how go adding accesstoken ioptions or equivalent?
thanks
m
after more investigating found way it. using answer here
using simple injector in mvc6 cookie auth
and looking how
https://github.com/dotnet-architecture/eshoponcontainers
did created itokenmanager , tokenmanager , had access ihttpcontextaccessor through di allows me token.
Comments
Post a Comment