Question

I'm just working on my first Web API 2 Single Page Application in Visual Studio 2013. When I started with the project I chose Authentication: Individual Accounts. So when I build the solution, the login form appeared. I registered a user and I can successfully log in.

My controller is ready to use and I put the [authorize]-Attribute in front of my requests.

When I'm not logged in and navigate to my request, it shows me the error-message:

"Authorization has been denied for this request."

That's great, but when I'm logged in and navigate to the request again, it still shows me the same message.

The controller itself is working fine without the [authorize]-attribute.

I'm really new to this topic and I couldn't find anything about how to connect the built in Login with authorizing my requests. I hope, you can help me.

EDIT:

I just found out about the differences of Authentication and Authorization. First is for identifying the user, second is for giving him rights to do anything...

So I tried [Authorize(Users="Username")], but it doesn't work. (It should work with [Authorize] as well, because therefore you authorize all users??)

What's wrong with my application? :(

EDIT 2:

I'm still searching for how to get the access_token into the header! :(

Was it helpful?

Solution

When You are sending Request To your controller through ajax add your authorization claims token

For every request you need to send authorization token

In your login.viewmodel.js of SPA after user successfully logged in you are saving data.access_token,this token needs to send for every ajax request as below

If this answered your question, Please check right on left side.

  $.ajax(url, {
                type: "POST",
                data: data,
                headers: "Authorization": "Bearer " + accessToken
            });




  dataModel.login({
            grant_type: "password",
            username: self.userName(),
            password: self.password()
        }).done(function (data) {
            self.loggingIn(false);

            if (data.userName && data.access_token) {
                app.navigateToLoggedIn(data.userName, data.access_token, self.rememberMe());
            } else {
                self.errors.push("An unknown error occurred.");
            }
        }).failJSON(function (data) {
            self.loggingIn(false);

            if (data && data.error_description) {
                self.errors.push(data.error_description);
            } else {
                self.errors.push("An unknown error occurred.");
            }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top