C#Microsoft身份验证从控制器获取登录用户

时间:2018-02-08 08:33:32

标签: c# angular msal

所以我有一个Angular和C#Web API 2应用程序,它使用Microsoft身份验证(msal.js)进行登录。现在我试图保存数据,我需要当前登录用户的详细信息。有没有办法从C#Controller获取登录用户?

我可以在Angular中执行此操作,但我认为从客户端执行此操作并不安全,因此我想是否有后端知道谁是已登录用户的方式。

提前致谢!

修改

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

修改

我在访问这样的API时使用它:

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

最终编辑

我发布了另一个关于此的问题,这个问题在那里得到了回答。我发布以下链接以防将来有人需要它:

C# Web API 2 & Angular - Microsoft Account Authentication

1 个答案:

答案 0 :(得分:2)

在Web Api中,您需要阅读Bearer Token。 here是一个关于这个主题的教程,但它的要点是在设置owin管道时在你的启动类中使用UseOAuthBearerAuthentication,这将在调用{{3时启用控制器中的访问权限}}

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

        }
    }