Single page redirect issue for public url using thinktecture - asp.net

I am creating a single page application with angularJs, aspnet and thinktecture. I have created a login screen in thinktecture (as localhost:44304) for customer login and after successful login, it redirects to customer portal like https://localhost:44302.
when I run the customer app then it redirected to thinktecture login screen and after a login success, it come back to customer portal.
Now issue is that any customer can register a request by using registration page which is placed on the customer portal and we are redirecting it from thinktecture login screen as shown
When I click on "here" link then redirect me again same login screen.
I added the code as below in startup.cs for customer poratal.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
string thinkTectureUrl = ConfigurationManager.AppSettings["ThinkTectureUrl"].ToString();
string loginSuccessUrl = ConfigurationManager.AppSettings["LoginSuccessUrl"].ToString();
string clientSecret = ConfigurationManager.AppSettings["ClientSecret"].ToString();
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
ClientId = "Provista.CustomerPortal.WebApp.External",
Authority = thinkTectureUrl,
RedirectUri = loginSuccessUrl,
ResponseType = "id_token",
Scope = "openid email",
SignInAsAuthenticationType = "Cookies",
ClientSecret = clientSecret.Sha256()
});
I searched on google and stackoverflow a lot but didn't get a reliable link that help me to solve this.
Please reply as soon as possible if any one have any idea.

You might have global authorization filter which redirects unauthenticated users to identity server. Probably in Global.asax
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
Requests to your 'Register User controller' also treated by this filter and redirect to identity server will happen.
To override global filter and allow unauthenticated users to your Register User controller use [AllowAnonymous] attribute in your 'Register User controller'.

Related

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 );

How do I issue the corresponding Bearer and Cookie identity in ASP.NET with multiple Authorization schemes?

This documentation describes in part how to use more than one authentication scheme:
In some scenarios, such as Single Page Applications it is possible to end up with multiple authentication methods. For example, your application may use cookie-based authentication to log in and bearer authentication for JavaScript requests. In some cases you may have multiple instances of an authentication middleware. For example, two cookie middlewares where one contains a basic identity and one is created when a multi-factor authentication has triggered because the user requested an operation that requires extra security.
Example:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = false
});
app.UseBearerAuthentication(options =>
{
options.AuthenticationScheme = "Bearer";
options.AutomaticAuthenticate = false;
});
However it only describes how to use Bearer or Cookie auth. What isn't clear is what other combinations are valid, or how to properly issue bearer or cookies to the client.
How can that be accomplished?
One common use case for this which large sites like Facebook, Google etc. use is to use multiple cookie authentication middleware's and set one of them to be the default using AutomaticAuthenticate
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "InsecureLongLived",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true
});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "SecureAndShortLived",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = false
});
The default one is long lived and used for non-critical auth scenarios e.g. on Facebook, this may be to view your profile page.
The more secure and short lived on is used for security critical user actions like changing your password or profile information.
This gives you the convenience of not having to login all the time with a long lived cookie but as soon as you need to do something potentially dangerous, you switch to doing auth with a much shorter lived and thus more secure cookie which requires the user to login again.

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
}

Getting an "Unauthorized" error in Dropnet

I'm using Asp.net MVC 4 and Dropnet to download a file from my DropBox account. I'm not sure what is wrong with my code but I get a error whenever I run my project,
Received Response [Unauthorized] : Expected to see [OK]. The HTTP response was [{"error": "Request token has not been properly authorized by a user."}].
Here are my codes,
public ActionResult DropDls()
{
var _client = new DropNetClient("API KEY", "API SECRET");
DropNet.Models.UserLogin login = _client.GetToken();
_client.UserLogin = login;
var url = _client.BuildAuthorizeUrl();
var accessToken = _client.GetAccessToken();
var fileBytes = _client.GetFile("/Getting Started.pdf");
return View();
}
I want only my Dropbox account to be accessed so I need to know how can I give my own USER TOKEN and USER SECRET. I've searched on the web for a solution but couldn't find anything that'll help me.
The problem is you are not getting the user to login before trying to access their dropbox account.
This line should not be there _client.UserLogin = login;
and after this line var url = _client.BuildAuthorizeUrl(); you will need to redirect the user to that url so they can login, then the dropbox site will redirect them back to your site which is when you make the call _client.GetAccessToken(); then you will have access to the users dropbox account.

This webpage has a redirect loop when login Facebook by Firebase

Follow code worked fine with a user already authenticated with my facebook application. But throw a error: "This webpage has a redirect loop" when use a new user.
var myRootRef = new Firebase('https://tttb-demo.firebaseio.com/');
var auth = new FirebaseSimpleLogin(myRootRef, function (error, user) {
});
auth.login('facebook', {
rememberMe: true,
scope: 'email,read_friendlists'
});
I had this problem.
Either:
1) Take your app out of Sandbox mode on Facebook
or
2) Add the user to the list of developers on Facebook.
It's because only you are authorised to access it by default when you create an app in Facebook.

Resources