This is happening usually because the router itself is doing some sort of proxy or authentication. You would usually see something like this in a public area where you need to 'log in' to get access.
iOS (and I think the Mac too) goes to look for a known file on one of Apple's servers. If that file doesn't exist (which basically means it can't reach it), it knows there must be some go-between first. It then will display this sheet, usually asking you to log in or accept the terms.
If the location is legitimate, I usually have no issue doing this. For example, businesses or restaurants that advertise free wifi service. I know the place I see this the most is at a grocery store I frequent. You must first click 'agree' on a form before moving on.
Also, the reason the cert is invalid is because until you 'authenticate', that router usually tries to forward all requests to its internal page. So, if you had an HTTPS connection open on apple.com, the device complains because apple.com is now resolving to that local router.