Forgot password in .Net Core 5.0 - asp.net-core

my login and register methods are working well and i use the Claim when the user try to login or logout.
i saw many example of that ForgotMyPassword page but all of it using
private readonly UserManager<IdentityUser> _userManager; which is based on Microsoft.AspNetCore.Identity; . Can i do ForgotMyPassword action without using UserManager
?? im asking that Claim based authentication and authorization is what i need in my project.
can i use them both,if i can how can i do that ?
it would be so great if someone explain its clearly,regards

When users register, their information will be added to the database. You can pass the registered email of the user to the ForgotMyPassword action. Then send a verification code to the mailbox or send a link to make user redirect to another page to reset the password. Make the user finish changing the password.
You can both use authentication and authorization, they are responsible for different businesses. Authentication has cookie, jwt and other authentication service. cookie authentication is the built-in component. Identity has integrated it. You should have learn about it.
The another service is authorization. Authorization service only works after authentication is successful. It has many authorization methods, about claim-based authorization, when one user access the authorized action, it will go through the middleware app.UseAuthorization(). This middleware will check whether there is a claim corresponding to the action policy's claim. Because you have configured it in startup.
services.AddAuthorization(options=>
{
options.AddPolicy("Policy1",policy=>
{
policy.RequireClaim("claim1",new string[] {"value1","value2" });
});
});
On the authorized action.
[Authorize(Policy = "Policy1")]
public IActionResult get()
{
return Ok();
}
In this scenario, the user should have the claim Claim("claim1","value1") or Claim("claim1","value2").

Related

Configure Silent Authentication in Open ID Connect

client type: Spa
grant type: implicit or code(pkce)
As a user, I want to be able to get silently authenticated if I have already logged with my identity provider. If not stay on the client side just like a guest user. And if I want to login to the client I should be able to get authenticated manually through the login page.
This has both manual sign-in and automatic sign-in scenarios. How would you handle such cases in Open ID Connect?
By adding the prompt=none in client settings will silently get a new token if user has a valid session. But if not I want the user to be able to manually authenticate through the login page upon his/her wish.
If I set prompt=none this will never have any user interaction such as authentication.
tags: Silent authentication oidc, automatic login, SSO
It is quite a deep subject, and the flow typically works like this:
CLASSIC OIDC SOLUTION
User is redirected for each SPA
If signed in already at the IDP there is no login prompt
OAuth state is stored in local storage (though it is recommended to only store actual tokens in memory)
When an access token expires (or before) do an iframe token renewal with prompt=none
When a new browser tab is opened do an iframe token renewal to get tokens for that tab - to avoid a full redirect
When the user logs out remove OAuth state from local storage
The most widely used library is OIDC Client which will do a lot of the hard work for you. See also my blog post + code sample for how this looks visually.
PROBLEM AREAS
It is worth being aware also that iframe silent renewal does not work by default in the Safari browser in 2020. Some notes on this here.
Alternatively, you can use signinSilent(). I have used it on my login page ngOnInit (since AuthGuard will anyway redirect the user to login, I thought it will be the perfect place in my scenario).
// login.ts
ngOnInit(): void {
this.authService.signinSilent().then(_ => {}).catch(_ => {});
}
// authService
public signinSilent() {
return this.userManager.signinSilent();
}
signinSilent method will return the user object if user already has a valid session with idp. else it will throw an error, probably login_required.

How signin-google in asp.net core authentication is linked to the google handler?

I went into the source code but I can't see where it's wired to the handler.
In the GoogleExtensions.cs file, I see the
=> builder.AddOAuth<GoogleOptions, GoogleHandler>(authenticationScheme,
displayName, configureOptions);
But I don't understand how the route "/signin-google" calls the handler.
How signin-google in asp.net core authentication is linked to the google handler?
The question can be divided into two small questions .
How user is redirected to the url of /signin-google
How GoogleHandler process the request on /signin-google
How user is redirected to signin-google
Initially, when user clicks the Google button to login with Google Authentication, the browser will post a request to the following url:
https://your-server/Identity/Account/ExternalLogin?returnUrl=%2F
Your server simply redirects the user to Google.com and asks Google to authenticate the current user :
https://accounts.google.com/o/oauth2/v2/auth?
response_type=code
&client_id=xxx
&scope=openid%20profile%20email
&redirect_uri=https%3A%2F%2Fyour-server%2Fsignin-google
&state=xxx
When Google has authenticated the user successfully, it will redirect the user to your website with a parameter of code according to redirect_uri above.
https://your-server/signin-google?
state=xxx
&code=yyy
&scope=zzz
&authuser=0
&session_state=abc
&prompt=none
Note the path here equals /signin-google. That's the first key point.
How GoogleHandler process the signin-google
Before we talk about how GoogleHandler goes , we should take a look at how AuthenticationMiddleware and AuthenticationHandler work:
When there's an incoming request, the AuthenticationMiddleware (which is registered by UseAuthentication() in your Configure() method of Startup.cs), will inspect every request and try to authenticate user.
Since you've configured authentication services to use google authentication , the AuthenticationMiddleware will invoke the GoogleHandler.HandleRequestAsync() method
If needed, the GoogleHandler.HandleRequestAsync() then handle remote authentication with OAuth2.0 protocol , and get the user's identity.
Here the GoogleHandler inherits from RemoteAuthenticationHandler<TOptions> , and its HandleRequestAsync() method will be used by AuthenticationMiddleware to determine if need to handle the request. . When it returns true, that means the current request has been already processed by the authentication handler and there's no further process will be executed.
So how does the HandleRequestAsync() determine whether the request should be processed by itself ?
The HandleRequestAsync() method just checks the current path against the Options.CallbackPath . See source code below :
public abstract class RemoteAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions>, IAuthenticationRequestHandler
where TOptions : RemoteAuthenticationOptions, new()
{
// ...
public virtual Task<bool> ShouldHandleRequestAsync()
=> Task.FromResult(Options.CallbackPath == Request.Path);
public virtual async Task<bool> HandleRequestAsync()
{
if (!await ShouldHandleRequestAsync())
{
return false;
}
// ... handle remote authentication , such as exchange code from google
}
}
Closing
The whole workflow will be :
The user clicks on button to login with Google
Google authenticates the user and redirects him to /signin-google
Since the path== signin-google, the middleware will use HandleRequestAsync() to proecess current request, and exchange code with google.
... do some other things

