ANGULARJS+WEBAPI2 cross-domain Basic authentication Authorization (i)

Source: Internet
Author: User



Today's apps, combined with a mix of front-end frameworks and HTML5, are already flourished. Among them Ionic+angularjs is the heyday. This pattern leverages ANGULARJS $http request data APIs to achieve a front-end separation popular. When it comes to Webapi cross-domain and authentication authorization always has to be mentioned. There are many examples of this ready-made example, but what I find is that it is either overly complex and not conducive to the first effective understanding of the whole process; Either the focus is single or bad, or if some of the pits are not stepped on, a change of environment is confused.



So, I'm going to try to find some of the pits and points of attention in the simplest way possible.



1. Take a look at our WEBAPI code



First, we realize our own authorizefilter.


 
public class HttpBasicAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        { if (actionContext.Request.Method == HttpMethod.Options) return true; if (actionContext.Request.Headers.Authorization != null && actionContext.Request.Headers.Authorization.Parameter != null) { // System.Web.Security.FormsAuthentication. var userdata= System.Text.Encoding.Default.GetString(Convert.FromBase64String(actionContext.Request.Headers.Authorization.Parameter)); if (userdata.Equals(String.Format("{0}:{1}", "tzy", "123"))) { return true; //base.IsAuthorized(actionContext);  }
            } return false; // return base.IsAuthorized(actionContext);  } protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            hrm.Headers.Add("WWW-Authenticate","Basic"); throw new HttpResponseException(hrm);
        }
    }


Where and how these codes are worth noting



1. if (ActionContext.Request.Method = = httpmethod.options) The decision is to cross-domain access when the browser initiates an Options request to test the request, But he will not take the data parameter and some header parameters, so the certification must not be able to continue through the cause, so give him direct authentication through. (No impact on non-cross-domain)



2. The decryption of the Authorization.parameter, the resolution here is the same as the token encryption method returned after the successful login, the Basic authentication method (simple 64-bit string) is used here



3.HandleUnauthorizedRequest method here because it is an inherited rewrite of Authorizeattribute, this method will be executed when IsAuthorized returns FALSE.



Here is the return of a 401 error message



4.HRM.   Headers.add ("www-authenticate","Basic"); This code, we'll talk about it later .



2. Then define our Apicontroller


 [httpbasicauthorize] publicclass  Basiccontroller:apicontroller    {
 [HttpGet] public ienumerable<string> Get () {  return  Newstring"tzy","123" };        }}


Then I used to change the route of the API and changed it a bit. Routetemplate Join/{action}


 
public static void Register(HttpConfiguration config)
        { // Web API configuration and services // Web API routes  config.MapHttpAttributeRoutes(); // config.Filters.Add(new AuthorizeAttribute());  config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }


There are two kinds of XML and JSON in WEBAPI



Anyway, I like json better.



This is a way of course there are other ways to change formatter here's not going to go into it.


 
protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
        }


3. Let's take a look at the effect.









Access through the browser the first authentication is unsuccessful and then executes the Handleunauthorizedrequest method we said above.



previously talked about HRM.   Headers.add ("www-authenticate","Basic"); This code indicates that the browser authentication mode is basic and then the browser automatically pops up a login window and encrypts it in basic mode each time it is transferred to the server through the header to authenticate and then be authorized.






Here we have a more intuitive understanding of the entire WEBAPI certification, and the next article will continue to combine this example. This process is accomplished through Ajax (Angularjs $http) in a cross-domain environment.



ANGULARJS+WEBAPI2 cross-domain Basic authentication Authorization (i)


Related Article

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.