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:
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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.