Skip to content

Instantly share code, notes, and snippets.

@ggMartinez
Last active September 19, 2023 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggMartinez/8c781c98d910ef9eccd9ff3ae008ac69 to your computer and use it in GitHub Desktop.
Save ggMartinez/8c781c98d910ef9eccd9ff3ae008ac69 to your computer and use it in GitHub Desktop.
Javascript - Login con API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var token = localStorage.getItem("accessToken");
if(token != null)
$(location).prop('href', '/principal.html');
$("#btnLogin").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var data = {
"username": username,
"password": password,
"grant_type" : "password",
"client_id" : 101,
"client_secret" : "OGhqS9Yspa9GSBpfsNEfC3py4AREMS3YVLiYEk6m"
}
jQuery.ajax({
url: 'http://localhost:8000/oauth/token',
type: 'POST',
headers: {
"Accept" : "application/json",
"Content-Type" : "application/json",
},
data: data,
success: function(data) {
localStorage.setItem("accessToken", data.access_token);
$(location).prop('href', '/principal.html');
},
error: function(data){
alert("Credenciales invalidas");
}
});
});
});
</script>
</head>
<body>
<h1>Login</h1>
<div id="login">
Usuario: <input type="text" name="username" id="username"> <br>
Password: <input type="password" name="password" id="password"> <br>
<button id="btnLogin">Login</button>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var token = localStorage.getItem("accessToken");
if(token == null)
$(location).prop('href', '/login.html');
$("#cerrarSesion").click(function(){
jQuery.ajax({
url: 'http://localhost:8000/api/logout',
type: 'GET',
headers: {
"Authorization" : "Bearer " + localStorage.getItem("accessToken"),
"Accept" : "application/json",
"Content-Type" : "application/json",
},
success: function(data) {
localStorage.removeItem("accessToken");
$(location).prop('href', '/login.html');
}
});
});
});
</script>
</head>
<body>
<h1>Holi</h1>
<button id="cerrarSesion">Cerrar sesion</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment