Blazor Wasm Authentication - jwt

I am trying to build a blazor wasm app and trying to authenticate with Jwt token. I am facing with an interesting problem. When I login, I can't access the pages which has [Authorize] attributes. But after refreshing the page, authentication works. Where may be the issue?

I have figured out the problem. While you are doing login operations you need to force load. If you don't force load AuthenticationStateProvider is not refreshed.
async Task Login()
{
var token = await AuthenticationUseCases.LoginAsync(userViewModel.UserName, userViewModel.Password);
if (string.IsNullOrWhiteSpace(token))
{
NotificationMessage message = new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "Info Summary", Detail = "Info Detail", Duration = 4000 };
NotificationService.Notify(message);
}
else
NavigationManager.NavigateTo("/", true); //true means force load
}

Related

Xamarin.Auth Facebook login Completed event not firing

I am trying to create a Xamarin.Forms application with a Facebook login button. Everything works up until the part where the Completed event, which never gets fired.
I am using a PageRenderer to initiate the auth flow as follows:
[assembly: ExportRenderer(typeof(Page1), typeof(LoginPageRenderer))]
namespace xmrn1.Droid {
class LoginPageRenderer : PageRenderer {
private const string ClientId = "<sanitized>";
public LoginPageRenderer(Context ctx) : base(ctx) { }
protected override void OnElementChanged(ElementChangedEventArgs<Page> e) {
base.OnElementChanged(e);
var authorizeUri = new Uri("https://www.facebook.com/dialog/oauth/");
var redirectUri = new Uri($"fb{ClientId}://authorize");
var auth = new OAuth2Authenticator(
ClientId,
"email",
authorizeUri,
redirectUri);
auth.Completed += Auth_Completed;
var ui = auth.GetUI(Context);
Context.StartActivity(ui);
}
private void Auth_Completed(object sender, AuthenticatorCompletedEventArgs e) {
// This never gets called
}
}
}
And this is my "Facebook Login" settings:
And my "Advanced Settings" settings:
Found the answer, I had to turn on the Web OAuth Login in the Facebook Login settings, and also to change the redirectUri to some uri in my domain, and add that uri to the Valid OAuth Redirect URIs in that same settings window.
Strange thing though, now when I log in, and the two-factor-authentication code prompt shows up, my phone displays an authenticator popup notification asking me to approve and when I press "Yes" it doesn't automatically confirm the login, I have to manually type the 2fa code anyway...

Aurelia Push State App Reload on Login and Logout

When configuring Push State with Aurelia and Visual Studio, I am getting an odd behavior where after I select login my entire app reloads instead of the router just pushing to the homepage. This also happens when I logout, I get to the login screen and it refreshes the entire app. I am using Aurelia Auth. Any assistance would be much appreciated.
I think I had the exact same issue some time ago and this was one of the reasons I switched back to pushState = false (but my infos may be helpful for you).
Anyways, the following issue describes what I was facing: https://github.com/paulvanbladel/aurelia-auth/issues/55
The problem is, internally the plugin sets href:
Login - https://github.com/paulvanbladel/aurelia-auth/blob/master/src/authentication.js#L95-L99
if (this.config.loginRedirect && !redirect) {
window.location.href = this.getLoginRedirect();
} else if (redirect && isString(redirect)) {
window.location.href = window.encodeURI(redirect);
}
Logout - https://github.com/paulvanbladel/aurelia-auth/blob/master/src/authentication.js#L139-L143
if (this.config.logoutRedirect && !redirect) {
window.location.href = this.config.logoutRedirect;
} else if (isString(redirect)) {
window.location.href = redirect;
}
What you need to do is avoid both conditions, i.e. set loginRedirect and logoutRedirect to the empty string (''). Then, do the navigation on your own via Aurelias router as I did in my example from the GH issue:
return this.auth.login(userInfo)
.then(response => {
console.log('You signed in successfully.');
this.router.navigate('/contents');
})
Of course, do the same router navigation on your logout method.

Facebook OAuth Xamarin Forms Redirection

I am using xamarin forms OAuth2 to signin into Facebook, Google and Twitter.
On android it works. But on iOS it screen freezes with spinning activity indicator at top right corner. Is there any one having same issue ?.
Update: Please find below code
partial void UIButton15_TouchUpInside(UIButton sender)
{
// https://developers.facebook.com/apps/
var auth = new OAuth2Authenticator(
clientId: "ID",
scope: "",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));
var ui = auth.GetUI();
auth.Completed += FacebookAuth_Completed;
PresentViewController(ui, true, null);
}
async void FacebookAuth_Completed(object sender, AuthenticatorCompletedEventArgs e)
{
if (e.IsAuthenticated)
{
var request = new OAuth2Request(
"GET",
new Uri("https://graph.facebook.com/me?fields=name,picture,cover,birthday"),
null,
e.Account);
var fbResponse = await request.GetResponseAsync();
var fbUser = JsonValue.Parse(fbResponse.GetResponseText());
var name = fbUser["name"];
var id = fbUser["id"];
var picture = fbUser["picture"]["data"]["url"];
var cover = fbUser["cover"]["source"];
}
DismissViewController(true, null);
}
On facebook developer site:
Created app using Facebook login plugin.
Added redirect URL as http://www.facebook.com/connect/login_success.html
UPDATED :
Below code works
PresentViewController(auth.GetUI(), true, false);
It seems like issue happening only with latest OAuth library. Couldn't build with previous versions of OAuth due to build errors. So created Webview based login followed by Graph API Request.

FIrebase Google auth operation not supported in this environment

