ASP.net core, AddSignInManager to get notification when a loggin happens - asp.net-core

I am trying to get a notification for sign-in.
For this purpose, I created a custom SignInManager and overridden the method used to sign in .
Now if I do the following it works:
builder.Services.AddDefaultIdentity<IdentityUser>(options =>
{
// ...
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager<MySignMan<IdentityUser>>();
But in my code, I use AddIdentity instead of AddDefaultIdentity, and I don't find how to make it work without DefaultIdentity

Can this work for you?
builder.Services.AddIdentity<IdentityUser, IdentityRole>(option =>
{
option.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>().AddSignInManager<MySignManager<IdentityUser>>();

Related

cypress cy.request 401 unauthorized [duplicate]

I want to save/persist/preserve a cookie or localStorage token that is set by a cy.request(), so that I don't have to use a custom command to login on every test. This should work for tokens like jwt (json web tokens) that are stored in the client's localStorage.
To update this thread, there is already a better solution available for preserving cookies (by #bkucera); but now there is a workaround available now to save and restore local storage between the tests (in case needed). I recently faced this issue; and found this solution working.
This solution is by using helper commands and consuming them inside the tests,
Inside - cypress/support/<some_command>.js
let LOCAL_STORAGE_MEMORY = {};
Cypress.Commands.add("saveLocalStorage", () => {
Object.keys(localStorage).forEach(key => {
LOCAL_STORAGE_MEMORY[key] = localStorage[key];
});
});
Cypress.Commands.add("restoreLocalStorage", () => {
Object.keys(LOCAL_STORAGE_MEMORY).forEach(key => {
localStorage.setItem(key, LOCAL_STORAGE_MEMORY[key]);
});
});
Then in test,
beforeEach(() => {
cy.restoreLocalStorage();
});
afterEach(() => {
cy.saveLocalStorage();
});
Reference: https://github.com/cypress-io/cypress/issues/461#issuecomment-392070888
From the Cypress docs
For persisting cookies: By default, Cypress automatically clears all cookies before each test to prevent state from building up.
You can configure specific cookies to be preserved across tests using the Cypress.Cookies api:
// now any cookie with the name 'session_id' will
// not be cleared before each test runs
Cypress.Cookies.defaults({
preserve: "session_id"
})
NOTE: Before Cypress v5.0 the configuration key is "whitelist", not "preserve".
For persisting localStorage: It's not built in ATM, but you can achieve it manually right now because the method thats clear local storage is publicly exposed as Cypress.LocalStorage.clear.
You can backup this method and override it based on the keys sent in.
const clear = Cypress.LocalStorage.clear
Cypress.LocalStorage.clear = function (keys, ls, rs) {
// do something with the keys here
if (keys) {
return clear.apply(this, arguments)
}
}
You can add your own login command to Cypress, and use the cypress-localstorage-commands package to persist localStorage between tests.
In support/commands:
import "cypress-localstorage-commands";
Cypress.Commands.add('loginAs', (UserEmail, UserPwd) => {
cy.request({
method: 'POST',
url: "/loginWithToken",
body: {
user: {
email: UserEmail,
password: UserPwd,
}
}
})
.its('body')
.then((body) => {
cy.setLocalStorage("accessToken", body.accessToken);
cy.setLocalStorage("refreshToken", body.refreshToken);
});
});
Inside your tests:
describe("when user FOO is logged in", ()=> {
before(() => {
cy.loginAs("foo#foo.com", "fooPassword");
cy.saveLocalStorage();
});
beforeEach(() => {
cy.visit("/your-private-page");
cy.restoreLocalStorage();
});
it('should exist accessToken in localStorage', () => {
cy.getLocalStorage("accessToken").should("exist");
});
it('should exist refreshToken in localStorage', () => {
cy.getLocalStorage("refreshToken").should("exist");
});
});
Here is the solution that worked for me:
Cypress.LocalStorage.clear = function (keys, ls, rs) {
return;
before(() => {
LocalStorage.clear();
Login();
})
Control of cookie clearing is supported by Cypress: https://docs.cypress.io/api/cypress-api/cookies.html
I'm not sure about local storage, but for cookies, I ended up doing the following to store all cookies between tests once.
beforeEach(function () {
cy.getCookies().then(cookies => {
const namesOfCookies = cookies.map(c => c.name)
Cypress.Cookies.preserveOnce(...namesOfCookies)
})
})
According to the documentation, Cypress.Cookies.defaults will maintain the changes for every test run after that. In my opinion, this is not ideal as this increases test suite coupling.
I added a more robust response in this Cypress issue: https://github.com/cypress-io/cypress/issues/959#issuecomment-828077512
I know this is an old question but wanted to share my solution either way in case someone needs it.
For keeping a google token cookie, there is a library called
cypress-social-login. It seems to have other OAuth providers as a milestone.
It's recommended by the cypress team and can be found on the cypress plugin page.
https://github.com/lirantal/cypress-social-logins
This Cypress library makes it possible to perform third-party logins
(think oauth) for services such as GitHub, Google or Facebook.
It does so by delegating the login process to a puppeteer flow that
performs the login and returns the cookies for the application under
test so they can be set by the calling Cypress flow for the duration
of the test.
I can see suggestions to use whitelist. But it does not seem to work during cypress run.
Tried below methods in before() and beforeEach() respectively:
Cypress.Cookies.defaults({
whitelist: "token"
})
and
Cypress.Cookies.preserveOnce('token');
But none seemed to work. But either method working fine while cypress open i.e. GUI mode. Any ideas where I am coming short?
2023 Updated on Cypress v12 or more:
Since Cypress Version 12 you can use the new cy.session()
it cache and restore cookies, localStorage, and sessionStorage (i.e. session data) in order to recreate a consistent browser context between tests.
Here's how to use it
// Caching session when logging in via page visit
cy.session(name, () => {
cy.visit('/login')
cy.get('[data-test=name]').type(name)
cy.get('[data-test=password]').type('s3cr3t')
cy.get('form').contains('Log In').click()
cy.url().should('contain', '/login-successful')
})

How to use UseExceptionHandler in the mvc startup without redirecting the user?

I have a ASP.NET Core 2.1 MVC application, and I'm trying to return a separate html view when an exception occurs. The reason for this is that if there are errors, we don't want google to register the redirects to the error page for our SEO (I've omitted development settings to clear things up).
Our startup contained this:
app.UseExceptionHandler("/Error/500"); // this caused a redirect because some of our middleware.
app.UseStatusCodePagesWithReExecute("/error/{0}");
But we want to prevent a redirect, so we need to change the UseExceptionHandler.
I've tried to use the answer from this question like below:
app.UseExceptionHandler(
options =>
{
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("sumtin wrong").ConfigureAwait(false);
});
});
But this gives a very ugly page without any styling. Another solution we've tried to use is creating an error handling middle ware, but there we run into the same problem there where we can't add a view.
How can I return a styled view in case of an exception, without redirecting the user?
EDIT: the UseExceptionHandler doesn't cause a redirect, it was caused by a bug in some of our middleware.
How can I return a styled view in case of an exception, without redirecting the user?
You're almost there. You could rewrite(instead of redirect) the path, and then serve a HTML according to current path.
Let's say you have a well-styled sth-wrong.html page in your wwwroot/ folder. Change the code as below:
app.UseExceptionHandler(appBuilder=>
{
// override the current Path
appBuilder.Use(async (ctx, next)=>{
ctx.Request.Path = "/sth-wrong.html";
await next();
});
// let the staticFiles middleware to serve the sth-wrong.html
appBuilder.UseStaticFiles();
});
[Edit] :
Is there anyway where I can make use of my main page layout?
Yes. But because a page layout is a View Feature that belongs to MVC, you can enable another MVC branch here
First create a Controllers/ErrorController.cs file :
public class ErrorController: Controller
{
public IActionResult Index() => View();
}
and a related Views/Error/Index.cshtml file:
Ouch....Something bad happens........
Add a MVC branch in middleware pipeline:
app.UseExceptionHandler(appBuilder=>
{
appBuilder.Use(async (ctx, next)=>{
ctx.Request.Path = "/Error/Index";
await next();
});
appBuilder.UseMvc(routes =>{
routes.MapRoute(
name: "sth-wrong",
template: "{controller=Error}/{action=Index}");
});
});
Demo:

Recommend way to make a UI middleware in aspnet core 1

I am trying to make a UI middleware and wanted to know what's the recommended way to go about it.
Should I do a AddMVC again in my middleware and give it a custom route or go by embedding resources.
I tried to make a MVC inside my middleware and I am able to hit the controller with the custom route but not the views in my middleware project. The sample website seems to always only look inside the main MVC views folder.
Let me know if you need more information and I will update the question accordingly.
Try to use embed views. You need to add:
"buildOptions": { "embed": [ "Views/**" ] },
Then you should tell mvc to look inside embed files
services
.AddMvc()
.AddRazorOptions(
o =>
{
o.FileProviders.Add(new EmbeddedFileProvider(yourAssembly, yourAssembly.GetName().Name));
}
);
You alse could try application parts:
AssemblyPart part = new AssemblyPart(yourAssembly);
mvcBuilder.ConfigureApplicationPartManager(manager =>
{
manager.ApplicationParts.Add(part);
});
foreach (var applicationPart in mvcBuilder.PartManager.ApplicationParts)
{
var assemblyPart = applicationPart as AssemblyPart;
if (assemblyPart != null)
{
mvcBuilder.AddRazorOptions(options =>
{
options.FileProviders.Add(new EmbeddedFileProvider(assemblyPart.Assembly, applicationPart.Name));
});
}
}
Hope it helps

Laravel Multi-role unable to create in laravel 5

I am having trouble creating multi-role application in laravel5 since in laravel 5 the authentication is pre defined so I am not willing to mess around with predefined codes of laravel 5 authentication. I have a constructor that authenticates every controller in my project but I am unable to check user roles for the following roles:-
1. Admin
2. Agent
3. User
I can check manually for every functions but that is not the right process of doing so and if I have a total of around 500 functions I cant go in every function and define manually. please any help
Thank you
Personally I would use middleware and route groups to accomplish the task, which would be similar the way Laravel checks for user authentication.
You just have to determine when you need to run the middleware, which can be done by nesting Route::group's or injecting the middleware from your controller.
So, for an example of nesting you can have something like this in your routes file:
Route::group(['middleware' => ['auth']], function () {
Route::get('dashboard', ['as' => 'dashboard', function () {
return view('dashboard');
}]);
Route::group(['prefix' => 'company', 'namespace' => 'Company', 'middleware' => ['App\Http\Middleware\HasRole'], function () {
Route::get('dashboard', ['as'=>'dashboard', function () {
return view('company.dashboard');
}]);
Route::resource('employees', 'EmployeesController');
...
...
});
});
or you can inject the middleware to your controllers like so:
use Illuminate\Routing\Controller;
class AwesomeController extends Controller {
public function __construct()
{
$this->middleware('hasRole', ['only' => 'update'])
}
}
And then add a one or more Middleware files using something like php artisan make:middleware HasRole which will give you the middleware boiler plate which you could then add your role checking logic:
<?php namespace App\Http\Middleware;
use Closure;
class HasRole {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->is('admin/*')){
[******ADD YOUR LOGIC HERE TO DETERMINE THE ROLE ******]
[******YOU CAN ALSO INCLUDE ANY REDIRECTS IF NECESSARY******]
}
return $next($request);
}
}
Notice I used the $route->is('admin/*') to filter any routes as an example of further filtering requests, which you would probably not include if you are injecting the middleware from the controller.
But if the user passes the required role check you do not need to do anything and they will be allowed to continue to the view. If they fail the role check, you can handle that accordingly, but beware of getting them caught in a failed permission loop.
I assume you get the gist of it, feel free to look into the Laravel middleware docs for more info.

'auth' Middleware with Route::resource

How can I use middleware with resources?
Route::resource('myitem', ['middleware' => 'auth', 'uses' => 'App\\Controllers\\MyitemsController']);
Just followed https://laracasts.com/discuss/channels/general-discussion/struggling-with-routeresource-and-auth-middleware but unfortunately could not solve.
Getting error:
ErrorException (E_UNKNOWN)
Array to string conversion
Open: /vendor/laravel/framework/src/Illuminate/Routing/Router.php
protected function getResourceAction($resource, $controller, $method, $options)
{
$name = $this->getResourceName($resource, $method, $options);
return array('as' => $name, 'uses' => $controller.'#'.$method);
}
Using filter with resource was not working that why had to use Route::group
Route::group(array('before' => 'auth'), function()
{
Route::resource('myitem', 'App\\Controllers\\MyitemsController');
});
https://stackoverflow.com/a/17512478/540144
Middleware is a new feature of Laravel 5. In Laravel 4, filters where something similar. So instead of using the key middleware you should use before or after. Also, and that's where the error comes from, the second argument of Route::resource should be the controller name as string and the third one is an array of options:
Route::resource('myitem', 'App\\Controllers\\MyitemsController', ['before' => 'auth']);
Edit
Apparently before filters only work with resource routes when you wrap a group around it. See the OPs answer for an example...
I just came up against this and found the easiest way is to add the middleware straight to the controller.
I found my answer here:
http://laravel.com/docs/master/controllers
class MyitemsController extends Controller {
/**
* Instantiate a new MyitemsController instance.
*/
public function __construct()
{
$this->middleware('auth');
}
}
How to do this in Laravel 5. The Answer you have been waiting for.
Use middleware instead of before
Route::group(array('middleware' => 'auth'), function()
{
Route::resource('user', 'UserController',
['only' => ['edit']]);
}
To check if the route is setup, run:
php artisan route:list
which should show the following:
GET|HEAD | user/{user}/edit | user.edit | App\Http\Controllers\UserController#edit | auth
Note auth instead of guest
Better solution
Use middleware instead of before
Route::group(['middleware' => 'auth'], function(){
Route::resource('myitem', 'MyitemsController');
});
You can check if it's ok with:
php artisan route:list