How to create identity in MVC app with JWT

I'll try to be explicit.
I have a Front End app (MVC), it can communicate with a Facade Web Api (Resource) and get token from an authentication server.
My problem is I can't create an identity in MVC app. This is mu Startup class.
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
When I try to go to a method controller decorated with [Authorize], I get 401 error instead to be redirected to Login page.
Please, I would appreciate any help, advice or example.
Regards,
Typically, unless your app is doing postback's you do not need to enable the cookie authentication with login path. That is for the oauth password login flow (grant_type) where you are internally authorizing your users against your identity database. If you're redirecting to an external authorization api (like facebook) then you don't need to set a login path in your application since the first authorization endpoint that gets hit is your external callback (after you send them to facebook, they will send them back to your external endpoint). The redirect you are getting is because cookie authentication is registered as active authentication mode so it redirects 401's to the login path you set (overriding other OWIN middleware).
If you want to house your authorization server in house, have a look at the link below, it will at the least get you setup with JWT support -
http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

Possible to validate ServiceStack's authentication cookie client side?

I am having a HTML (Angular) site which has a login button and needs (of course) to present a different GUI when the user is authenticated. I am using ServiceStack based REST services. Now when a user is successfully authenticated I was wondering if it is possible to check the generated authentication cookie (by ServiceStack) on the client only. I just need to check the userid, maybe role and expiration date of the cookie. Advantage is I do not have to make 'CheckUserIsAuthenticated' server rest call's just for showing a different GUI (of source CRUD actions are validated serverside).
You can check that a cookie exists with document.cookie, as it's hard to work with directly Mozilla provides a lightweight cookies wrapper to make it easier to work with, likewise AngularJS provides $cookies provider.
But a cookie doesn't tell you anything about the user since even non-authenticated / anonymous users will have cookies. Instead to check if the user is authenticated you can call /auth route via ajax which when authenticated ServiceStack will return summary info about the user, e.g:
{
UserId: "1",
SessionId: "{sessionId}",
UserName: "user#gmail.com",
DisplayName: "First Last"
}
If the user is not authenticated /auth will return 401 Unauthorized.

Owin and Windows Auth (mvc5) - using Windows auth as a part of login

I'm trying to have a MVC5 webapp which partially uses Windows Auth.
What I mean by that is, it's effectively forms/cookie based auth, but with the requesting user's Windows principal forming a part of their login credentials.
For example, the login page will say, "You have been identified as somedomain\kierenj. Please enter the secret code to log in." If they enter the correct code, the cookie is set and they're logged in.
If Windows auth fails, then the login page would still appear, but be disabled.
I've experimented with a WindowsPrincipalHanlder like this: https://github.com/JabbR/JabbR/blob/master/JabbR/Middleware/WindowsPrincipalHandler.cs
The gist of it is, if I enable Windows Authentication and disabled Anonymous Authentication, then Owin (or presumably the cookie auth part of it) redirects to the login page - which redirects to the login page - it's a redirect loop.
Note I'm using a very simplified Owin setup. UseCookieAuthentication with ApplicationCookie type and a LoginPath specified; then I call SignIn like this from my account controller:
var claims = new[] {
new Claim(ClaimTypes.Name, "Username"),
new Claim(ClaimTypes.Role, "AuthenticatedUser")
};
AuthenticationManager.SignIn(new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie));
(Having first checked WindowsIdentity.GetCurrent() for example)
Do I really need to write my own version of the Owin cookie auth middleware? Can I get the source so I can debug/derive?
To avoid the redirect loop, in the constructor of the controller that serves the Login page, try setting current HttpContext's Response.SuppressFormsAuthenticationRedirect to true