Security for two websites talking to each other - asp.net

I have two websites (one a new MVC app, and the other an older WebForms app). I need them to be able to communicate with each other.
I'm looking at implementing a RESTful Web API on both sites, and then having each site call the other site's Web API.
So far, so good, but what about authentication? I'm looking at Authentication Filters. They seem like a reasonable approach for the MVC app, but looks like they may be unsupported on WebForms.
My question is, since the only entity that will ever be calling either of these API is the other website, is there a way to simplify this process? For example, could I just have a secret GUID and pass that, and if the other site gets the right GUID, then I assume it's okay?
Note that I will be using HTTPS. Also, we're not a bank. Security only needs to be reasonable and nothing more.

You can setup a simple user id/password for the client and pass it in with every request on the Authorization header. Then, creates a custom AuthorizationFilterAttribute to authenticate the credential.
Something like this.
public class MyAuthorizeAttribute : AuthorizationFilterAttribute
{   
        public ICustomerAuthenticator CustomerAuthenticator { get; set; }
        
        public override void OnAuthorization(HttpActionContext actionContext)
        {   
            var authInfo = $"{actionContext.Request.Headers.Authorization.Parameter}";
            var authenticationResult = CustomerAuthenticator.Authenticate(new []{ authInfo });
            if (!authenticationResult.Authenticated)
            {
                
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {   
                    Content = new StringContent("You are not authorized.")
                };
            }
            else
            {
                actionContext.RequestContext.Principal = new GenericPrincipal(new ClaimsIdentity(new List<Claim>
                {
                    new Claim("CustomerId", authenticationResult.Customer.Id.ToString()),
                    new Claim("CustomerName", authenticationResult.Customer.Name)
                }));
            }
        }
}
Hope this helps.

Related

All Complications with the same name

I made some complications for the Apple Watch.
I uses Intents for this complications.
This code is used to add the complications:
func provideVehicleItemOptionsCollection(for intent: ConfigurationIntent, with completion: #escaping (INObjectCollection<VehicleItem>?, Error?) -> Void) {
        let vehicleStatusList = VehicleStatus.loadVehicleStatusList()
        var list: [VehicleItem] = []
        for item in vehicleStatusList {
            list.append(VehicleItem(identifier: item.id, display: item.name ?? "No Name"))
        }
        let collection = INObjectCollection(items: list)
        completion(collection, nil)
    }
But with this all complications show the same name.
On the Apple Watch they show an icon in addition to this name, but also with is sometimes not working.
How can I change the Title of the complications?

.net core 2.2 multiple bearer token authentication schemes

