1

I am working on having native app be able to authenticate to a web api which uses an existing identity db database created from MVC6. I understand this is not a secure way of doing things as per this post. However, until I can figure out how to get IdentityServer3 working with a database I thought I would try a simple web api that authenticates to a database I already created when I built a standard MVC 6 web app. Here is what I did:

Created an asp.net 5 web api from the template and added the following: Settings: appsettings.json I added:

"Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-TestUsers-eaf0c85f-23e4-4603-97ce-b9f49ee1d167;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  },

Startup:

services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApiDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

Models:

public class AppUser : IdentityUser
    {
    }

DBContext:

public class ApiDbContext : IdentityDbContext<AppUser>
    {
    }

Controller:

private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager;
private readonly ILogger _logger;
...
public async Task<IEnumerable<string>> Post([FromBody]LoginModel model)
        {
            if (ModelState.IsValid) { 
                string user = model.userid;
                string passwd = model.password;

                var result = await _signInManager.PasswordSignInAsync(model.userid, model.password, false, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation(1, "User logged in.");
                    return new string[] { user };
                }
                else
                {
                    return new string[] { "Failed" };
                }
            }
            else
            {
                return new string[] { "Incorrect format received"};
            }
        }

However, it bombs at the _signInManager line with the error:

System.NullReferenceException: Object reference not set to an instance of an object.

So apparently _signInManager is Null because I know the model is fine because I am printing the userid and password and they are there.

What am I missing so I can use the signInManager in a web api?

1 Answer 1

0

I went back yet another time to see what was different between the web api and the web app, since the web app auth was working fine. Here is what I added to get it working:

controller needed a constructor:

public AuthController(
            SignInManager<AppUser> signInManager,
            ILoggerFactory loggerFactory)
        {
            _signInManager = signInManager;
            _logger = loggerFactory.CreateLogger<AuthController>();
        }

Which got rid of my other error but produced the following error:

System.InvalidOperationException: No authentication handler is configured to handle the scheme: Microsoft.AspNet.Identity.Application

So after researching that I needed to add to startup: configureservices:

services.AddIdentity<AppUser, IdentityRole>()
                .AddEntityFrameworkStores<ApiDbContext>()
                .AddDefaultTokenProviders();

configure:

app.UseIdentity();

Adding these to the above allowed me to post JSON with userid and password.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.