前后端分离之权限验证

前后端分离之权限验证

原理:将登录验证的请求头中后端生成的秘钥(token)接收后存储在cookie内,在再次请求数据时添加在请求头中发送给后端验证,请求数据。

代码:

登录ajax:

    $scope.aaa=function aaa() {
        $scope.uname = $(".inpu1").val();
        $scope.passwd = $(".inpu2").val();
        $scope.aaaa={"uname":$scope.uname,"passwd":$scope.passwd};/*获取用户名密码*/
        $.ajax({
            crossDomain:true,
            type:'POST',
            url:'http://192.168.1.10:8080/demo/tokens ',
            dataType:'json',
            contentType:'application/json',
            data:JSON.stringify( $scope.aaaa) ,
            complete: function(resp){
                var cookss = resp.getResponseHeader('Authorization'));/*获取后端传过来的token*/
                $.cookie("cookaa",cookss,{expires:0.01});/*将token转存在cookie中*/
            },
            success: function(data){
                window.location.href="#/strat";
            },
            error:function () {
                alert(2);
            }.bind(this)
        });
    };

数据请求:

$.ajax({
    withCredentials:true,
    crossDomain:true,
    type:'GET',
    url:'http://192.168.1.10:8080/demo/liveInfo/liveInfolist ',
    xhrFields: {
        withCredentials: true
    },/*在ajax跨域请求中携带cookie做身份验证*/
    dataType:'json',
    contentType:'application/json',
    async: false,
    beforeSend: function(xhr) {
        xhr.setRequestHeader("X-Token",$.cookie("cookaa"));/*将token的值插入请求头*/
    }.bind(this),
    success:function (data) {
        if(data.meta.success){
            $scope.data=data.data;
        }
    },
    error:function () {
    }.bind(this)
}) ;

 

posted @ 2017-11-15 15:00  莫小龙  阅读(3121)  评论(0编辑  收藏  举报