xgqfrms / learning

learning : A collection of all kinds of resources, videos, pdf, blogs, codes... 📚 + 💻 + ❤
https://learning.xgqfrms.xyz
MIT License
16 stars 12 forks source link

HTTP status code & cookie & credentials & CORS #24

Open xgqfrms opened 5 years ago

xgqfrms commented 5 years ago

HTTP status code

not login === un-auth

authorization

https status code & not login

https://stackoverflow.com/questions/23917679/proper-status-code-to-return-when-login-fails

https://httpstatuses.com/

1×× 2×× 3×× 4×× 5××

xgqfrms commented 5 years ago

Access-Control-Allow-Methods: OPTIONS

CORS

https://stackoverflow.com/questions/20478312/default-value-for-access-control-allow-methods https://www.html5rocks.com/en/tutorials/cors/

https://www.w3.org/TR/cors/#preflight-request

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

Comma-delimited list of the allowed HTTP request methods.


Access-Control-Allow-Methods: POST, GET, OPTIONS

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS https://fetch.spec.whatwg.org/#http-access-control-allow-methods

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

image image

xgqfrms commented 5 years ago

preflight request/response

预检请求/响应:

https://www.cnblogs.com/xgqfrms/p/9993892.html

demo


var invocation = new XMLHttpRequest();
var url = 'http://bar.other/resources/post-here/';
var body = '<?xml version="1.0"?><person><name>Arun</name></person>';

function callOtherDomain(){
  if(invocation)
    {
      invocation.open('POST', url, true);
      invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
      invocation.setRequestHeader('Content-Type', 'application/xml');
      invocation.onreadystatechange = handler;
      invocation.send(body); 
    }
}

// ......

xgqfrms commented 5 years ago

cookie & credentials & CORS

By default, in cross-site XMLHttpRequest or Fetch invocations, browsers will not send credentials.

no cookie by default

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Requests_with_credentials

withCredentials = true;

By default, the invocation is made without Cookies.


var invocation = new XMLHttpRequest();
var url = 'http://bar.other/resources/credentialed-content/';

function callOtherDomain(){
  if(invocation) {
    invocation.open('GET', url, true);
    invocation.withCredentials = true;
    invocation.onreadystatechange = handler;
    invocation.send(); 
  }
}

server CORS configs

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Credentialed_requests_and_wildcards

server set CORS & Access-Control-Allow-Origin: *

image

xgqfrms commented 5 years ago

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

xgqfrms commented 5 years ago

Token & Auth

https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication

https://auth0.com/learn/token-based-authentication-made-easy/ https://shahmeeramir.com/4-methods-to-bypass-two-factor-authentication-2b0075d9eb5f?gi=8380e6a7711b

https://stackoverflow.com/questions/42137230/how-to-pass-authorization-token-to-get-method-to-access-authorized-resource

这么设置 cookie 是读不到的,port & path 不同

image

对的 所以你登录后会给你一个Acess-Token 你需要写到header里去???

如果是 token 就不用写到 header 了, url 带着就可以了

image

https://auth0.com/learn/token-based-authentication-made-easy/ https://auth0.com/blog/ten-things-you-should-know-about-tokens-and-cookies//

xgqfrms commented 5 years ago

Axios & CORS & cookies

https://github.com/axios/axios/issues/191

https://stackoverflow.com/questions/48846653/get-cookie-from-axios-response-using-cors-on-the-server-side

Apache Server

Access-Control-Allow-Credentials: true

Access-Control-Allow-Origin: * ??? conflict ???

image

JS Client

withCredentials: true, === cookie


Axios bug

axios.defaults.withCredentials = true;

https://stackoverflow.com/questions/40941118/axios-wont-send-cookie-ajax-xhrfields-does-just-fine

xgqfrms commented 5 years ago

https://github.com/axios/axios/issues/876#issuecomment-438559189

server & client

CORS

https://www.html5rocks.com/en/tutorials/cors/#toc-withcredentials https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Requests_with_credentials https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication

xgqfrms commented 5 years ago

Apache shrio & CORS & cookie

https://shiro.apache.org/web.html#Web-SessionCookie https://shiro.apache.org/static/1.3.2/apidocs/org/apache/shiro/web/servlet/SimpleCookie.html

https://stackoverflow.com/questions/22526146/how-to-enable-cors-in-apache-tomcat http://tomcat.apache.org/tomcat-8.0-doc/config/filter.html#CORS_Filter

https://searchblox.zendesk.com/hc/en-us/articles/203979539-How-do-I-enable-support-for-CORS-

xgqfrms commented 5 years ago

https://www.talentcookie.com/2015/03/apache-shiro-features-and-terminologies/

