我正在编写我的第一个Azure移动应用程序,我想实现"自定义身份验证"针对现有网站用户数据库。
在现有的ASP.Net网站上,我有通常的dbo.AspNetUsers表等。
我无法弄清楚如何调用此现有网站来验证用户身份。
我有以下代码,但我失去了如何让isValidAssertion函数与Axure Mobile App中的现有用户数据库通信。
这相当于网站上的这一行......
ApplicationSignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
所以,我有以下代码:
private static bool isValidAssertion(JObject assertion)
{
// this is where I want to call the existing user database
// this is how it's done in the MVC website
//ApplicationSignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
return true;
}
public IHttpActionResult Post([FromBody] JObject assertion)
{
if (isValidAssertion(assertion)) // user-defined function, checks against a database
{
JwtSecurityToken token = AppServiceLoginHandler.CreateToken(new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, (string)assertion["username"]) },
mySigningKey,
myAppURL,
myAppURL,
TimeSpan.FromHours(24));
return Ok(new LoginResult()
{
AuthenticationToken = token.RawData,
User = new LoginResultUser() { UserId = (string)assertion["username"] }
});
}
else // user assertion was not valid
{
return ResponseMessage(Request.CreateUnauthorizedResponse());
}
}
有人能指出我正确的方向吗?
答案 0 :(得分:0)
您需要使用Asp.Net Identity
。
基本上,您需要创建BaseApiController
才能首先获得OWIN
上下文:
public class BaseApiController : ApiController
{
private ApplicationUserManager _appUserManager = null;
protected ApplicationUserManager AppUserManager
{
get
{
return _appUserManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
}
}
然后在您的自定义身份验证控制器中需要继承BaseApiController
:
[MobileAppController]
public class CustomAuthController : BaseApiController
{
private static bool isValidAssertion(JObject assertion)
{
var username = assertion["username"].Value<string>();
var password = assertion["password"].Value<string>();
//Validate user using FindAsync() method
var user = await this.AppUserManager.FindAsync(username, password);
return (user != null);
}
}
您还需要在OWIN
中初始化Startup class
上下文:
[assembly: OwinStartup(typeof(UPARMobileApp.Startup))]
namespace UPARMobileApp
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOWinContext(app);
ConfigureMobileApp(app);
}
}
}
public static void ConfigureOWinContext(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
}
有关如何设置ApplicationDbContext
,ApplicationUserManager
和OWIN配置的详细信息,请参阅此处:
http://bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/