Monday, 9 October 2017

Azure B2B Customized Login Step By Step setting from Admin Panel with creating a Tanent

Setup

Two Azure Active Directory apps must be created in your tenant. The first is the administrative app:
  • Log into the Azure portal, and click on Azure Active Directory, then click on Properties
    alt text
  • Click to copy the "Directory ID". This is also referred to as a "Tenant Id". Save this string, you'll need it in a bit.
  • Click on App registrations
    alt text
  • Click "+ New application registration" and enter the name of your app (like "B2B Admin App"). This title will be seen when users are prompted for their credentials.
  • Select "Web app / API", and enter the Sign-on URL. If you're setting this up before you deploy the app to Azure, you can enter https://loopback as a placeholder. Click "Create".
    alt text
  • From the application list, find the app you just created and click to open and edit it
  • Click on "Required permissions", then click "+ Add". On "Select an API", click and select "Microsoft Graph"
  • Click "Select permissions". On the "Enable Access" panel that appears, check the following items:
    • APPLICATION PERMISSIONS
      • Read and write directory data
      • Read and write all users' full profiles
    • DELEGATED PERMISSIONS
      • Sign in and read user profile
  • Click "Select"
    alt text
  • Back on the "Required permissions" panel, click the "Grant Permissions" button at the top. This authorized all users in your company to use the application, with the permissions you just assigned. (The actual users that can use the app will be limited to a few select roles, which we'll cover in a bit.)
    alt text
  • Back on the Settings panel, click "Keys". Under Description, enter a name for the application key, like "Key 1". Under Expires, select 1 or 2 years. (NOTE: you or someone in your organization will need to make a note to come back and refresh this key before it expires.)
  • Click "Save". An application secret will be generated and displayed. COPY this key and record it - you'll need it in an minute when setting up the web application. NOTE: this key will not be displayed again and cannot be retrieved. If you lose it, you'll have to come back, delete it, and create another one.
    alt text
  • Finally, before we are done with the first app, record the "Application ID". You can click to the right of it in the main panel and it will copy it to your clipboard. Record it along with the app secret from above - these two strings will be needed to setup the web app.
    alt text
The second app is the "pre-auth" app. This is a multi-tenant application that you'll create to allow your prospective guests to authenticate against their home Azure Active Directory tenant before completing their sign-up request. This allows you to know that they are who they say they are.
  • Follow the steps to create an app above. Name this one something like "B2B Pre-authentication App". It can include your company name, and you can customize it with a logo if you like. Use https://loopback for this sign-on URL too (for now).
  • Again, find the app you just created and click to edit it. On this one, on the Properties, page, you need to toggle the "Multi-tenanted" button to "Yes". Click "Save".
    alt text
  • Under "Required permissions", you will again add the Microsoft Graph API. This time you only need to check one item:
    • DELEGATED PERMISSIONS
      • Sign in and read user profile
  • Click "Select"
  • Follow the same steps to generate an app secret, as above. Again remember to copy the key and save it for the web app setup.
  • Follow the same steps to copy the "Application ID" and save this one too.
  • There is one additional step we need to take for the pre-auth app - we need to edit the "Manifest". This is a text file that gives us detailed access to some of the inner features of Azure AD applications. We need to enable "oauth2AllowImplicitFlow" for this application. By default, it is "false" and we will change it to "true". In the main panel, click "Manifest" to open the manifest editor.
    alt text
  • Find the line "oauth2AllowImplicitFlow", and change "false" to "true". Don't include quotes, just replace the word.
  • Click "Save".
  • That's it!
Web Application Setup
At this point, you should have 5 items saved: the tenant ID, the admin app ID and secret, and the pre-auth app ID and secret. You can now click the "Deploy to Azure" button on the landing page of this GitHub Repo, and it will take you to Azure. Log in, and you'll see a form like this one:
alt text
  • Enter the name of your new Resource Group. This is where the web application and DocumentDB will be deployed.
  • Select a region to deploy into.
  • Enter the Hosting Plan Name. This is the name of the compute resources that will power your web application. This name will be used throughout the deployment as part of the web app and DocumentDB names as well.
  • SKU refers to the size and price of your hosting plan. See https://azure.microsoft.com/en-us/pricing/details/app-service/for details.
  • SKU capacity refers to the number of compute instances deployed in your farm. NOTE: this code is currently tested and optimized for a single deployment. A Redis Cache should be implemented as a shared state engine for a farm deployment.
  • Tenant Name: this is the name of the Azure Active Directory tenant where you deployed your applications, like "contoso.onmicrosoft.com", or "contoso.com".
  • Tenant Id: Paste the TenantID you copied earlier.
  • Client Id_admin: Paste the ApplicationID from your admin app.
  • Client Secret_admin: Paste the application secret from your admin app.
  • Client Id_pre Auth: Paste the ApplicationID from your preauth app.
  • Client Secret_pre Auth: Paste the application secret from your preauth app.
The remaining fields are optional - if you like, you can set this app to use your own mail server to send the invitations once they are approved. If you choose this option, you get more flexibility in the content and structure of your invitation emails. By default (without defining a mail server), Azure Active Directory B2B will send the invitations on your behalf, using a standard email template. You do have an option to inject a custom message within the context of this email if you like.
That's it. Click "Purchase" (there's no charge for this software - you are agreeing to pay for the Azure compute resources you are about to provision). Within 2-5 minutes, the deployment will complete and your application will be ready.
Cleanup
Now that the app is deployed, there's a final step. We need to go back into our Azure Active Directory apps and update the URLs to match the URL of our new web app.
  • Navigate to your new web application - it's under "App Services". Click to copy the URL.
    alt text
  • Edit each of your Azure AD apps. First, update the Home page URL:
    alt text
  • Now edit the reply URL:
    alt text