I am currently trying to use 2 different bearer tokens in a .net core 2.2 app. I would like to use an Identity Server token and an Azure AD bearer token. According to Microsoft this is possible (https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-2.2) but I am having no success getting it working.
I have the Identity Server token as the "default" authentication followed by the AzureAD token as documented in the aforementioned link:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ClockSkew = ClockSkew
};
o.Audience = Audience;
o.Authority = IdentityIssuer;
o.RequireHttpsMetadata = true;
})
.AddJwtBearer("AzureAd",o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
};
o.Audience = AudienceUri;
o.Authority = Authority
});
Identity Server tokens validate as expected; however Azure AD tokens do not. They appear to always hit the default Bearer token handler.
Try with something like this (I have 2 auth schemes; one for AAD and another one for custom Bearer auth)
var url = new MongoUrl(mongoSettings.ConnectionString); // I'm using MONGODB as databse ..but you can choose what you want
var client = new MongoClient(url);
var database = client.GetDatabase(url.DatabaseName);
services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 0;
// ApplicationUser settings
options.User.RequireUniqueEmail = false;
//options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#.-_";
}).RegisterMongoStores<ApplicationUser, ApplicationRole>(
p => database.GetCollection<ApplicationUser>("AspNetUsers"),
p => database.GetCollection<ApplicationRole>("AspNetRoles"))
.AddDefaultTokenProviders();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(appConfiguration.Key));
var tokenValidationParameters = new TokenValidationParameters
{
                //RequireExpirationTime = true,
                //RequireSignedTokens = true,
                //ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
ValidateIssuer = false,
ValidIssuer = appConfiguration.SiteUrl,
ValidateAudience = false,
ValidAudience = appConfiguration.SiteUrl,
                //ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(options =>
{
//options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer("AAD", options =>
{
//options.Audience = appConfiguration.SiteUrl;
//options.ClaimsIssuer = appConfiguration.SiteUrl;
options.IncludeErrorDetails = true;
options.Authority = "https://sts.windows.net/800859e2-e8c3-4842-b31a-3b3727070cb6/v2.0";
options.Audience = "5e2ddaf2-2ed3-4829-bbe8-9aa127a754ef";
options.SaveToken = true;
options.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
if ((context.Request.Path.Value.StartsWith("/videohub")
//|| context.Request.Path.Value.StartsWith("/looney")
//|| context.Request.Path.Value.StartsWith("/usersdm")
)
&& context.Request.Query.TryGetValue("token", out StringValues token)
)
{
context.Token = token;
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
//TODO:
return Task.FromResult(0);
},
OnTokenValidated = context =>
{
//At this point, the security token has been validated successfully and a ClaimsIdentity has been created
var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
//get username
var preferred_username = claimsIdentity.Claims.ToList().Where(c => c.Type == "preferred_username").Select(c => c.Value).FirstOrDefault();
var username = !string.IsNullOrEmpty(preferred_username) ? preferred_username : claimsIdentity.Claims.ToList().Where(c => c.Type == "upn").Select(c => c.Value).FirstOrDefault();
//add your custom claims here
var serviceProvider = services.BuildServiceProvider();
var userservice = serviceProvider.GetService<IUsersService>();
var us = userservice.Find(xx => xx.UserName == username);
if (us == null) return Task.FromResult(0);
// ADD SCHEMA (so we know which kind of token is .. from AZURE ACTIVE DIRECTORY .. OR CUSTOM)
// TO RETRIEVE THE SCHEMA ..--> //var result = User.Claims.Where(c=>c.Type=="schema").FirstOrDefault().Value;
claimsIdentity.AddClaim(new Claim("schema", "AAD"));
//GET ROLES FROM DB
if (us != null && us.Roles.Any())
{
//add THEM
us.Roles.ForEach(rr =>
{
claimsIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, rr.ToUpper()));
});
}
else
{
//OR ADD A DEFAULT ONE
claimsIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, Constant.ROLES.Dipendente));
}
// add MONGDB Id as ClaimTypes.NameIdentifier
claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, us.Id));
return Task.FromResult(0);
}
};
}).AddJwtBearer("CUSTOM", options =>
{
//options.Audience = appConfiguration.SiteUrl;
//options.ClaimsIssuer = appConfiguration.SiteUrl;
options.TokenValidationParameters = tokenValidationParameters;
options.SaveToken = true;
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = context =>
{
//TODO:
return Task.FromResult(0);
},
OnTokenValidated = context =>
{
//At this point, the security token has been validated successfully and a ClaimsIdentity has been created
var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
//add your custom claims here
// ADD SCHEMA (so we know which kind of token is .. from AZURE ACTIVE DIRECOTY .. OR CUSTOM)
claimsIdentity.AddClaim(new Claim("schema", "CUSTOM"));
return Task.FromResult(0);
}
};
});
then in yours Controller mark class or methid as :
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = "AAD,CUSTOM")] //<-- yours schema
public class AccountController : Controller
{
// ...
}
Hope it helps you!!
Possible things you could try:
1 Set up the default policy
services.AddAuthorization(options => {
options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme, "AzureAD")
.RequireAuthenticatedUser()
.Build();
2 On the OnAuthenticationFailed > under one of the jwtOptions.Events, add a condition if it's authenticated then complete the task and don't show the error. Sometimes the user is authenticated already but the error from one provider prevents the proper response
if (arg.HttpContext.User.Identity.IsAuthenticated)
{
return Task.CompletedTask;
}
3 If this doesn't work. There's a hack to check if it's authenticated. Add more conditions per scheme.
app.Use(async (context, next) =>
{
if (!context.User.Identity.IsAuthenticated)
{
var result = await context.AuthenticateAsync("AzureAD");
if (result?.Principal != null)
{
context.User = result.Principal;
}
}
await next.Invoke();
});

Why Button Press on MSP430 Doesn't Light LEDs

Pin 1.3step counter: Modify the code to have the LEDs step one binary order each time the button has been pushed.
I'm relatively new with programming on a Micro Controller. So what is above is what I'm attempting to do. However while trying to get it to step in binary order, the button has seemed to stop working and thus none of the LEDs flash. I'm uncertain what changed since previously it ran well without the button push. Comparing with friends it looks the same so stumped on what went wrong.
This is the code I have.
#include <msp430.h>
/*
* main.c
 */
int main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 // Stop watchdog timer
  volatile unsigned int i;
  volatile unsigned int j;
  P1DIR |= 0x41;                            // Set P1.0 to output direction
  P1DIR &=~(BIT3);                          // Ensure P1.3 is an input
  P1REN |= BIT3;                            // Set pulling Resistor for P1.3
  P1OUT |= BIT3;                            // Make the pulling resistor for P1.3 a pull-UP resistor
  j=0;                                      // Button presses set to 0
  P1OUT &=~0x01;
  while (1)                                 // Test P1.3
  {
    if ((BIT3 & P1IN)) {                    // if P1.3 set, set P1.0 turning on the LED
        if (j == 0)
            P1OUT &= ~0x41;
        if (j == 1) {
            P1OUT |= 0x01;
            P1OUT &= ~0x40;
        }
        if (j == 2) {
            P1OUT &= ~0x01;
            P1OUT |= 0x40;
        }
       if (j == 3)
           P1OUT |= 0x41;
    else {
        for (i=3000; i>0; i--);
        if (j == 3)
            j++;
        else
            j = 0;
        }
       while ((BIT3 & P1IN));
  }
}
}
You only increase j if j == 3. So j always stays at 0, which means all LEDs off. You also missed a closing brace before the else. Formatting the code with correct indentation helps finding such errors.
while (1)
{
if ((BIT3 & P1IN))
{
if (j == 0)
{
P1OUT &= ~0x41;
}
if (j == 1)
{
P1OUT |= 0x01;
P1OUT &= ~0x40;
}
if (j == 2)
{
P1OUT &= ~0x01;
P1OUT |= 0x40;
}
if (j == 3)
{
P1OUT |= 0x41;
}
}
else
{
for (i=3000; i>0; i--);
// here I exchanged the == with <
if ( j < 3 )
{
j++;
}
else
{
j = 0;
}
}
while ((BIT3 & P1IN));
}

