3

I have two .net core 2.2 projects; the first one is an MVC project which is like presentation layer that user can login and the other Web API that handles DB operations. I want to handle login request in Web API and return the login result to MVC project by using MVC Core Identity. My DbContext is in the Web API project. Is there anyway to create identity cookie according to result of Web API request?

1
  • You might be able to do that with Request.GetOwinContext().Authentication.SignIn(). Dec 2, 2019 at 10:54

4 Answers 4

2
+50

In this situation the authentication should be handled with an access token rather than a cookie.

For your Web API, implement Resource Owner Password Credentials grant type of OAuth2 protocol with the help of IdentityServer 4 library. At the end you should be able to get an access token from the API in exchange of login credentials.

For your MVC project, create a table to store token-sessid pairs, so when the MVC application gets an access token from the API during a session, it will save them in the table. For the subsequent requests the MVC app will get the token from the table (by using the sessid) and use it to access the Web API.

0

First in the startup class of your MVC on the server side add->

 services.AddAuthentication(options => { 
        options.DefaultScheme = "Cookies"; 
    }).AddCookie("Cookies", options => {
        options.Cookie.Name = "auth_cookie";
        options.Cookie.SameSite = SameSiteMode.None;
        options.Events = new CookieAuthenticationEvents
        {                          
            OnRedirectToLogin = redirectContext =>
            {
                redirectContext.HttpContext.Response.StatusCode = 401;
                return Task.CompletedTask;
            }
        };                
    });

Then in your Login Controller of MVC

[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
    if (!IsValidUsernameAndPasswod(username, password))
        return BadRequest();

    var user = GetUserFromUsername(username);

    var claimsIdentity = new ClaimsIdentity(new[]
    {
        new Claim(ClaimTypes.Name, user.Username),
        //...
    }, "Cookies");

    var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
    await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);

    return NoContent();
}

Notice that we are referencing the “Cookies” authentication scheme we’ve defined in Startup.cs.

Afterwards on your web api->

CookieContainer cookieContainer = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler
{
    CookieContainer = cookieContainer
};
handler.CookieContainer = cookieContainer;
var client = new HttpClient(handler);

var loginResponse = await client.PostAsync("http://yourdomain.com/api/account/login?username=theUsername&password=thePassword", null);
if (!loginResponse.IsSuccessStatusCode){
    //handle unsuccessful login
}

var authCookie = cookieContainer.GetCookies(new Uri("http://yourdomain.com")).Cast<Cookie>().Single(cookie => cookie.Name == "auth_cookie");

//Save authCookie.ToString() somewhere
//authCookie.ToString() -> auth_cookie=CfDJ8J0_eoL4pK5Hq8bJZ8e1XIXFsDk7xDzvER3g70....

This should help you achieve your Task. Of course change values based on your requirements, but thus code would be a good reference point.

Also add the required code to set cookies from your web api application. Hope it helps!

0

I am not sure I’m fully up to speed with your problem statement. I am assuming that you’re after some sort of mechanism that enables a user to pass their identity all the way from web client to your DbContext. I also assume you then don’t really authenticate users on the MVC app and basically proxy their requests onto WebAPI.

If so, you might want to consider crafting a JWT (preferably, signed) token as your WebAPI response and then storing it on the client (I guess cookie is a good enough mechanism).

Then MVC project will naturally get the token by virtue of Session State and all you will have to do would be to pass it along with every WebAPI request you make.

0

1. Only two services

If your system has only two services (front and back) you could use Cookies for all your authentication schemes in your front and consume your api for user validation.

Implement the login page in your web app and verify the users from your login action method (post) calling a backend endpoint (your api) where you can validate the credentials against your database. Note that you do not need to publish this endpoint in internet.

ConfigureServices:

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = "/auth/login";
    options.LogoutPath = "/auth/logout";
});

AuthController:

[HttpPost]
public IActionResult Login([FromBody] LoginViewModel loginViewModel)
{
    User user = authenticationService.ValidateUserCredentials(loginViewModel.Username, loginViewModel.Password);

    if (user != null)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.Role, user.Role),
            new Claim(ClaimTypes.Email, user.Email)
        };
        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var principal = new ClaimsPrincipal(identity);

        await HttpContext.SignInAsync(principal);

        return Redirect(loginViewModel.ReturnUrl);
    }

    ModelState.AddModelError("LoginError", "Invalid credentials");
    return View(loginViewModel);
}

2. OAuth2 or OpenId Connect dedicated server

But if you want to implement your own authorization service or idenitity provider which can be used by all your applications (both front and back) I would recommend creating your own server with a standard like OAuth2 or OpenId. This service should be dedicated exclusively for this purpose.

If your services are net core you could use IdentityServer. It is a middleware that is certified by OpenIdConnect and is very complete and extensible. You have extensive documentation and it's easy to implement for both OAuth2 and OpenId. You could add your dbContext to use your user model.

Your Web app ConfigureServices:

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
    options.SignInScheme = "Cookies";
    options.Authority = "https://myauthority.com";
    options.ClientId = "client";
    options.ClientSecret = "secret";
    options.SaveTokens = true;
    options.Scope.Clear();
    options.Scope.Add("myapi");
    // ...
}

Your Identity Provider ConfigureServices:

services.AddIdentityServer()
    .AddInMemoryClients(Config.GetClients())
    .AddInMemoryApiResources(Config.GetApis())
    .AddInMemoryIdentityResources(Config.GetIdentityResources())
    .AddConfigurationStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    .AddDeveloperSigningCredential();

In this way your fronts would request access to the scopes necessary to access the apis. The front would receive an access token with this scope (if this client is allowed for the requested scopes). These apis in turn could validate the access token with a validation middleware like the following:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://myauthority.com";
        options.Audience = "myapi";
    });

3. Custom remote handler

If you still prefer to implement something remote by yourself you can implement your custom RemoteAuthenticationHandler. This abstract class helps you to redirect to a remote login service (your api) and handles results on callback redirections with the authorization result in your web app. This result is used to populate the user ClaimsPrincipal and if you configure your web app authentication services in this way you could maintain the user session in a Cookie:

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "CustomScheme";
})
.AddCookie()
.AddRemoteScheme<CustomRemoteAuthenticationOptions, CustomRemoteAuthenticationHandler>("CustomScheme", "Custom", options =>
{
    options.AuthorizationEndpoint = "https://myapi.com/authorize";
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.SaveTokens = true;
    options.CallbackPath = "/mycallback";
});

You can see the remote handlers OAuthHandler or OpenIdConnectHandler as a guide to implement yours.

Implementing your own handler (and handler options) could be cumbersome and insecure, so you should to consider the first options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.