WebAPI - Can it be used to Logout a user? - ajax

This method when called in a WebAPI controller from the client via an AJAX call returns a 200 code but the user gets re-authenticated upon a page refresh. What am I doing wrong?
[HttpPost]
[Route("logout")]
public IHttpActionResult Logout() {
AuthenticationManager.SignOut();
}
This works in a standard MVC controller as an ActionResult and a full page view, but it does not work via AJAX.

It looks like you're using a custom AuthenticationManager class because the one built into the framework doesn't look like it has a SignOut method.
http://msdn.microsoft.com/en-us/library/system.net.authenticationmanager(v=vs.110).aspx
If that is the case, then does your AuthenticationManager class use the Session to store user info? Because WebAPI controllers do not have the same type of access to session that MVC controllers do. Reference for session in WebAPI:
Accessing Session Using ASP.NET Web API

Related

ASP.Net Core Web API - ResponseCache attribute is not adding "Cache-Control" header to the reponse

I have multiple controllers in my ASP .NET Core application and I am using ReponseCache attribute like this on a few methods:
//controller
[Route("api/[controller]")]
[EnableCors("CorsPolicy")]
public class InsightsApiController : Controller
//method
[Route("CoursesTextContent")]
[HttpGet]
[DecryptFilter]
[ResponseCache(Duration = 60)]
public IActionResult GetCoursesContent(string locale, string tabKey, string widgetType)
The issue that I am having is that for one controller this is working fine and I can see the response in chrome dev tools with "Cache-Control:public max-age=60" but in a different controller when I add this attribute its adding "Cache-Control:no-cache". I compared both controllers and methods in them and they are configured same. I have also tried to add ASP.NET Core middleware recommended here but same results. I am calling both methods from Angular2 webpage. Is there something I can do from the client side (request)? or something in the ASP.NET Core app setup?
You are missing a trailing parenthesis
[ResponseCache(Duration = 60]
needs to be
[ResponseCache(Duration = 60)]
I had a session middleware enabled in the startup.cs file of my ASNETCore webapi project. I removed it and its working for all calls/controllers now. Not sure why it was causing problem only with one Controller.

WEB API OnAuthorization is Called Twice

I'm developing web API solution for authorization, we decorated each controller action method with the BasicHttpAuthorizeAttribute class with inherits from AuthorizeAttribute.
public class BasicHttpAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
For every request, I see OnAuthorization method is called twice. when I check the callstack, all the request is made by same thread/processId. I'm using UnityContainer. I registered by Custom Authorize in WebApiConfig.cs Please let me know the reason for calling twice.
If you register a filter in webapiconfig.cs it will run for every incoming request.
If you decorate an action with a filter, it will run for that action.
Since you registered the filter and decorated the action, it will run two times.

VS2013 (RTW): Authentication differences in SPA template vs MVC5 template?

I've been playing with the new ASP.NET identity offerings in the VS2013 RTW MVC template (for "indivual user accounts"), and it works great: I am able to integrate Facebook login while customizing the way the data is serialized.
All well and good, but I noticed that if I create a new SPA app (instead of MVC), the authentication story seems very different. As an example:
From the SPA template:
public AccountController()
: this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
{
}
public AccountController(UserManager<IdentityUser> userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
From the MVC template:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
This is just the difference in constructors of the Account controller. There are many, many other differences as well. With the MVC version I was able to easily derive my own context class from ApplicationDBContext, and use that to store my own tables alongside the authentication tables. I couldn't figure out how to customize the data storage in the SPA template.
Also, the SPA template includes and uses this class:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
The MVC template doesn't define (or use) this class.
I don't understand why there needs to be any differences at all between an MVC template and an SPA template.
Could anyone give me some guidance as to why authentication is handled so differently in these two templates? Starting a project from scratch, is there a preferred path to follow between the two? (It seems like the code in the MVC template is best, especially in terms of customizing how the data is stored by defining a custom EF Context class.)
Thanks...
-Ben
Take MVC and SPA project templates as Controller vs ApiController implementation sample.
As well as CookieAuthentication and oAuthAuthentication.
MVC uses Controller at the first request as well as all subsequent requests (having request defined Action Methods).
SPA uses Controller at the first request to SPA and all other interactions are handled by ApiController.
MVC uses cookie authentication.
SPA uses oAuth authentication.
Now in real apps, we need to take mix of both. Stating this, you can use the IdentityModel.cs (ApplicationDBContext) and it's customized copy of MVC project in your SPA too.
In oAuth implementation, the token is issued in GrantResourceOwnerCredentials method of ApplicationOAuthProvider. The user verification uses the same database of Identity framework by default. Moreover, oAuth provide authentication check in ApiController. In the sample implementation, oAuth's ResourceOwner flow is provided where user's username and password are verified.
In my opinion, templates are starting point examples.
I did notice the same thing when I first looked at all the posts about changing the model for the user and I couldn't find the model in the SPA template. Of course, the difference as #jd4u pointed out is that one is based on Controller and the other on ApiController.
So, I decided to see what it would take to make the SPA solution use the same Identity Model extension as the MVC template. I created a post that goes through the process that I went through. There is a link at the bottom to download the code from GitHub.

Set custom 401 error view in Windows Authentication mode for MVC application

My MVC application is set on Windows Authentication mode.
I would like to provide a custom 401 error view/page when a not-authorized user trying to access some resource at my app instead of the default IIS page.
I'm decorating my Action with the following Attributes:
[HttpGet]
[Authorized(Roles="Admin")]
public ActionResult Add()
{
return View();
}
How can I do it in MVC?
Thank you,

Adding HTTP Headers in JSP

I am creating a Spring REST web services, that communicates with Android App and JSP web pages.
The method at my spring controller is like
#RequestMapping(method = RequestMethod.POST, value = "/login")
public ModelAndView userLogin(#RequestBody User user,
HttpServletRequest request){
//do something with user
}
Andoid App is able to access this method through adding request Headres like
"Content-Type" application/json , "Accept" application/json etc. Here the user information sent by android end is comes in request body. Thats ok..
But problem occurs when i POST the contents from my JSP page. I am not able to access the same userLogin method from jsp page with #RequestBody but when i replace it with #ModelAttribute it works for jsp page ...but then doesn't works for android app. Please tell me how can i solve this.
Make the JSP page do the same thing as the android app (posting as JSON) using JavaScript, or implement a second method in your Spring controller (userLogin2), mapped to a different URL, and use this URL in your JSP.

Resources