JWT登录的实现包含前后端

我们添加一个弹出窗口,在右上角添加一个按钮,然后点击按钮弹出一个窗口,

输入账号和密码,点击登录按钮,ajax发起对webapi的请求,api根据账号和密码,验证用户

验证通过就生成JWT的Token,然后发送Token过来。前端把Token写入到localStrage中。

然后刷新整个页面。以后很多地方,需要调用后台其他的接口api,这些接口api比如请求左侧菜单

请求当前登录人信息。等等。调用这些API的时候都要带上Token。

那么下面我们首先实现登录框。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Full Layout - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.6.8/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.6.8/themes/icon.css">
<script src="jquery-easyui-1.6.8/jquery.min.js"></script>
<script type="text/javascript" src="jquery-easyui-1.6.8/jquery.easyui.min.js"></script>
</head>
<body class="easyui-layout">
<div data-options="region:'north',border:false" style="height:60px;background:#B3DFDA;padding:10px;">
<div style="float:right;">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#w').window('open')">登录</a>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#w').window('close')">Close</a>
</div>
</div>
<div data-options="region:'west',split:true,title:'West'" style="width:150px;padding:10px;">west content</div>
<div data-options="region:'south',border:false" style="height:30px;background:#A9FACD;padding:10px;">south region</div>
<div data-options="region:'center',title:'Center'"></div>
<div id="w" class="easyui-window" title="登录系统" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:400px;height:250px;padding:10px;">
<form id="ff" class="easyui-form" method="post" data-options="novalidate:true">
<div style="margin-bottom:20px">
<input id="idname" class="easyui-textbox" name="name" style="width:100%" data-options="label:'账号:',required:true">
</div>
<div style="margin-bottom:20px">
<input id="idpassword" class="easyui-passwordbox" name="password" style="width:100%" data-options="label:'密码:',required:true">
</div>
</form>
<div style="text-align:center;padding:5px 0">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()" style="width:80px">提交</a>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">清除</a>
</div>
</div>
<script>
        function submitForm(){
        var isValide = $('#ff').form('enableValidation').form('validate');
        if (isValide) {
        var name = $("#idname").val();
        var password = $("#idpassword").val();
        $.ajax({
        type: "POST",
        url: "http://localhost:23557/api/login",
        data: JSON.stringify({name:name,password:password}),
        contentType: "application/json",
        success: function (data) {
        if (data) {
        localStorage.setItem("Token", data);
        window.location.href = "/index.html";
        }
        },
        error: function (data) {
        }
        });
        }
        }
        function clearForm(){
            $('#ff').form('clear');
        }
</script>
</body>
</html>
下面是后台

using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Demo.Controllers
{
    public class LoginController : ApiController
    {
        private string secret = "bamn.cn";
        public string Post(dynamic obj)
        {
            IDateTimeProvider provider = new UtcDateTimeProvider();
            var now = provider.GetNow();
            var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch
            var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
            var payload = new Dictionary<string, object>
            {
                {"name", obj.name },
                {"exp",secondsSinceEpoch+10 },
                {"jti","luozhipeng" }
            };
            Console.WriteLine(secondsSinceEpoch);
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            var token = encoder.Encode(payload, secret);
            return token;
        }
    }
}

 

posted @ 2020-04-14 17:39  zhangzhiping35  阅读(65)  评论(0)    收藏  举报