0

So I have an Angular and C# Web API 2 app that uses Microsoft Authentication (msal.js) for the login. Now I'm trying to save data and I need the details of the current logged user. Is there a way to get the logged user from the C# Controller?

I can do this in Angular, but I think it's not secured to do it from the client side so I was thinking if maybe there was a way that the backend knows who's the logged user.

Thanks in advance!

EDIT

Startup.Auth.cs

  var tvps = new TokenValidationParameters
  {
    ValidAudience = "the id given from Microsoft Graph Registration", //xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    ValidateIssuer = false,
  };

  app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
  {
    AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"))
  });

frontend-login.ts

let userAgentApp = new UserAgentApplication(clientId, null,
    (errorDes: any, token: any, error: any, tokenType: any) => {
        userAgentApp.acquireTokenSilent(["user.read"]).then((token: string) => {});
    }, { redirectUri: 'http://localhost:port/signin-microsoft' });
userAgentApp.loginPopup(["user.read"]).then((token: string) => {
    //store the token and redirect to home page
});

EDIT

I am using it when accessing the API like this:

this.headers.append('Authorization', 'Bearer ' + sessionStorage.getItem('token'));
this.http.get(`${this.url}`, { headers: this.headers })
  .map((response: Response) => { return response.json() })

FINAL EDIT

I posted another question regarding this and this problem was answered there. I am posting the link below in case someone needs it in the future:

C# Web API 2 & Angular - Microsoft Account Authentication

3
  • 1
    Could you try var user = User.Identity Commented Feb 8, 2018 at 9:02
  • Your comment //store the token and redirect to home page suggests that you are storing the token somewhere for later use. Can you post some code showing how you are using the stored token when contacting your web api later on? Commented Feb 14, 2018 at 15:26
  • @Tewr updated my question. Thanks Commented Feb 16, 2018 at 6:02

1 Answer 1

2

In Web Api, you need to read the Bearer Token. Here is a tutorial on the subject as a whole, but the gist of it is to use UseOAuthBearerAuthentication in your startup class when setup up the owin pipeline, this will enable access in controllers when calling RequestContext.Principal.

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);
        //Rest of code is here;
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }
    }
Sign up to request clarification or add additional context in comments.

6 Comments

Completely missed the WebApi part.... Not enough coffee this morning, good answer :)
Well reading your comment made me re-read and see a mistake in my answer. I'll just go ahead and blame insufficient coffee too, convenient.
Haha why not :p
I have set my Startup for Microsoft Authentication and i'm using msal.js. But the RequestContext.Principal.Identity.Name returns null. Is there another where I can get the data? In frontend I can get it using the UserAgentApplication.getUser(), but I wanted to do it in MVC if possible.
@Jed: Might be an error or inconsistency in your setup code. You should post your setup code both client side and server side! Your startup.cs as well as your js for setting up the Bearer token in callbacks, does it look like this?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.