How to Disable : Authorise attribute automatically login the user - asp.net-core-2.0

I'm having an issue with identity server.
When unauthenticated If I try to access an action that has the authorize attribute I am taken to the login page to login(as expected)
After I logout then try to access an action that has the authorize attribute, I am given access.
After Logout When I access non secure action I can see that User.Identity.IsAuthenticated is false but when I try to access a secure action , I am granted access and I see that User.Identity.IsAuthenticated is true.
I assume that this is part of the functionality. How can I disable it?

It turns out I had a bug
Log out Code:
public async Task<ActionResult> LogOut()
{
await HttpContext.SignOutAsync("Cookies");
await HttpContext.SignOutAsync("oidc");
return RedirectToAction("Index");
}
Changed to :
public IActionResult Logout()
{
return new SignOutResult(new[] { "Cookies", "oidc" });
}

Related

Unable to Sign-out using Azure AD Authentication on a .Net Core Web App

I am unable to signout from a .Net core Web App while using Azure AD to login.
When i try to login using a different email, its just logging in as the previous user who logged in. Its not even asking for password when the new user is trying to login.
I have tried the following approaches but -
// Send an OpenID Connect sign-out request.
HttpContext.GetOwinContext().Authentication.SignOut(
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
OR
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
or
if (HttpContext.User.Identity.IsAuthenticated)
{
await HttpContext.Authentication.SignOutAsync(settings.SignInPolicyId);
await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
None of these work on .Net Core.
This code below builds and runs on .net core but it doesnt completely logout the user.
Request.GetOwinContext().Authentication.SignOut(new AuthenticationProperties { RedirectUri = clsCommonFunction.GetLoginURL() });
Please help.
Here is the SignOut method for ASP.NET Core.
[HttpGet]
public IActionResult SignOut()
{
var callbackUrl = Url.Action(nameof(SignedOut), "Account", values: null, protocol: Request.Scheme);
return SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
[HttpGet]
public IActionResult SignedOut()
{
if (User.Identity.IsAuthenticated)
{
// Redirect to home page if the user is authenticated.
return RedirectToAction(nameof(HomeController.Index), "Home");
}
return View();
}
Its not even asking for password when the new user is trying to
login.
Please clear the browser cache Ctrl+F5.

Google SignIn returns Current user as null

I am using google login for my Xamarin iOS app, however after successfully entering the username and password in the safari browser prompt that appears, It returns properties CurrentUser as null.
My Code:
Google.SignIn.SignIn.SharedInstance.Delegate = this;
Google.SignIn.SignIn.SharedInstance.UIDelegate = this;
Google.SignIn.SignIn.SharedInstance.SignInUser();
Google.SignIn.SignIn.SharedInstance.SignedIn += SharedInstance_SignedIn;
private void SharedInstance_SignedIn(object sender, SignInDelegateEventArgs e)
{
var signin = (Google.SignIn.SignIn)sender;
//Here if i debug signin variable, its property CurrentUser comes as null
}
I am using
Xamarin.IOS.Google.Signin: v4.0.1.1
Am I missing some setting that needs to be enabled in the Google api console?
Sender indicate the class that raised the event.
To get User ,you can use e.User Or Google.SignIn.SignIn.SharedInstance.CurrentUser
here explatins the function of method SignIn
The Sign-In SDK automatically acquires access tokens, but the access tokens will be refreshed only when you call SignIn or SignInSilently methods.

External Login WebAPI2 MVC5

I need to use a 3rd party token as a way to authenticate. I'm getting the token in the home controller and need to be able to send it on to my WebAPI controllers (It's an SPA application using Backbone). Is there a way of doing this?
EDIT:
Relevant code:
public ActionResult Index(string projectId, int companyId, bool isCompanyAdmin)
{
// if not a valid user return error
var validate = new Validate().ValidateContext(HttpContext,
"Key", "Secret");
if (!validate.IsValidated) return View(Constants.ValidationFailed);
// The info validated, so now I can set it to authorized
// put code here for doing it
//Get the model for the user
try
{
var model = ConvertToVM(_smsRepository.GetCompany(companyId, projectId));
}
catch (ProviderIncompatibleException)
{
// connection string wrong
return View(Constants.ConnectionFailed);
}
catch (Exception e)
{
// catch all
return View(Constants.DatabaseError);
}
//create and send through the view model that determines what view the user will get
return View(model);
}
Ok I put in the index method on the Home Controller. Like I said, we make a call to a third party API passing in the context, the client key, and the client secret to verify our identity. Could I just add a Bearer token in the home controller? Or otherwise pass the http context to OWiN and use some custom logic to add the token if validate.IsValidated is true? It needs to be something that works with WebAPI.

Identity 2.0 After Login go to Infinite Loop asp.net mvc 5

I have added email confirmation process like below:
var code = await _users.GenerateEmailConfirmationTokenAsync(model.UserName);
var callbackUrl = Url.Action(
"ConfirmEmail", "Account",
new { username = model.UserName, code = code },
protocol: Request.Url.Scheme);
then confirm email with below code:
public async Task ConfirmationEmailAsync(CmsUser user, string token)
{
var provider = new DpapiDataProtectionProvider(WebConfigurationManager.AppSettings["AppName"].ToString());
_manager.UserTokenProvider = new DataProtectorTokenProvider<CmsUser>(
provider.Create("EmailConfirmation"));
await _manager.ConfirmEmailAsync(user.Id, token);
}
after that I will login it will go to infinite loop.
http://localhost:3214/account/login?ReturnUrl=%2Faccount%2Flogin%3FReturnUrl%3D%252Faccount%252Flogin%253FReturnUrl%253D%25252Faccount%25252Flogin%25253FReturnUrl%25253D%2525252Faccount%2525252Flogin%2525253FReturnUrl%2525253D%252525252Faccount%252525252Flogin%252525253FReturnUrl%252525253D%25252525252Faccount%25252525252Flogin%25252525253FReturnUrl%25252525253D%2525252525252Faccount%2525252525252Flogin%2525252525253FReturnUrl%2525252525253D%252525252525252Faccount%252525252525252Flogin%25252525252525...
Here, I have calling below method:
public async Task<string> GenerateEmailConfirmationTokenAsync(CmsUser user)
{
var provider = new DpapiDataProtectionProvider(WebConfigurationManager.AppSettings["AppName"].ToString());
_manager.UserTokenProvider = new DataProtectorTokenProvider<CmsUser>(
provider.Create("EmailConfirmation"));
return await _manager.GenerateEmailConfirmationTokenAsync(user.Id);
}
The problem is not about your Generate EMail action. It is about your authentication.
Probably, your Login action in Account controller is requiring authorization. For instance, you can have AuthorizeAttribute on an action or a controller. Maybe, it's a global filter or something's wrong with Web.config.
Anyway, that's what actually happens:
User tries to access your Generate EMail method
He is unauthorized. Then, he is redirected to Account / Login method.
This method requires authorization. Goto 2.
You need to review your authentication, debug it and find the basic problem before you continue implementing your EMail confirmation.

Access to WebAPI 2.2 from mvc application after Logging In

I have MVC 5 application that uses Form Authentication (the same as in default MVC 5 project template). The same project contains WebAPI 2.2 controller that provides some API the application uses.
I would like to have two type of access to the API by using Bearer Tokens. The API will be invoked via javascript. I added code to do that using http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api.
The problem is that the example code gets token by making call to separate API and providing username and password. What I would like to achieve is to return Bearer Token after the user successfully logs in into MVC application and not by making another call in javascript.
Is this possible ?
Update:
I would like to return token in Login action of Account controller by using header. However probably because of redirections the header is discarded.
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
You can use Oauth authentication thereby which you can generate an access token and can be used the same for further requests to the web API. This access token can be saved in db or somewhere for using in future requests.

Resources