简体   繁体   English

使用外部PHP API的ASP.net MVC身份验证

[英]ASP.net MVC Authentication using external PHP API

I'm developing an asp.net MVC website with the following requirements: 我正在开发具有以下要求的asp.net MVC网站:

  1. Develop pages for Admin and Users, these pages must be accessed based on logged in user role: Admin or User 为“管理员”和“用户”开发页面,必须根据登录的用户角色访问这些页面:“管理员”或“用户”
  2. The website supports login only, You will call a PHP API which resides on an external website, it returns a JSON as a result that includes id, username, and role (admin, user) 该网站仅支持登录,您将调用一个驻留在外部网站上的PHP API,其返回的JSON结果包括ID,用户名和角色(管理员,用户)
  3. You may save the result of returned json on a session to be used in your pages but this data must disappear after logout or session expiration. 您可以将返回的json的结果保存在要在您的页面中使用的会话中,但是此数据必须在注销或会话到期后消失。

I know how to develop the calling HTTP stuff and processing json, but I'm not familiar with authorization and authentication stuff, nor with using membership providers, I searched a lot and at first I thought of using SimpleMembership but I found that won't work since it depends on SQL queries and in my case I'm not going to use any type of databases. 我知道如何开发调用HTTP的内容和处理json,但是我不熟悉授权和身份验证的内容,也不熟悉使用成员资格提供程序,因此进行了很多搜索,起初我想使用SimpleMembership,但是我发现不会因为它取决于SQL查询,所以可以工作,在我的情况下,我将不使用任何类型的数据库。

I heard about asp.net identity but I'm not sure how to use it or if it's for my case or not, I searched again and I couldn't find any resource to help me achieve authentication and authorization for my case 我听说过asp.net身份信息,但是我不确定如何使用它,或者是否适合我的情况,我再次搜索,找不到任何资源来帮助我实现我的情况的身份验证和授权

I'm asking for your help to help me out and point me in the right direction 我正在寻求您的帮助,以帮助我并指出正确的方向

Thank you for your help 谢谢您的帮助

There is an example of using OAuth separated http auth API: http://www.asp.net/web-api/overview/security/external-authentication-services 有一个使用OAuth分隔的HTTP身份验证API的示例: http : //www.asp.net/web-api/overview/security/external-authentication-services

Yes, this example depends on some specified http API.. But in case when you have some another JSON/XML RPC API you can try to create your own feature like a: 是的,此示例取决于某些指定的http API。但是,如果您有其他JSON / XML RPC API,则可以尝试创建自己的功能,例如:

public class ExternalAuthAPIClient {
    public User Auth(string username, string password) { .... }
}

And use it in your AuthController in the method Login 而在方法登录使用它在你的AuthController

BUT! 但! This approach requires a lot of side changes.. where to store your user.. then create custom AuthenticateAttribure ... etc. 这种方法需要进行很多改动。.在哪里存储用户..然后创建自定义的AuthenticateAttribure ...等。

The better solution is to create oAuth supported API on your PHP side and use it with ASP.NET Identity. 更好的解决方案是在PHP端创建支持oAuth的API,并将其与ASP.NET Identity结合使用。

I finally found a solution,I didn't need to use any membership providers since my website supports only login and via an API,I wrote the following code,this one is in AccountController : 我终于找到了一个解决方案,因为我的网站仅支持登录并通过API支持,所以不需要使用任何成员资格提供程序,我编写了以下代码,该代码位于AccountController

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel login, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            ViewBag.Error = "Form is not valid; please review and try again.";
            return View(login);
        }

        //Call external API,check if credentials are valid,set user role into userData
        string userData="Admin";

        var ticket = new FormsAuthenticationTicket(
        version: 1,
        name: login.Username,
        issueDate: DateTime.Now,
        expiration: DateTime.Now.AddSeconds(HttpContext.Session.Timeout),
        isPersistent: false,
        userData: userData);

        var encryptedTicket = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        HttpContext.Response.Cookies.Add(cookie);

        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", userData);

    }

Then decorate admin/user controller with Authorize attribute like this: 然后使用Authorize属性装饰管理员/用户控制器,如下所示:

[Authorize(Roles = "admin")]
public class AdminController : Controller

Then add the following code in Global.asax : 然后在Global.asax添加以下代码:

        public override void Init()
        {
            base.PostAuthenticateRequest += Application_PostAuthenticateRequest;
        }
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                var decodedTicket = FormsAuthentication.Decrypt(cookie.Value);
                var roles = decodedTicket.UserData;

                var principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
                HttpContext.Current.User = principal;
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.Net MVC - 使用外部URL形成身份验证 - ASP.Net MVC - forms authentication using an external URL 在ASP.NET MVC中添加外部身份验证 - Adding External Authentication in ASP.NET MVC 使用Asp.net MVC 6和Web Api进行身份验证 - Authentication with Asp.net MVC 6 and Web Api ASP.NET Web API + ASP.NET MVC身份验证 - ASP.NET Web API + ASP.NET MVC Authentication 如何在ASP.NET MVC Web Api上使用外部身份验证服务 - How to use external authentication services on a ASP.NET MVC Web Api 针对外部Web服务的ASP.NET MVC Forms身份验证 - ASP.NET MVC Forms authentication against external web service ASP.NET MVC基于声明的用户使用“外部”身份验证 - ASP.NET MVC claims-based users with “external” authentication 使用Asp.Net MVC针对Active Directory用户的内部和外部身份验证 - Internal and External Authentication against Active Directory users using Asp.Net MVC 在 ASP.NET MVC 中使用外部身份验证获取所有服务的用户配置文件照片 - Get User Profile Photo For All Services using External Authentication in ASP.NET MVC ASP.NET核心Web API和Angular Client中的外部身份验证 - External authentication in ASP.NET core Web API and Angular Client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM