Disable or Unregistered Meteor.Accounts default login handler (loginWithPassword) - meteor

I have created my own custom login handler to authenticate users.
loginWithPasswordPlatfrom(user,passwd,platformId)
I want to disable the default login method loginWithPassword(user,password) of the meteor and force clients (android, ios, web) to use my custom method.
but what happened if client call login with user and password parameter it is successfully logedin because default login is still registered in a meteor.
please suggest how to disable or unregister a login handler in meteor accounts.

You can modify Accounts._loginHandlers on the server and throw out the default login method. Accounts.loginWithPassword() is then no longer possible on the client.
var hs = []
for(var i = 0; i < Accounts._loginHandlers.length; i++) {
if(Accounts._loginHandlers[i].name != 'password') hs.push(Accounts._loginHandlers[i])
}
Accounts._loginHandlers = hs

Related

Update UserIdentities with roles after Azure AD B2C login

I have a Blazor WASM application communicating with a ASP.NET 6 Web API.
User authentication is done via Azure AD B2C by attaching the AD token to Http requests sent to the Server using
builder.Services.AddHttpClient("Portal.ServerAPI", client => client.BaseAddress = new Uri("https://localhost:7001/api/"))
.AddHttpMessageHandler<SslAuthorizationMessageHandler>();
User specific information like UserRoles is stored in a user database.
I'm using the RemoteAuthenticatorView.OnLoginSuceeded handler to load the user profile containing the roles from the API server.
Then I add a new identity to the existing ClaimsPrincipal which I get from the AuthenticationStateProvider like so:
var state = await authStateProvider.GetAuthenticationStateAsync();
var user = state.User;
if (user.Identities.Any(x => x.Label == "myAuthToken"))
{
return;
}
// Turn the JWT token into a ClaimsPrincipal
var principal = tokenService.GetClaimsPrincipal(sslToken);
var identity = new ClaimsIdentity(principal.Identity);
identity.Label = "myAuthToken";
user.AddIdentity(identity);
Not sure if that's the right way to do this but it works fine.
Now my problem:
When I refresh the page by hitting F5 in the browser the above handler is not called and the roles are not written to the new identity, means user.IsInRole("myRole") doesn't work.
Does anyone have an idea how to solve the issue of enriching an existing user identity on Blazor with roles coming from the server?
Any help is much appreciated.

What to do to clear all cache about my client credential in 'logout' function

I made an app in xamarin forms that provides login/logout functionality.
This steps work correctly in UWP:
User start the app
User put correct credential and login (here wrong credential always doesn't work and this is ok)
User click logout
User put wrong credential and can't login
Unfortunately in Android in third step user still can login.
I've tried using functions like Abort() Close() Dispose() on my client. Regardless of that after make new object of my client and put in wrong credential still everything works.
this I make while login
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; // (I can use here NTLM and basic, result is the same)
MyClient myClient = new MyClient(binding, new EndpointAddress(myUrl));
myClient.ClientCredentials.Windows.ClientCredential.UserName = username
myClient.ClientCredentials.Windows.ClientCredential.Password = password;
myClient.ClientCredentials.UserName.UserName = username;
myClient.ClientCredentials.UserName.Password = password;
// this I've tried after logout and idk what I can do more
myClient.InnerChannel.Abort();
myClient.InnerChannel.Close();
myClient.InnerChannel.Dispose();
myClient.Abort();
myClient.Close();
myClient = null;
// Edit
// I used Android.Webkit.CookieManager on Android when logout in this way:
var cookieManager = CookieManager.Instance;
cookieManager.RemoveAllCookie();
cookieManager.RemoveSessionCookie();
cookieManager.RemoveExpiredCookie();
cookieManager.Flush();
// but still the same problem, I'm using Android 8.1 so I don't need CookieSyncManager.Instance.Sync(), because it's deprecated since api 21
I expect that app will prevent from use wrong credential after logout in Android. Currently only UWP provides that succesfully.

Created a mvc5 app with Identity2, how do i set it up to use session cookies, so they expire when the browser closes

Created a mvc5 app with Identity2,using google login (pretty much the empty app, with google stuff turned on)
How do I set it up to use session cookies, so they expire when the browser closes.
The app will be used by students who may hot swap seats, so i need the login to expire when the browser closes.
I read an SO article that implies this is the default, but when i close the browser, and go back to the site, it remembers the google login.
Edit
Sorry to burst everyone bubble, but this isn't a duplicate.
It reproduced in Chrome after the settings in the supposed "answer" are changed, and it also reproduces in IE... This is an Asp.net Identity 2 +Google login issue, not a Chrome issue.
Edit
Adding Startup Auth file for Setup Help
using System;
using System.Configuration;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentPortalGSuite.Models;
namespace StudentPortalGSuite
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes( 30 ),
regenerateIdentity: ( manager, user ) => user.GenerateUserIdentityAsync( manager )
)
},
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// per https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on - EWB
//dev-jcsn email
app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions()
{
ClientId = "...",
ClientSecret = "..."
} );
//});
}
}
}
EDIT
The use case I'm trying to fix is, since our app is used in a classroom, that student A Closes his/her browser instead of logging out, and then next user tries to login. As it stands they are autologged into user A's account.
I'd also be up for a way to 100% log out the user when redirected to the login page, but all the ways I've tried that aren't working.
Maybe you can catch the window close event on page and call logout method
$(window).on("beforeunload", function() {
//ajax call to a post controller that logs the user out
})
Calling this at the top of the LogIn controller Method solved the issue.
Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ApplicationCookie );// https://stackoverflow.com/questions/28999318/owin-authentication-signout-doesnt-seem-to-remove-the-cookie - stralos s answer
Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ExternalCookie );