xgqfrms commented 5 years ago

markdown to html

Markdown PDF

https://marketplace.visualstudio.com/items?itemName=yzane.markdown-pdf

Press F1 or Ctrl+Shift+P

Type export and select below

markdown-pdf: Export (settings.json) markdown-pdf: Export (pdf)

markdown-pdf: Export (html)

markdown-pdf: Export (png) markdown-pdf: Export (jpeg) markdown-pdf: Export (all: pdf, html, png, jpeg)

xgqfrms commented 5 years ago

MacOS

MacOS 环境下 vim 配置

https://blog.csdn.net/yangcs2009/article/details/79445027 https://www.jianshu.com/p/9fa9bedc259a

xgqfrms commented 5 years ago

antd bug

https://codepen.io/webgeeker/pen/vQpwPY?editors=0110

image

image

bug

import {
    Table,
    Modal,
    Button,
    Input
} from 'antd';

const { TextArea } = Input;

    <div className="input-table">
        <Button type="primary" onClick={this.showModal}>
            查看请求URL
        </Button>
        <Modal
            title="输入请求 URL"
            footer={[
                <Button key="back" onClick={this.handleCancel}>
                    Return
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={this.handleCopy}>
                    Copy
                </Button>,
            ]}
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}>
            <div>
                {/* 输入 Tab 请求URL: {this.props.inputUrl}  */}
                <TextArea rows={4} />
                {/* <Input
                    type="textarea"
                    placeholder="输入 Tab 请求URL"
                    rows="15"
                    cols="500"
                    value={inputUrl}
                    onChange={(e) => this.changeHanlder(e)}
                /> */}
            </div>
        </Modal>
    </div>

OK


import {
    Table,
    Modal,
    Button,
    Input
} from 'antd';

const { TextArea } = Input;

<div className="input-table">
        <Button type="primary" onClick={this.showModal}>
            查看请求URL
        </Button>
        <Modal
            title="输入请求 URL"
            footer={[
                <Button key="back" onClick={this.handleCancel}>
                    Return
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={this.handleCopy}>
                    Copy
                </Button>,
            ]}
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}>
            <div>
                {/* 输入 Tab 请求URL: {this.props.inputUrl}  */}
                {/* <TextArea rows={4} /> */}
                <Input
                    type="textarea"
                    placeholder="输入 Tab 请求URL"
                    rows="15"
                    cols="500"
                    value={inputUrl}
                    onChange={(e) => this.changeHanlder(e)}
                />
            </div>
        </Modal>
    </div>
xgqfrms commented 5 years ago

click & copy

https://github.com/zenorocha/clipboard.js/issues/604 https://github.com/zenorocha/clipboard.js/issues/27

clipboard

https://clipboardjs.com/ https://alligator.io/js/copying-to-clipboard/

// ES6 Modules
import { Clipboard } from "clipboard";

click copy & demo

https://codepen.io/webgeeker/pen/JepjwY

https://codepen.io/webgeeker/pen/JepjwY

xgqfrms commented 5 years ago

https://alligator.io/js/copying-to-clipboard/ https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html

componentDidMount() method

https://busypeoples.github.io/post/react-component-lifecycle/ https://tech.io/playgrounds/8747/react-lifecycle-methods-render-and-componentdidmount https://stackoverflow.com/questions/28662624/reactjs-componentdidmount-render

xgqfrms commented 5 years ago

click copy

https://codepen.io/webgeeker/pen/KrQRvL

React & css hidden & copy bug

https://codepen.io/webgeeker/pen/RqQJWq

xgqfrms commented 5 years ago

加了这两个快捷的功能 image

xgqfrms commented 5 years ago

