How the. NET Authorize (Microsoft Foundation permissions Framework) works for Cordova

Source: Internet
Author: User
Tags httpcontext

Recently toss Cordova, hope to develop a B/s project like the development of a set of apps, so that development costs and maintenance costs and learning costs can be minimized;

The choice of Cordova is mainly personal experience limited, do not want to toss the Android and iOS development. Oneself into. NET deep;

And Cordova can be fast app, if not to do high performance requirements of the app (such as the game) is very recommended to use Cordova. Before the survey shows that the hybrid app accounted for about 70% really amazing!

Basically, the server side uses. NET MVC 5; technology is mostly rest API interaction;
The client app mainly uses Cordova to generate JavaScript using typescript, and a lot of Cordova plug-ins such as QR code scanning, positioning inside;

The start of the architecture and the development environment are progressing smoothly, but a recent problem has been identified. Cordova need to call the server side need to authorize the API interface when there is no way to do permissions.
Because there is no cookie storage in the Cordova, and even if there is a cookie can not cross the domain, the web search for the next incredibly received. NET-related solutions; I can only say that Cordova ecology is not very well;
And. NET community of the Cordova is not much better; Can only rely on their own thinking of the problem;

My implementation is also simple, since the client does not support cookies so HTML5 Localstore or sessionstore still support it.
In addition to the jquery asynchronous call when we pass Headers header server side through header header to determine the user information soon, thinking is very simple;

First, from the server side:

To implement your own Authorizeattribute, the code is as follows:

Namespace ..... WebUI.Framework.Security {//<summary>///For mobile Cordova authorization check://</summary> public class Cordova        Authorizeattribute:authorizeattribute {public override void Onauthorization (AuthorizationContext filtercontext)            {var request = FilterContext.RequestContext.HttpContext.Request; if (Request. isauthenticated) {base.                Onauthorization (Filtercontext);            Return            }//Use header to verify Cordova Security//xhr.setrequestheader ("username", "" ");            Xhr.setrequestheader ("Password", "" "); var username = Request.            headers["username"]; var password = Request.            headers["Password"]; if (string.                IsNullOrEmpty (username) | | String. IsNullOrEmpty (password)) {//user information Invalid Filtercontext.result = new Httpunauthorizedjs                Onresult ();            Return  } try {              Here you get the content that the user stores in the database according to your business code.                For performance here you can add cache.                var svc = enginecontext.current.resolve<imemberservice> (); var user = Svc.                GetUserInfo (username, findbytype.byusername); if (user = = null) {//Cannot find user Filtercontext.result = new Httpunauthor                    Izedjsonresult ();                Return } if (user. Status.getvalueordefault (0)! = 1) {//user has been locked Filtercontext.result =                    New Httpunauthorizedjsonresult ();                Return                } var hasher = new Passwordhasher (); var flag = Hasher. Verifyhashedpassword (user.                PasswordHash, password); if (flag = = passwordverificationresult.failed) {//checksum failed Filtercontext .                    Result = new Httpunauthorizedjsonresult ();       Return         } if (string. IsNullOrEmpty (Roles) && string.                IsNullOrEmpty (Users) {//success: return; } if (string. IsNullOrEmpty (Roles) && users.split (new[] {",", ";"}, Stringsplitoptions.removeemptyentries).                 Contains (username, stringcomparer.ordinalignorecase)) {//success: return; } if (!string. IsNullOrEmpty (Roles)) {var userroles = user. Aspnetroles.select (A = a.name).                    ToList ();                    foreach (Var _role in Roles.split (new[] {",", ";"}, Stringsplitoptions.removeemptyentries)) {foreach (var role in userroles) {i F (role.                           Equals (_role, stringcomparison.ordinalignorecase)) {     Success: return;                }}}}} catch { User name error, etc. exception//todo:}//checksum failed: Filtercontext.result = new httpunauthorized        Jsonresult (); }}///<summary>//JSON error///</summary> internal class Httpunauthorizedjsonresult:jsonres            ult {public override void Executeresult (ControllerContext context) {//Avoid redirection after Cordova call Context.            HttpContext.Response.StatusCode = (int) Httpstatuscode.ok;            Data = new {status = (int) httpstatuscode.unauthorized};            Jsonrequestbehavior = Jsonrequestbehavior.allowget; Base.        Executeresult (context); }    }}

  

The server-side code is done. We can add the Cordovaauthorizeattribute attribute header for the Cordova authorization check on our action and controller.

Like what:

[Cordovaauthorize (roles= "Admin")]
Public Contentresult Test (string id)
{

Return Content ("Success");
}

The code for the Cordova client to invoke the server-side API is much simpler to post directly:

       var url = "Server-side address";         $.ajax (URL, {            crossdomain:true,            data: {                rnd:Math.random ()            },            beforesend:function (XHR) {                / /Here the user name and user password are recommended to be stored in Sessionstore.                Xhr.setrequestheader ("username", "user name");                Xhr.setrequestheader ("Password", "User password")            ,            success:function (data, status, req) {                if (data.status && data.status==401) {                    //authorization failed. Then jump to the landing page according to your own business:                }                //Other status will be returned according to your business:             },            error:function (Error) {                alert (json.stringify (Error));            },            method: "GET",// Determine whether post or get            complete:function () {                alert ("complete!") according to your business            ,            timeout:5000        });

Then the tricky problem is solved;
If you consider the security of the client, you can consider password encryption. If you consider that back-end checking is too frequent for database queries, consider using caching appropriately.

I recently self-study Cordova hope that there are like-minded in the garden to explore joint research!
Finally, any questions can be exchanged for communication Thank you!

How the. NET Authorize (Microsoft Foundation permissions Framework) works for Cordova

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.