All done!
Configuration
The first step will be for an administrator, or someone with "Guest Inviter" privileges in the tenant, to log in. The app will notice that this is the first time you've logged in and will walk you through the initial configuration. Once that's complete, you can give the web address to potential guests.
Azure App Services supports creating custom web addresses. The customization of App Services is beyond the scope of this article, but details can be found here: https://docs.microsoft.com/en-us/azure/app-service-web/custom-dns-web-site-buydomains-web-app. NOTE: custom domain names are available with the Basic or above SKU. Basic and above also includes a 99.95% SLA.

Thursday, 7 September 2017

Message Broadcast using google Api. in asp.net. (firebase Push Notification on Mobile)

   public void Test(string tokenid,string messagebody,string messgaetitle)
    {
        try
        {
//This applicationid and senderid comes from mobile developer. this comes from www.console.firebase.google.com
            var applicationID = "AAAAuSEmjuQ:APA91bFewTUFbEwbHOH7-W2Cvl5a6LXDMjHp7grlv2aBBzlCS0gwgRFir3a29hNdkmqMPTjVfk8FI_px973BPs_XfO6WjsLmEDKR2FgFjQUcF6Q75uX4oYvqIBgZAT-zX7rBqD9jVO2F";
            var senderId = "795125124836";

//This device id from Database when A app install automettically his device id has post ourdatabase.
            string deviceId = tokenid;
            WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/json";
            var data = new
            {
                to = deviceId,
                notification = new
                {
                    body = messgaetitle,
                    title = messagebody,
                    icon = "myicon"
                },
                priority = "high"

            };

            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
            tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
            tRequest.ContentLength = byteArray.Length;

            using (Stream dataStream = tRequest.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (WebResponse tResponse = tRequest.GetResponse())
                {
                    using (Stream dataStreamResponse = tResponse.GetResponseStream())
                    {
                        using (StreamReader tReader = new StreamReader(dataStreamResponse))
                        {
                            String sResponseFromServer = tReader.ReadToEnd();
                            Response.Write(sResponseFromServer);
                            txtdepartmentname.Text = sResponseFromServer;
                        }
                    }
                }
            }
        }

        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
=========================================
 protected void BtnSave_Click(object sender, EventArgs e)
    {
if (e.CommandName == "btnsend")
        {
            for (int i = 0; i < Griddepartment.Items.Count; i++)
            {
                int ID = Convert.ToInt32(((RadLabel)Griddepartment.Items[i].FindControl("lblattributeid")).Text);
                string msgbody = ((RadLabel)Griddepartment.Items[i].FindControl("lblattributename")).Text;
                string msgtitle = ((RadLabel)Griddepartment.Items[i].FindControl("lblcontrolname")).Text;
                RadCheckBox chksend = (RadCheckBox)Griddepartment.Items[i].FindControl("chksend");
                if (chksend.Checked == true)
                {
                    var tokens = GetallTokens().ToList();
                    foreach (var ss in tokens)
                    {
                        Test(ss.RegistartionToken_DeviceID, msgbody, msgtitle);
                        n1.Text = "Message Send Successfully";
                        n1.Show();
                    }
                }
            }
        }
}


Saturday, 2 September 2017

Azure API Management with Swagger With Subscription Key Management and token Management from Publisher Portal and Developer Portal


  1. Develop APIs. Add and publish an API Product. Add operations. ...
  2. Secure your backend. Protect Web API backend with AAD. Connect to a virtual network. ...
  3. Configure Policies. Custom caching. Advanced monitoring. ...
  4. Customize the developer experience. Modify page content and layout. ...
  5. Manage in production. Deploy to multiple Azure regions.

Creating Azure WebApi with Swagger.

First create  WebApplication add Azure Api App Template and Select MVC.
Click OK.

Open URL https://www.nuget.org/packages/Swashbuckle to get new Swashbuckle
To install Swashbuckle - Swagger for WebApi, run the following command in the Package Manager Console
PM > Install-Package Swashbuckle -Version 5.5.3
Open SwaggerConfig.cs from App_start-> SwaggerConfig.cs.
Un comment the bellow line
//c.IncludeXmlComments(GetXmlCommentsPath());
And Replace GetXmlCommentsPath() with the following
c.IncludeXmlComments(string.Format(@"0}\bin\AzureApiSwagger.XML",System.AppDomain.CurrentDomain.BaseDirectory));

Go to the application properties -> Build -> check “XML documentation file, copy the provided path from the text box and REPLACE. AND SAVE.

Go to global.asx page and comment the following

//RouteConfig.RegisterRoutes(RouteTable.Routes);
And save

Next Go to Web Api application
1.    Add Install-Package Microsoft.AspNet.WebApi.HelpPage
2.    for Help Page which is on

Next Add Install-Package WebApiTestClient   for Designing Test API

For Unit Resolver You add This thing
Install-Package Unity -Version 2.1.505.2

Create an API Management instance

Note
To complete this tutorial, you need an Azure account. If you don't have an account, you can create a free account in just a couple of minutes. For details, see Azure Free Trial.
The first step in working with API Management is to create a service instance. Sign in to the Azure Portal and click New, Web + Mobile, API Management.
API Management new instance
For Name, specify a unique sub-domain name to use for the service URL.
Choose the desired Subscription, Resource group and Location for your service instance.
Enter Contoso Ltd. for the Organization Name, and enter your email address in the Administrator E-Mail field.
Note
This email address is used for notifications from the API Management system. For more information, see How to configure notifications and email templates in Azure API Management.
New API Management service
API Management service instances are available in three tiers: Developer, Standard, and Premium.
Note
The Developer Tier is for development, testing, and pilot API programs where high availability is not a concern. In the Standard and Premium tiers, you can scale your reserved unit count to handle more traffic. The Standard and Premium tiers provide your API Management service with the most processing power and performance. You can complete this tutorial by using any tier. For more information about API Management tiers, see API Management pricing.
Click Create to start provisioning your service instance.
New API Management service
Once the service instance is created, the next step is to create or import an API.

Import an API

An API consists of a set of operations that can be invoked from a client application. API operations are proxied to existing web services.
APIs can be created (and operations can be added) manually, or they can be imported. In this tutorial, we will import the API for a sample calculator web service provided by Microsoft and hosted on Azure.
Note
For guidance on creating an API and manually adding operations, see How to create APIs and How to add operations to an API.
APIs are configured from the publisher portal. To reach it, click Publisher portal from the service toolbar.
Publisher portal
To import the calculator API, click APIs from the API Management menu on the left, and then click Import API.
Import API button
Perform the following steps to configure the calculator API:
  1. Click From URL, enter http://calcapi.cloudapp.net/calcapi.json into the Specification document URL text box, and click the Swagger radio button.
  2. Type calc into the Web API URL suffix text box.
  3. Click in the Products (optional) box and choose Starter.
  4. Click Save to import the API.
 OR YOU CAN ADD JSON FILE FROM YOUR LOCAL

Run your Api on Internet Explorer . And Save Jshon File. And Uplaod it.
Add new API
Note
API Management currently supports both 1.2 and 2.0 version of Swagger document for import. Make sure that, even though Swagger 2.0 specification declares that host, basePath, and schemesproperties are optional, your Swagger 2.0 document MUST contain those properties; otherwise it won't get imported.
Once the API is imported, the summary page for the API is displayed in the publisher portal.
API summary
The API section has several tabs. The Summary tab displays basic metrics and information about the API. The Settings tab is used to view and edit the configuration for an API. The Operations tab is used to manage the API's operations. The Security tab can be used to configure gateway authentication for the backend server by using Basic authentication or mutual certificate authentication, and to configure user authorization by using OAuth 2.0. The Issues tab is used to view issues reported by the developers who are using your APIs. The Products tab is used to configure the products that contain this API.1
By default, each API Management instance comes with two sample products:
  • Starter
  • Unlimited
In this tutorial, the Basic Calculator API was added to the Starter product when the API was imported.
In order to make calls to an API, developers must first subscribe to a product that gives them access to it. Developers can subscribe to products in the developer portal, or administrators can subscribe developers to products in the publisher portal. You are an administrator since you created the API Management instance in the previous steps in the tutorial, so you are already subscribed to every product by default.

Call an operation from the developer portal

Operations can be called directly from the developer portal, which provides a convenient way to view and test the operations of an API. In this tutorial step, you will call the Basic Calculator API's Add two integers operation. Click Developer portal from the menu at the top right of the publisher portal.
Developer portal
Click APIs from the top menu, and then click Basic Calculator to see the available operations.
Developer portal
Note the sample descriptions and parameters that were imported along with the API and operations, providing documentation for the developers that will use this operation. These descriptions can also be added when operations are added manually.
To call the Add two integers operation, click Try it.
Try it
You can enter some values for the parameters or keep the defaults, and then click Send.
HTTP Get
After an operation is invoked, the developer portal displays the Response status, the Response headers, and any Response content.
Response

View analytics

To view analytics for Basic Calculator, switch back to the publisher portal by selecting Managefrom the menu at the top right of the developer portal.
Manage
The default view for the publisher portal is the Dashboard, which provides an overview of your API Management instance.
Dashboard
Hover the mouse over the chart for Basic Calculator to see the specific metrics for the usage of the API for a given time period.
Note
If you don't see any lines on your chart, switch back to the developer portal and make some calls into the API, wait a few moments, and then come back to the dashboard.
Click View Details to view the summary page for the API, including a larger version of the displayed metrics.
Analytics
Summary
For detailed metrics and reports, click Analytics from the API Management menu on the left.
Overview


Main Thing is Create Policy
For API Security Reason You add below line in your Web API config
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Filters.Add(new UseApiManagementAttributes());
            // Web API routes
            config.MapHttpAttributeRoutes();
            
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
==============================
Next Step you add a folder which name is Filters on Api. and add a class name UseApiManagementAttributes.
And add below code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;
using System.Globalization;
using System.Net;

namespace API.Filters
{
    public class UseApiManagementAttributes:ActionFilterAttribute
    {
        #region Methods
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var configkey = ConfigurationManager.AppSettings["Api.Key"];
            IEnumerable<string> Keys = null;
            var error = false;
            var checkKey = true;
            if(String.IsNullOrEmpty(configkey))
            {
                error = true;
            }
            else
            {
                if (actionContext.Request.Headers.Contains("Ocp-Apim-Subscription-Key"))
                {
                    //Seems like we are called from Azure API Management here.Be aware that this code is anythng.
                    //but secure. It simple assume that Ocp-Apim-Subscription-Key and User-Agent are present in the header
                    //This is Because of the lack of certificate in current azure portal.
                    error = !actionContext.Request.Headers.TryGetValues("Ocp-Apim-Subscription-Key", out Keys) || Keys.Any();
                    if(!error)
                    {
                        //if the magic Apim-key is present check now, if the agent is correct.
                        var agent = string.Empty;
                        var agents = actionContext.Request.Headers.GetValues("User-Agent");
                        error=!agent.Any() || !agents.First().Equals("EMA-Gateway",StringComparison.OrdinalIgnoreCase);
                    }
                    //We don't need to check the key because it is managed by API Management.
                    checkKey = false;
                }
                else if(actionContext.Request.Headers.Contains("api_Key"))
                {
                    //This could be valid APi call using a static secerate API from request.
                    error=!actionContext.Request.Headers.TryGetValues("api_Key",out Keys)||!Keys.Any();
                }
                else if(actionContext.Request.RequestUri.ParseQueryString().HasKeys() && actionContext.Request.RequestUri.ParseQueryString().HasKeys())
                {
                    //This could be a valid API call a static API key from URL like swagger case.
                    Keys = new[] { actionContext.Request.RequestUri.ParseQueryString().Get("api_Key") };
                }
                else
                {
                    error = true;
                }
            }
            if(!error && checkKey && !Keys.First().Equals(configkey,StringComparison.Ordinal))
            {
                error = true;
            }
            if(error)
            {
                var message = string.Format(CultureInfo.InvariantCulture, "Request are only allocated using the api management URLS.");
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.UseProxy, message);
                return;
            }
            base.OnActionExecuting(actionContext);
        }

        #endregion

    }
}
===================
Set on API Web Config Below Code
<appSettings>
    <add key="Api.Key" value="1234" />
  </appSettings>
===========================
Next When you call api on your Project Below code Example
===========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class APITEST : System.Web.UI.Page
{
    HttpClient client = new HttpClient();
    List<Department> DepartmentList = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "dbe20779b9ce47cab9e60c132da99e82");
        var path = "https://swashapimanagementservice.azure-api.net/Trinty/api/Department";
        //  var appsurl = ConfigurationManager.AppSettings["APIPath"].ToString();
        client.BaseAddress = new Uri(path);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        GetData();
    }

    private List<Department> GetData()
    {
        HttpResponseMessage skill = client.GetAsync("Department").Result;
        if (skill.IsSuccessStatusCode)
        {
            DepartmentList = skill.Content.ReadAsAsync<List<Department>>().Result;
            return DepartmentList.Where(a => a.IsActive == true).OrderByDescending(a => a.Department_ID).ToList();

        }
        else
        {
            return null;
        }
    }
}