create login in asp.net(Proprietary of admin login) - asp.net

the name of God
and Hi to you
I created some login pages in asp.net
i want use SHA-1 algoritm for my passwords, it's mean, controller get password then send to SHA-1 function and then save it to db.
first: I have these cods in cshtml
<input type="text" name="Username" required="required" />
<label for="Username">Username</label>
<div>
<input type="password" name="Password" required="required"/>
<label for="Password">Password</label>
</div>
<div type="submit" class="button-container">
<button><span>Go</span></button>
</div>
after submit username and pass will be checked and if those be true an new page will be open and user login happen successfully but I don't have any idea about to show my login happened, let explain it whit a sample
I submit my login page and then this page will be open :http://localhost:19926/Home/Home because I used these codes(%1)
in html:
#using (Html.BeginForm("webAdminAccess", "Authentication")){
...myhtml codes...}
in controller:
public ActionResult webAdminAccess(string Username, string Password)
{
if (mLO.webAdminAccess(Username, Password))
{
return RedirectToAction("Home", "Home");
}
else
{
return View("webAdminAccessWrong");
}
}
and there is no difference if I run my project in visual and I put this link http://localhost:19926/Home/Home in my brower(%2)
now let me ask my question:
how make a difference between these two?(%1,%2)
what is Characteristic or Proprietary of a page that was open whit a login?
how make a difference between login as admin or login as client?
(I have admin class, authenticationController and use my sql)
tnx for you help

Related

405 (Method Not Allowed) in live Shared hosting - Laravel and Vue3 with Vite

So, this is my first post on stack, if I missed something please let me know.
So I have project that's working well on localhost Dev but when i uploaded to the server the API given 405 method not allowed.
I have a login form:
<form #submit.prevent="login" method="POST">
<input type="hidden" name="_token" :value="form.csrf">
<p><input type="email" name="login" placeholder="Username or Email" v-model="form.email"></p>
<p><input type="password" placeholder="Please Enter Password" v-model="form.password"></p>
<p class="remember_me">
</p>
<p class="submit"><input type="submit" value="Login"></p>
</form>
The form has some inputs, a textarea and a file input. Those are my routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::controller(AuthController::class)->group(function(){
Route::post('/login', 'login');
});
When I submit the form I get the The GET method is not supported for this route. Supported methods: POST. error.
Here is my Route list :
enter image description here
after everything possible things updating still on same error.
enter image description here
In Chrome network tab showing this
enter image description here
Maybe you guys have any idea what is happening here and point me in the right direction.
Thanks!

ASP.NET CORE MVC CRUD operation. Create form doesn't work anymore

Im am currently working on my CRUD operations for the website. On the attached pictures you can see that im using the create form for 2 purposes. 1. to create a user and 2 to edit a user. My Query is made well but when im adding a hidden id to get a certain user for editing. I cannot press create user anymore because i passed the piece of code in at picture 1. (the line i selected)
But when i remove this piece of code i can create a user but when im trying to edit a user when removing this piece of code it just edits the user and then creates a new one with the edited content. Does anyone know how to fix this issue?
p.s. i made screenshots of the controller and the piece of code where it goes wrong.
Kind regards,
Sem
[Piece of code where it goes wrong][1] [User controller][2] [User
controller][3] [Data transfer objects][4] [CreateOrUpdate
query/function][5]
[1]: https://i.stack.imgur.com/5XxDe.jpg [2]:
https://i.stack.imgur.com/s5pqh.jpg [3]:
https://i.stack.imgur.com/2vLXM.jpg [4]:
https://i.stack.imgur.com/R2OBn.jpg [5]:
https://i.stack.imgur.com/ADyv5.jpg
As per your screenshot you are calling same action method from UI, in that case you need to validate id in your action method to see if it valid then its update otherwise it will be add. Scenario first time your page loaded id will be empty and second time if you load then it will have id and same you can use for edit.
Hope this solve your problem 👍
First, you can copy your code using '{}' in above toolbar, so it will be more convenient for others to test your code.
but when im trying to edit a user when removing this piece of code it just edits the user and then creates a new one with the edited content.
You can check the database for the passed model, if id exists, create one, but if not, remove the old one and create this new one.
Here is a demo with linq, you can check the logic and modify my code to yours:
public async Task<IActionResult> ProcessCreate(UsersDto user)
{
if (!_context.UsersDtos.Any(x => x.Id == user.Id)) //if not exist, create one directly
{
_context.Add(user);
await _context.SaveChangesAsync();
}
else { //else, delete old one and create new one
var therow = _context.UsersDtos.Where(x => x.Id == user.Id).FirstOrDefault();
_context.Remove(therow);
_context.Add(user);
await _context.SaveChangesAsync();
}
return RedirectToAction("Index");
}
In Create.cshtml,you can show the id:
<form method="post" asp-action="ProcessCreate">
<div class="form-group" hidden>
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="First_name" class="control-label"></label>
<input asp-for="First_name" class="form-control" />
<span asp-validation-for="First_name" class="text-danger"></span>
</div>
//.......
<div class="form-group">
<input type="submit" value="CreateOrEdit" class="btn btn-primary" />
</div>
Result:

