C# Microsoft Authentication Get logged user from controller

爱⌒轻易说出口 提交于 2019-12-24 22:01:50

问题


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


回答1:


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());

        }
    }


来源:https://stackoverflow.com/questions/48680946/c-sharp-microsoft-authentication-get-logged-user-from-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!