asp.net-mvc


Call a Web API from MVC controller (cookie authentication)


I have a Web Api and Mvc 5 on same project.
That Web Api is protected with bearer token (but I commented the SuppressDefaultHostAuthentication line, so I can access the api from browser when I am authenticated with cookie mvc)
Now I´m trying to access the api from a mvc controller without sending the token, is that possible with SuppressDefaultHostAuthentication off?
Tried that without success (401 error):
HttpClientHandler handler = new HttpClientHandler()
{
PreAuthenticate = true,
UseDefaultCredentials = true
};
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://localhost:11374/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/MyApi").Result;
if (response.IsSuccessStatusCode)
{ }
}
If its not possible, how is the best way to handle that problem?
WebApi adheres to REST, which among other things, dictates that requests are stateless. That means with WebApi, or any REST-compatible API, there's no concept of anything such as cookies, sessions, etc. Each request to the API must contain all information needed to service the request. Therefore, if you have an endpoint that requires authentication, you must authenticate the request to access it. Period. If you're doing auth via bearer tokens, then you must pass the bearer token.
Since the WebAPI and the MVC app are in the same project you don't need to go through HTTP and make a request in order to access a method of each one - they're neighbors :)
You can treat the WebAPI as an ordinary class and instantiate it in the MVC controller. Afterwards you call the methods on the instance as you do with any other object in your application.
However it isn't possible to avoid tokens and/or other security mechanisms the WebAPI is designed with IF you leverage a request through HTTP to access it.

Related Links

VS2012 add areas to an existing project? start over? with MVC5 or stick with MVC4
Edit view from HttpPost method
Best practive for logging errors (handled and unhandled) in MVC
ServiceStack request giving 500 for large request
Cross domain session asp mvc in IE and old browsers
Adding MVC Controller scaffolding error
Unable to debug plugin in NopCommerce
Displaying HTML and Images in MultiSelectList ASP.NET MVC Razor
#Html.DisplayFor() value not change after the postback
Location of Validation Message
ASP.NET Identity update column type for primary key Id in AspNetUsers table from a string to and int or a guid, yes or no?
Deploying ASP MVC 5 App with IIS 7.5
validation for dropdown in MVC3
MVC getting a list of music and image into a table
How to allow users to only edit their details in a catalog
Defining Repository for MVC best practice

Categories

HOME
validation
ssl
unit-testing
vr
dynamics-crm-365
module
pyqt5
jsessionid
apacheds
garbage-collection
linear-programming
localforage
middleware
robot
format
sweetalert
google-adwords
plotly
asciidoc
executable
reload
python-2.5
raspberry-pi2
jgit
spring-cloud-consul
afnetworking-2
swig
realm-java
amazon-cloudfront
montecarlo
symbolic-math
kubernetes-go-client
localdb
deep-copy
data-science
ecdsa
transpose
otroslogviewer
dsx
btle
invalidate
android-calendar
azure-cdn
node.js-tape
ammonite
catalina
graph-traversal
configuration-profile
jasny-bootstrap
vb4android
file-management
trello.net
training-data
win32com
dual-table
dhc
sketching
windows-universal
newsql
simpleadapter
prettyfaces
express-jwt
before-save
zeroclipboard
aps
pkcs#10
tinkerpop-frames
bson
dirpagination
magento-1.6
deepzoom
disk-io
xml.modify
junit-runner
pydatalog
django-endless-pagination
gdb-python
arden-syntax
time-limiting
graphiti-js
c++builder-xe2
intel-8080
semantic-zoom
websolr
katta
mkreversegeocoder
having
custom-tag
winamp
pinging
clipboard-pictures
server.transfer
palm-pre
variable-names
usenet
corporate-policy

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App