How to generate Joomla login token from outside Joomla

Here's the context. I have a Joomla Backend with tons of custom code in a very old Joomla 1.X version. Everything is still surprisingly holding up well. The site owner wants a new front facing website and his company chose WordPress. Website was built, now we want to add a log in form to the Joomla backend from a WP page.
Here's what worked:
Go to Joomla login page (domain.com/administrator)
Copy the HTML form (including hidden input with token)
Paste the HTML and adjust the action attribute of the form
Went to the WP page (domain.com/wordpressFolder/page, entered credentials and it works perfectly!
Obviously these tokens can only be used once. Added a shortcode in WP that gets the form from Joomla and "extract" the token and returns it to the page.
function st_login_form( $atts ) {
$joomla = file_get_contents('http://www.example.com/administrator/index.php');
$doc = new DOMDocument();
$doc->loadHTML($joomla);
$inputs = $doc->getElementsByTagName('input');
$token = $inputs[5]->attributes[1]->nodeValue;
$html = '<form action="https://www.example.com/administrator/index.php" method="post" name="login" id="form-login" style="clear: both;">
<p id="form-login-username">
<label for="modlgn_username">Username</label>
<input name="username" id="modlgn_username" type="text" class="inputbox" size="15">
</p>
<p id="form-login-password">
<label for="modlgn_passwd">Password</label>
<input name="passwd" id="modlgn_passwd" type="text" class="inputbox" size="15">
</p>
<input type="submit" value="Connexion" />
<input type="hidden" name="option" value="com_login">
<input type="hidden" name="task" value="login">
<input type="hidden" name="'.$token.'" value="1">
</form>';
return $html;
}
The code behaves has expected and inspecting the form on the WP page with injected token looks fine, however when logging in it gives me an invalid token error.
I don't quite understand why it works when copy pasting but not when I retrieve the token from PHP. Any clue or potential solutions?
Found my first mistake. The GET is done over HTTP while the POST is sent over HTTPS. Obviously, CSRF token are domain-signed.
Now it simply redirects me to the login page but I'm not logged in.

User authentication never invoke

I tried to authenticate user from MySQL database with BCrypt using this
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery(USER_LOGIN_QUERY).authoritiesByUsernameQuery(GET_USER_ROLE_QUERY)
.dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
}
on those requests here
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/reg").permitAll().anyRequest().hasAuthority("ADMIN").anyRequest()
.authenticated().and().csrf().disable().formLogin().loginPage("/login").failureUrl("/login?error=true")
.defaultSuccessUrl("/").usernameParameter("username").passwordParameter("password").and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
.exceptionHandling().accessDeniedPage("/403");
}
on Login page
<div class="login-page">
<div class="form">
<form class="login-form" th:action="#{/login}" method="post">
<input type="text" placeholder="Username" id="username"
name="username" />
<input type="password" placeholder="Password" id="password"
name="password" />
<button type="submit">login</button>
<p class="message">
Not registered?
<a th:href="#{/reg}">Create an account</a>
</p>
</form>
<label th:if="${param.error}"
class="message text-danger text-capitalize">Login
credentials invalid</label>
</div>
</div>
Both overridden 'configure' methods do invoke when Web bootup. As I did put syserr to print out a random line to console from both.
I setup the datasource in application.properties and confirm it's correct since I can sign-up new user successfully. It's autowired
The USER_LOGIN_QUERY and GET_USER_ROLE_QUERY is normal too, it worked on MySQL query.
bCryptPasswordEncoder works since registering new user does encode password into hashed string. It's autowired
With jpa.show-sql = true, registering user(save to database) and other query do show SQL in the console. However, the two queries for authentication DON'T show up in the console log. So I assume login with post method never invoke authentication, hence, datasource, queries and passwordEncoder are not related
As a result, login always redirect me to failureUrl.
Where did I do wrong? How can I properly do authentication?
PS: On the other note,I follow the tutorial here https://github.com/gustavoponce7/SpringSecurityLoginTutorial , I build and run this tutorial source with no problem like above.
UPDATE: I tried new Spring Boot project, repeated the procedure to make a plain simple Spring Web with Security. jdbcAuthentication does authenticate for sometimes but giving me SQL query error. After correcting query error, BOOMM, nothing works again, even reverting edit won't do anything.

