public override void OnAuthorization(HttpActionContext actionContext) { if (SkipAuthorization(actionContext)) { return; } var userSessionManager = new UserSessionManager(); if (userSessionManager.ReValidateSession()) { base.OnAuthorization(actionContext); } else { actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse( HttpStatusCode.Unauthorized, "Session token expried or not valid."); } }
public IHttpActionResult Logout() { // This does not actually perform logout! The OWIN OAuth implementation // does not support "revoke OAuth token" (logout) by design. this.Authentication.SignOut(DefaultAuthenticationTypes.ExternalBearer); // Delete the user's session from the database (revoke its bearer token) var userSessionManager = new UserSessionManager(); userSessionManager.InvalidateUserSession(); return this.Ok( new { message = "Logout successful." } ); }
public async Task<IHttpActionResult> LoginUser(LoginUserBindingModel model) { if (model == null) { return this.BadRequest("Invalid user data"); } // Invoke the "token" OWIN service to perform the login (POST /api/token) // Use Microsoft.Owin.Testing.TestServer to perform in-memory HTTP POST request var testServer = TestServer.Create<Startup>(); var requestParams = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", model.Username), new KeyValuePair<string, string>("password", model.Password) }; var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams); var tokenServiceResponse = await testServer.HttpClient.PostAsync( Startup.TokenEndpointPath, requestParamsFormUrlEncoded); if (tokenServiceResponse.StatusCode == HttpStatusCode.OK) { // Sucessful login --> create user session in the database var responseString = await tokenServiceResponse.Content.ReadAsStringAsync(); var jsSerializer = new JavaScriptSerializer(); var responseData = jsSerializer.Deserialize<Dictionary<string, string>>(responseString); var authToken = responseData["access_token"]; var username = responseData["username"]; var userSessionManager = new UserSessionManager(); userSessionManager.CreateUserSession(username, authToken); // Cleanup: delete expired sessions fromthe database userSessionManager.DeleteExpiredSessions(); } return this.ResponseMessage(tokenServiceResponse); }