$ zip -r apitool-2018-11-22.zip apitool/*
xgqfrms commented 5 years ago

https://tech.io/playgrounds/8747/react-lifecycle-methods-render-and-componentdidmount

angular 2018

https://scrimba.com/g/gyourfirstangularapp

image

xgqfrms commented 5 years ago

image

xgqfrms commented 5 years ago

image

xgqfrms commented 5 years ago

es6 destructuring nested object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

https://stackoverflow.com/questions/33336170/destructuring-es6-nested-objects

https://ponyfoo.com/articles/es6-destructuring-in-depth

https://stackoverflow.com/questions/42856985/es6-object-destructuring-default-values-for-nested-parameters

Nested object and array destructuring

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

const metadata = {
    title: 'Scratchpad',
    translations: [
       {
        locale: 'de',
        localization_tags: [],
        last_edit: '2014-04-14T08:43:37',
        url: '/de/docs/Tools/Scratchpad',
        title: 'JavaScript-Umgebung'
       }
    ],
    url: '/en-US/docs/Tools/Scratchpad'
};

let {
    title: englishTitle,// rename
    translations: [
        {
            title: localeTitle,// rename
            age:
        },
    ],
} = metadata;

console.log(englishTitle); // "Scratchpad"
console.log(localeTitle);  // "JavaScript-Umgebung"

demo


const options = {
        "accountName": "admin",
        "passWord": "123456",
        "rememberMe": false
    };
    const url = URLs.login;
    Axios({
        url,
        data: options,
        method: "post",
        withCredentials: false,
        // headers: {
        //     "Access-Token": sessionStorage.getItem("componentToken"),
        // },
    })
    .then((res) => {
        let {
            data: json
        } = res;
        // ES Destructing Assignment
        let {
            message,
            status,
            data: {
                accessToken,
                accountName,
            },
            // accessToken,
            // userId,
        } = json;
        console.log(`json =`, JSON.stringify(json, null, 4));
        console.log(`accessToken =`, JSON.stringify(accessToken, null, 4));
        // json.data.accessToken
        localStorage.setItem("componentAccount", accountName);
        sessionStorage.setItem("componentToken", accessToken);
    })
    .catch(err => console.log(`login error`, err));
xgqfrms commented 5 years ago

Utils

emptykeysFilter()


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2018.11.23
 * @modified 2018.11.23
 *
 * @description Utils
 * @augments
 * @example emptykeysFilter(obj);
 *
 */

const emptykeysFilter = (obj = {}, debug = false) => {
    // const newObj = {};
    let keys = Object.keys(obj);
    keys.forEach(
        (key, i) => {
            // console.log(`key`, key);
            // console.log(`obj[key]`, obj[key]);
            if (!Object.keys(obj[key]).length) {
                delete obj[key];
            } else {
                // newObj[key] = obj[key];
            }
        }
    );
    // console.log(`new obj =`, JSON.stringify(newObj, null, 4));
    // return newObj;
    // console.log(`new obj =`, JSON.stringify(obj, null, 4));
    return obj;
};

const Utils = {
    emptykeysFilter,
};

export default Utils;

export {
    Utils,
    emptykeysFilter,
};

/*

let obj = {
    "id": "123",
    "name": [],
    "userName": {},
    "telephoneNum": [1],
    "phoneNum": {k: "v"},
    "email": "",
};

emptykeysFilter(obj);

// {
//     "id": "123",
//     "telephoneNum": [1],
//     "phoneNum": {k: "v"},
// };

*/
xgqfrms commented 5 years ago

Object empty value key filter

https://github.com/xgqfrms/vue/issues/35


Note: Axios 参数, 前端传递方式约定如下:

1.前后端同时双重过滤
2.no value, no key

example:

{
  "status": false,
  "roleIds": [],
  "keyWordType": "AccountName",
  "keyWord": ""
}

过滤空值的 keys, 过滤后如下

{
  "status": false,
  // "roleIds": [],
  "keyWordType": "AccountName",
  // "keyWord": ""
}

即

{
  "status": false,
  "keyWordType": "AccountName"
}
xgqfrms commented 5 years ago

CORS & cookie

https://www.cnblogs.com/xgqfrms/tag/CORS/

https://github.com/xgqfrms/learning/issues/24

credentials: includes

https://github.com/github/fetch/issues/452

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials

Ajax XHR & withCredentials = true;


// Access-Control-Allow-Credentials: true

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true); 
xhr.withCredentials = true; 
xhr.send(null);

Fecth & credentials: 'include'


fetch(url, {
  credentials: 'include'  
})

https://www.cnblogs.com/xgqfrms/p/9956725.html


{
    // `withCredentials` indicates whether or not cross-site Access-Control requests  should be made using credentials
    withCredentials: false, // default
}

AMP

https://amp.dev/

https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cors-requests/


xgqfrms commented 3 years ago

CSP bug

https://www.cnblogs.com/xgqfrms/p/14722228.html

xgqfrms commented 3 years ago

fetch POST cookies & credentials

fetch(`http://10.1.159.45:3000/api/post`, {
// fetch(`http://localhost:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    // cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    // cookies
    credentials: 'include',
    // mode: "no-cors",
    mode: "cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));

https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

xgqfrms commented 3 years ago

CSP

  1. URL 404 ❌

image

  1. URL 200 ✅

image

xgqfrms commented 3 years ago

...

xgqfrms commented 1 year ago

https://www.cnblogs.com/xgqfrms/p/17666229.html

https://stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input

xgqfrms commented 1 year ago

https://stackoverflow.com/a/77003350/5934465

xgqfrms commented 11 months ago

https://www.cnblogs.com/xgqfrms/p/16133286.html