Reputation: 87
I have this asp.net mvc project that uses cookie based authentication and i added a web api endpoint to it following this stackoverflow thread. It worked like a charm but when i decorate the api controller with an [Authorize]
, the requests fail to authenticate even when I provide username and password in postman. I would like the ApiController
to allow token based authentication while keeping the cookie based authentication in the mvc part. Thanks in advance for any help.
Upvotes: 0
Views: 2940
Reputation: 1076
I am assuming you have separate projects in your applications for Web API and MVC.
In the Web API project, if you create a project with authentication as 'Individual User Accounts', it automatically adds OAuth files and related code to the project. If you create a project with No Authentication, you have to add the Owin Middleware to access OAuth feature.
You will be looking at these settings in Statup.Auth.cs file.
On the MVC side, the default authentication is cookie based. To call your Web APIs, you have to use HTTPClient. This should return a token which you can add to your DefaultRequestHeaders like this (I am using this approach).
Other option is to store the token in Sessions or add it to the Authentication Cookie.
I hope you will find this helpful.:)
Upvotes: 1
Reputation: 278
In Visual Studio 2019 when you create a Web API project template and select Individual User Accounts for Authentication, the vs implement a Token-Based Authentication for you very similar to this Article. the only difference is that the article uses a legacy table for storing user data and Microsoft's code uses the famous AspNetUsers table. I strongly recommend you to follow the article and at the end replace the GrantResourceOwnerCredentials method in the ApplicationOAuthProvider file with the following code:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
Upvotes: 0