Handle denied email permission in Facebook

I am trying to build Login with Facebook API manually. I am using https://www.nuget.org/packages/Facebook/ & using following code in my ASP.NET MVC.
Basic idea is to ask users permission, access the users email, auto-register to my system.
Problem is when user un-check access to email & click on Ok on the facebook authentication popup. Next time when user clicks on "Login with Facebook" button, facebook authentication pop-up won't appear, as user has already allowed the access, and I don't get users email. The only way, facebook authentication box re-appear, is user revoke access to my app from his personal facebook account.
Is there another way, I can get the facebook authentication popup again? Or better way to do this?
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = System.Configuration.ConfigurationManager.AppSettings["FacebookAppId"],
client_secret = System.Configuration.ConfigurationManager.AppSettings["FacebookAppSecret"],
redirect_uri = System.Configuration.ConfigurationManager.AppSettings["FacebookRedirectURL"],
code = code
});
var accessToken = result.access_token;
// Store the access token in the session
Session["AccessToken"] = accessToken;
// update the facebook client with the access token so
// we can make requests on behalf of the user
fb.AccessToken = accessToken;
// Get the user's information
dynamic me = fb.Get("me?fields=first_name,last_name,id,email");
if (!String.IsNullOrWhiteSpace(me.email))
{
string email = me.email;
// Register Or login user
}
else
{
// Handle declined email permissions
}

WIF, ADFS 2.0, wsignoutcleanup1.0 and wreply

I have set up a WIF web application, a custom STS and an ADFS 2.0 instance as the go between. I am having a hard time understanding the sign out process for my application. Currently, when my user clicks the sign out button, I am calling this code:
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri("https://myrelyingpartyapp.com/?wa=wsignoutcleanup1.0"));
If I use this code, it works fine. All of the cookies and sessions are disposed of correctly. The only problem is that the browser just displays a little green check after the process is over. Obviously, I want to be redirected back to the login page of the STS. To accomplish this I attempted the following code:
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri("https://myrelyingpartyapp.com/?wa=wsignoutcleanup1.0&wreply=" + HttpUtility.UrlEncode("https://myrelyingpartyapp.com/Default.aspx")));
My belief was that the wreply would cause the user to be redirected back to my relying party app where they would be unauthorized and therefore be redirected back to the STS login page. Instead this causes an error in ADFS (which I cannot see because of their helpful error page.) No matter what url I use for wreply, the error is thrown. Am I using wsignoutcleanup1.0 correctly? Just for reference, here is the code in my STS where I handle sign in/sign out requests:
if (action == "wsignin1.0")
{
SignInRequestMessage signInRequestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
SecurityTokenService securityTokenService = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
SignInResponseMessage signInResponseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(signInRequestMessage, User as ClaimsPrincipal, securityTokenService);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(signInResponseMessage, Response);
}
else
{
throw new UnauthorizedAccessException();
}
}
else if (action == "wsignout1.0")
{
SignOutRequestMessage signOutRequestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(signOutRequestMessage, User as ClaimsPrincipal, signOutRequestMessage.Reply, Response);
}
All I needed for correct behavior was correct logout code. This code eventually logged my user out and did a proper cleanup:
var module = FederatedAuthentication.WSFederationAuthenticationModule;
module.SignOut(false);
var request = new SignOutRequestMessage(new Uri(module.Issuer), module.Realm);
Response.Redirect(request.WriteQueryString());
This code was put in the event handler of my logout button on my relying party app.

Resources