React和Redux HTTP标头授权

时间:2016-08-26 14:35:26

标签: reactjs react-router react-redux redux-thunk react-router-redux

我正在尝试使用API​​后端设置React身份验证。 API后端使用电子邮件和密码,并且还为每个新用户创建令牌。所有这些都是通过直接JSON而不是JWT提供的,所以我使用Auth0 tutStack q/a作为起点。

我的第一个目标是进行简单的登录和重定向。我把动作/缩减器连接起来,我现在正在进行API调用。我正在使用基本的auth调用并将其转换为64位字符并通过标头发送。这些都是通过Postman测试和工作的。

当我执行当前的React设置时,它会在控制台中显示“Fetching”,但从不“我在这里。”,页面只是重新加载。我不知道在哪里解决这个并获得它授权和重定向。我出错的任何想法?

HomePage.js(容器)

class HomePage extends React.Component {
 constructor(props) {
  super(props);
 }

 render() {
  const { dispatch, isAuthenticated } = this.props;
 return (
   <div>
     < HomeHeader onLogin={this.props.onLogin} />
   </div>
  );
 }
}

 function mapStateToProps(state) {
  return { loginResponse: state.loginResponse };
 }

 function mapDispatchToProps(dispatch) {
 return {
   onLogin: (creds) => dispatch(loginUser(creds)),
 };
}

export default connect(
mapStateToProps,
mapDispatchToProps
)(HomePage);

AuthorizationActions.js(操作)

function requestLogin(creds) {
 return {
  type: types.LOGIN_REQUEST,
  isFetching: true,
  isAuthenticated: false,
  creds
 }
}
function receiveLogin(user) {
 return {
  type: types.LOGIN_SUCCESS,
  isFetching: false,
  isAuthenticated: true,
  id_token: user.id_token
 }
}

export function loginUser(creds) {
 **console.log("Fetching");**
 const hash = new   Buffer(`${creds.username}:${creds.password}`).toString('base64')

return fetch('http://api.xxx.dev/sessions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Basic ${hash}'
  },
 })
  .then(response => {
    **console.log("I'm here");**
    if(response.status >= 200 && response.status < 300){
      console.log("Response; ", response);
      // Dispatch the success action
      dispatch(receiveLogin(user));
      localStorage.setItem('id_token', user.id_token);
    } else {
      const error = new Error(response.statusText);
      error.response = response;
      dispatch(loginError(user.message))
      throw error;
    }
  })
  .catch(error => { console.log('Request Failed: ', error);});
 }

AuthorizationReducer.js(Reducer)

import { browserHistory } from 'react-router';
import Immutable from 'immutable';

const initialState = new Immutable.Map({
 username: '',
 password: '',
 isLoggingIn: false,
 isLoggedIn: false,
 isFetching: false,
 error: null,
 isAuthenticated: localStorage.getItem('id_token') ? true : false
});

function authenticationReducer(state = initialState, action) {
 switch ( action.type ) {
 case 'LOGIN_REQUEST':
  return { ...state,
      isFetching: true,
      isAuthenticated: false,
      user: action.creds
  }
 case 'LOGIN_SUCCESS':
  return {
    ...state,
    browserHistory: browserHistory.push('/dashboard')
  }
 case 'LOGIN_FAILURE':
  return alert('Crap, there are login failures');
 default:
  return state;
 }
}
export default authenticationReducer;

configureStore.js(商店)

const middleware = applyMiddleware(
  thunk,
  apiMiddleware,
  global.window ? logger : store => next => action => next( action )
);
const store = createStore( reducers, initialState, compose(middleware,    window.devToolsExtension ? window.devToolsExtension() : f => f  ))

AuhorizeLogin.js组件

 constructor(props, context) {
  super(props, context);
  this.state = {};
  this._login = this._login.bind(this);
 }

 _login(e) {
  e.preventDefault;
  const email = this.refs.email;
  const password = this.refs.password;
  const creds = { email: email.value.trim(), password: password.value.trim() };
  this.props.onLoginClick(creds);

}

HomeHeader.js组件

 `_handleChange(eventKey) {
< AuthorizeLogin onLoginClick={this.props.onLogin}/>);
`

HomePage.js容器

constructor(props) {
 super(props);
}
render() {
 const { dispatch, isAuthenticated } = this.props;
 return (
 ...
 < HomeHeader onLogin={this.props.onLogin} />
 ...
 )
}

function mapStateToProps(state) {

return {
 loginResponse: state.loginResponse,
 };
}

function mapDispatchToProps(dispatch) {
 return {
  onLogin: (creds) => dispatch(loginUser(creds)),
 };
}

export default connect(
 mapStateToProps,
 mapDispatchToProps
 )(HomePage);

1 个答案:

答案 0 :(得分:1)

尝试使用return fetch('http://api.xxx.dev/sessions'...。 没有经过测试,但它应该让你“我在这里”。 最后,包装箭头函数{}