I am working on ionic and firebase project, made a login page to sign in with google. I am using this Below.
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider).then(function (result) {
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
$state.go('app.homepage');
}).catch(function (error) {
});
firebase.auth().getRedirectResult().then(function (result) {
if (result.credential) {
var token = result.credential.accessToken;
}
// The signed-in user info.
var user = result.user;
}).catch(function (error) {
});
When I run it in the browser it is working fine, but when I run it in android device I am getting auth/operation-not-supported-in-this environment.
The application is running on "location.protocol".
I researched a bit but could not find an exact answer. What could be wrong ?
popup and redirect operations are not currently supported in Ionic/Cordova environment. As a a fallback you can you an oauth cordova plugin to obtain a google/facebook OAuth access token and then sign in the user via signInWithCredential. Check this thread for more on this:
auth.signInWithCredential(firebase.auth.FacebookAuthProvider.credential(fbAccessToken));
https://groups.google.com/forum/#!searchin/firebase-talk/facebook$20cordova/firebase-talk/mC_MlLNCWnI/DqN_8AuCBQAJ
Try the following because local storage is not enabled in webView, which is required for firebase
webSettings.setDomStorageEnabled(true);

Facebook action script 3 API login/logout issue

I'm making mobile AIR app for Android using Flash builder 4.5, AIR 2.6, Facebook action script 3 API the latest version.
I have a problem with login/logout. I can login only one time - then my data caches somehow and Facebook automatically logs me in. When I call logout I receive response TRUE, but I don't really logout from system. Standard login dialog doesn't appear for me. I have already read a lot of articles on stackoverflow and open issues on official site, but none of them were helpfull. How can I solve this? Here is the code I use:
package
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.system.Capabilities;
import flash.system.Security;
import flash.display.Loader;
import com.facebook.graph.FacebookMobile;
public class TestProj extends Sprite
{
public function TestProj()
{
super();
//register to add to stage
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
}
private function onAddedToStage(event:Event):void
{
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
FacebookMobile.init("195053007196177", initCallback);
}
private function initCallback(success:Object, fail:Object):void
{
var appPermissions:Array = new Array("read_stream", "offline_access", "publish_stream", "read_friendlists");
FacebookMobile.login(loginCallback, this.stage, appPermissions);
//FacebookMobile.logout(logoutCallback);
}
private function loginCallback(success:Object, fail:Object):void
{
//And here I always receive success with my UserID
//and login dialog don't appears to me before this
if (success)
{
trace("login ok");
}
else
trace("login failed");
}
private function logoutCallback(success:Object):void
{
//here I reseive "TRUE" always!!
trace(success);
}
}
}
You're only passing the 1st argument of logoutCallback to your logout method. If you add in the 2nd argument of your site url specified for your app, it should clear it out the html cookie for that window. Also, set FacebookMobile.manageSession = false;
FacebookMobile.logout(logoutCallback, "http://your_app_origin_url");
There is a potential, related bug that involves Desktop and Mobile not accessing or clearing the access token's the same way. For that, there's a hack that describes exposing the access token in FacebookMobile, then manually calling the "logout" method with the access token. The issue is described here, including a method called "reallyLogout". If what I've written above doesn't work, implement "reallyLogout".
When you log out, your app clears the local session but does not log you out of the system. This is clearly defined in the documentation for logout. Think about it, if you're logged into Facebook on your Smartphone, Web Browser, and now this Mobile Desktop App, and suddenly you log out... it shouldn't log you out EVERYWHERE, just within that browsers session. So pass that 2nd parameter.
I've had this exact problem, and after trying numerous fixes, this finally seems to work:
The default logout functionality seems to not be properly clearing cookies via the FacebookMobile actionscript API. The solution in comment #33 here worked for me, reproduced here. Make sure to sub in your own APP_ID:
function logout(e:MouseEvent):void {
FacebookMobile.logout(onLogout, "https://m.facebook.com/dialog/permissions.request?app_id=APP_ID&display=touch&next=http%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&type=user_agent&perms=publish_stream&fbconnect=1");
}
function onLogout(result:Object):void
{
trace("Perfect Log Out!")
}
Have had this Android Facebook clean logout problem the whole day, manage to solve it. Hope it helps. Here is my FB mobile handlelogin code to ensure all fb cookies and sessions are being removed and user will need to relogin.
Sometimes FB server is very slow. Its best to put a timer before you call handleLoginClick() again
function handleLoginClick():void
{
trace("connecting to facebook");
if (FacebookMobile.getSession() == null)
{
FacebookMobile.init(APP_ID, onHandleInit, null);
FacebookMobile.manageSession = false
}
else
{
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle(0, 0, 1, 1);
webView.stage = this.stage;
webView.loadURL("https://m.facebook.com/logout.php?confirm=1&next=http://www.facebook.com&access_token=" + FacebookMobile.getSession().accessToken);
webView.addEventListener(Event.COMPLETE,webviewhandleLoad);
function webviewhandleLoad(e:Event)
{
FacebookMobile.logout(null, "http://apps.facebook.com/<appName>/");
FacebookMobile.logout(null, "http://www.facebook.com");
webView.dispose()
webView = null
setTimeout(handleLoginClick,3000)
}
}
}
look at the solution of this problem. Maby someone it helps:
var stage_ref:Stage = PlatformUtil.originalStage(); //my custom class to get stage
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle(0, 0, stage_ref.width, stage_ref.height);
FacebookMobile.login(loginCallback, stage_ref, appPermissions, webView);
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=381
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=382
http://code.google.com/p/facebook-actionscript-api/issues/detail?id=383