When browser navigates to the page and webserver responds with 401, browser will try to authenticate user based schemas in WWW-Authenticate header. If it can't find credentials user gets a prompt to provide them. Then browser sends them to the the server.
If you forbid unauthenticated access to your website this negotiation happens before any static resources are loaded to the page, so there is no way for you to intercept that with JS.
You can expose endpoint which returns user name and make ajax call to get it when your React application starts.
public async Task<String> Username() => await Task.FromResult(HttpContext.User.Identity.Name)
class UserComponent extends Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false
};
}
componentWillMount() {
fetch("/").then(result => {
this.setState({
isLoaded: true,
username: result.url
});
});
}
render() {
return this.state.isLoaded && <div>{this.state.username}</div>;
}
}