0

I'm currently using a .Net Core 2.2 WebApp with React + Redux... when I host the project on the IIS and the users open the main page everything works fine, the page request the user credentials...

But, how I can get the user name of the person that login into the page using Javascript?enter code here

MiBol
  • 1,985
  • 10
  • 37
  • 64

1 Answers1

1

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>;
  }
}

fenixil
  • 2,106
  • 7
  • 13
  • I got a problem trying to read the Identity.Name is coming in null: ```[Route("api/[controller]")] public class ValuesController : Controller { // GET: api/ [HttpGet] public async Task Username() { string user = await Task.FromResult(HttpContext.User.Identity.Name); user = string.IsNullOrWhiteSpace(user) ? "NO VALUE" : user; return user; } }``` – MiBol Aug 09 '19 at 02:06
  • It may vary depends on authentication method. There are a lot of materials online how to get Identity name on the backend, please check [this](https://stackoverflow.com/questions/51821277/asp-net-core-2-1-windows-auth-httpcontext-user-identity-name-not-working-in-iis) or [this](https://stackoverflow.com/questions/46528292/asp-net-core-iis-hosting-user-identity-name-is-empty-and-isauthenticated-false) – fenixil Aug 09 '19 at 03:21