ASP.NET MVC On form post, how to get the check status of a checkbox in the view?

In a system where I am using the Identity framework, I have the following form in a view that is bound to the model AppUser:
<div class="form-group">
<label>Name</label>
<p class="form-control-static">#Model.Id</p>
</div>
#using (Html.BeginForm("Edit", "Admin", new { returnUrl = Request.Url.AbsoluteUri }, FormMethod.Post, new { #id = "edituserform" }))
{
#Html.HiddenFor(x => x.Id)
<div class="form-group">
<label>Email</label>
#Html.TextBoxFor(x => x.Email, new { #class = "form-control" })
</div>
<div class="form-group">
<label>Password</label>
<input name="password" type="password" class="form-control" />
</div>
<input type="checkbox" name="userLockout" value="Account Locked" #(Html.Raw(Model.LockedOut ? "checked=\"checked\"" : "")) /> #:Account Locked <br>
<button type="submit" class="btn btn-primary">Save</button>
<button class="btn btn-default"
id="canceleditbutton">
Cancel
</button>
}
The model definition for AppUser:
public class AppUser : IdentityUser
{
public bool LockedOut { get; set; }
/*Other fields not shown for brevity*/
}
My specific question is regarding the checkbox for the LockedOut flag, which is a custom property I added. For a test user, I manually set the flag in the database to True and as expected, on the view the checkbox was checked when it was loaded. Now my goal is to be able to access this in the POST edit method of the AdminController that this form calls on submit. The skeleton for that method is as follows:
[HttpPost]
public async Task<ActionResult> Edit(string id, string email, string password, string userLockout)
{
//Code here to change the LockedOut value in the database based on the input received
}
The issue is that the userLockout parameter comes in as null when I click Save on the submit on the edit screen. The other two values are populated correctly. How can I access the userLockout value, so that I can continue with saving the change into the database if needed?
And lastly, my ultimate goal here is to implement a system where an admin can lock or unlock a user account via the LockedOut flag (which gets checked each time someone logs in). I know the Identity framework has support for lockouts, but this seems to be time restricted lockouts only. Is there a way that exists in the Identity framework to have permanent (unless manually changed) lockouts? I am trying to use as little custom code and design as possible, so that's why I am interested in knowing this as well. Particularly, I am interested in using the way the framework keeps track of unsuccessful login attempt counts, because I want to try to avoid implementing that manually as well.
Thank you.
Change userLockout type to bool in the Edit method and post should work.
To lock the user for a very long duration (a sub for permanent lock) after n failed attempts, one option is to set the DefaultLockoutTimeSpan to some x years in the future.
To check if a user is locked out, try UserManager.IsLockedOutAsync(userId)

Resources