signalR first demo project

I am new to SignalR and I am looking for a sample application in Asp.net not mvc that does real time notifications so that I can start working. Can any one guide me to a working sample because I have downloaded many samples that do not work
Please note that this answer was for SignalR version 0.5.3 and is now out of date with the latest version of SignalR
It is really simple just to set up your own little Demo. There really isn't much to it.
Just create a new project, install SignalR via the NuGet package manager console, and then do the very basics to get it running.
I blogged about how to do it over at my site http://timjames.me/creating-your-first-signalr-mvc-project
Hub
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR;
using SignalR.Hubs;
namespace MySignalR
{
public class SNRL : Hub
{
public void SendMessage(string msg)
{
Clients.sendMessage(msg);
}
}
}
Javscript
<script>
    $(function () {
        var myHub = $.connection.sNRL;
        myHub.sendMessage = function (data) {
            $('#mySpanTag').html(data);
        };
        $.connection.hub.start({ transport: 'auto' }, function () {
            myHub.sendMessage("Hello World!");
        });
    });
</script>
html
<span id="mySpanTag"></span>
And make sure you reference the correct script files
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-0.5.3.min.js"></script>
<script src="/signalr/hubs"></script>
Have you tried downloading the SignalR sample from NuGet Library?

Load jquery images dynamically for ASPX

i am using .net and jquery for image popup.
$("#manual2").click(function() {
var imageNames = document.getElementById("hdImages").value;
$.fancybox([
'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
{
'href' : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
}
], {
'padding' : 0,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'image',
'changeFade' : 0
});
});
Here i keep images static only,but i want to get images from page load,Now i want load images dynamically from page load.
For the dynamic purpose i saved image urls to hdImages('http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg','http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg')
When i write the above jquery like:
$("#manual2").click(function() {
var imageNames = document.getElementById("hdImages").value;
$.fancybox([
imageNames
], {
'padding' : 0,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'image',
'changeFade' : 0
});
});
Here not working now.
Plz tell me how to load images to jquery from page load.
Thanks in advance
On the aspx page
  $("#manual2").click(function() {
    $.fancybox([
        ' ',
        '<%# ImageUrl %>',
        {
            'href'  : '<%# ImageUrl %>',
            'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
        }
    ], {
        'padding'           : 0,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        'type'              : 'image',
        'changeFade'        : 0
    });
});
In the page_load function
ImageUrl = "http://..."
....
Page.DataBind()
You should use your function as below script
i.e :
$(function () {
$("#manual2").click(function() {
//your script code here..
});
});
Hopes its help..
manually fire event on document.ready ex.. $("#manual2").click();

Resources