MVC3 Razor Engine execution/rendering order - asp.net-mvc-3

I have a few links (login, logout, and register) in the _layout template, where the links are shown depending on whether the user is logged in. Like so:
if (User.Identity.IsAuthenticated)
{
<span class="username">#User.Identity.Name</span>
<span class="link">#Html.ActionLink("Logout", "Logout", "Account")</span>
}
else
{
<span class="link">#Html.ActionLink("Login", "Login", "Account")</span>
<span class="link">#Html.ActionLink("Register", "Register", "Account")</span>
}
Problem is that the logout link is still displayed the first time the user logs out of the system (I would expect that to be immediately replaced with the login, and register links) - that is until the page is refreshed, or the user moves to another page. Here is the logout action code:
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Abandon();
return View();
}
I have gone through this link - http://mvcdev.com/differences-between-asp-net-razor-and-web-forms-view-engines/ - which explains the execution order of the Razor engine, but in my case it seems to be executing differently. Ideally I would expect the FormsAuthentication.SignOut() to execute before the User.Identity.IsAuthenticated in the _layout.
What am I doing wrong? Thanks!

That's normal, you need to redirect after logging out:
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Abandon();
return RedirectToAction("Index");
}
The reason this happens is because when the client requested the Logout link he was still authenticated (he sent the authentication cookie along with the request). Then inside the controller action you are logging him out (FormsAuthentication.SignOut()) which does nothing more than mark the authentication cookie for removal on subsequent requests. Then you return a view, and inside this view of course the user is still authenticated as this view executes under the same request and the cookie is still present.

Related

CORS error when trying to redirect user from a partial view

I am working on an application written in ASP.NET MVC5 which require the user to be log in. The authentication works with Central Authentication Service (CAS). On the homepage, I have several partial views :
Home page with partial views
I call a controller's action when I want to update the user's data.
It's working well, until the CAS session expires. If I try to refresh the partial views, I get an error :
"OPTIONS https://example.com/CAS/Authentication 403 (Forbidden)"
"Failed to load https://example.com/CAS/Authentication: Response for preflight has invalid HTTP status code 403"
I think it comes from the use of Ajax to refresh the partial view and it returns me the login page, which is not on the same domain. How can I overcome this issue ?
In my View I send the datas to the Controller with Ajax.BeginForm() and my controller returns a partial view, so that I don't need to completely refresh the page.
To overcome the Cross Origin Request error, I needed to handle the Ajax response. Instead of letting the login page being returned in the partial view, I call a Javascript function on the OnComplete event, checking the status code of the response.
In my partial view :
AjaxOptions ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
OnComplete = "redirectToLoginPage"
};
using (Ajax.BeginForm("ActionName", "ControllerName", null, ajaxOptions))
{
<button type="submit">Submit</button>
}
On click on submit, it will execute the action "ActionName" from the controller "ControllerName". Then, it will fire the Javascript function "redirectToLoginPage", which is :
function redirectToLoginPage(xhr) {
if (xhr.status == 200) {
//Whatever
}
else
{
window.location.replace("https://login.example/");
}
}
This do the trick.

Pass parameters from webflow to redirected page

I have this issue.
I redirect the user to /login page after registration, but I want to pass attribute from end-state of webflow to login.html that says something like "you have registered successfully". How can I accomplish that?
Edit: By the way I use thymeleaf.
when User clicks on Signup button the method which handles the registration there you need to add Model and insert the message as the attribute and pass to the login page.
example:
//Suppose these is the method which handles the registeration
void register(Model model)
{
model.addAttribute("Message","You are successFully Login");
return "loginPage";
}
And in login.jsp you can get the Message object as:
${Message}

Yammer javascript SDK logout issue

I can successfully login with yam.platform.login but when I call
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
yam.platform.logout(function (response) {
if (response) {
alert("logout success");
}
})
}
}
);
the inner callback function is never reached. Do people know what is happening?
EDIT: another strange behavior that could be related to the problem: after the above logout function call, the login status is still "connected" and I checked in Chrome that all cookies from yammer.com are deleted. But when I manually ask Chrome to delete the cookies, login status would return "unconnected".
Response from yam.platform.logout seems "false" after successful logout so you might try "if(response == false)" or even without if statement..
I was also facing the same issue. It is hard to believe that the issue still exists in 2018! I dug a bit more and found that after the app is authorized by user, Yammer server sends a cookie which gets stored in the browser somewhere (not tied to the session) and yam.platform.logout is unable to delete this cookie (Ideally it should!)
But I found a good workaround which is working neatly for me.
Below is JS in my login page:
$("#yammer-login").click(function(){
console.log("clicked");
yam.getLoginStatus(
function(resp) {
yam.platform.login(function (response) { //prompt user to login and authorize your app, as necessary
if (response.authResponse) {
console.dir(response); //print user information to the console
alert("login success");
}
$.ajax({
type:"POST",
url:"/setSession",
data:JSON.stringify(response,null,'\t'),
contentType:"application/json;charset=UTF-8",
success: function(result){
alert("Result from setSession is: "+result);
window.location.replace("/login");
}});
});
}
);
});
Here #yammer-login is the id for login element
<h2 class="sign-in">
<center>
Sign-in With Yammer
<br><br>
<span id="yammer-login">Click</span>
</center>
</h2>
Here is my workflow:
The JS on login page sends a POST request to setSession and sets the session. The execution of window.location.replace("/login"); sends a GET request to my server for /login url. As the session is now set, my server then redirects this request to the dashboard. After I click on logout button on the dashboard. I clear all the session cookies and redirect it back to the login page. As the session is now un-set- I see the login page again! All works smooth!
So, the next time user clicks on #yammer-login DOM element - the session gets set and she gets redirected to dashboard (this time without authorizing the app)!
Hope this helps someone who faces this issue like me in the future!

Codeigniter Passing parameters from view to controller

view has this anchor:
echo anchor('login', 'Login or Register');
how do i send the current url to my controller login? and then use it on another function called login_validation?
all i want is, login and back to the last url, however nothing works. so i thought saving the current url when i click "Login or Register" and then after login, on function login_validation, i should redirect to that url saved...
controller index
public function index(){
$this->main_login();
}
main_login
public function main_login(){
$this->load->helper('url');
// on view i will call the next function login_validation
$this->load->view("view_login");
}
login_validation
public function login_validation(){
$this->load->library('form_validation');
(...)
if ($this->form_validation->run()){
// i should redirect the saved url here, instead of home
redirect('home');
}else{
(...)
}
}
i appreciate any help
You can do this simply by using $this->agent->referrer() in your controller class main_login().
Save the referrer url into your session, and once the user is validated (or if they are), then you pull that string from session:
in main_login():
// grabs url where you clicked login
$this->session->set_userdata('referrer_url', $this->agent->referrer());
in login_validation():
// pull url from session and redirect, make sure to account for not having url too
redirect( $referrer_url );
I apologize for the delay, i was really busy with the end of the semester,
So i will explain how i did to solve this problem, all i wanted was back to the current page after the login.. so, everytime i open my view login i will save the last page url, with this code:
$refering_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '' ;
and then i should save it in my session, so i can access from my controller and redirect the user to the last page, but look, i can’t simple save the url every time i access the view login, beucase every time i miss the password, i will be redirected to the login page, and so the last url, will the login and not the last one, and of course its wrong, So we have to save it on session, but only in the first time we access the view login, to do that, i compare the variable above ($refering_url) to the view login and view login validation, if its not the same, i can confirm that the previous page is the one i was before the login, and then i can save it to my session,
here the comparison, and the last url saved in my session:
if (($refering_url != ‘URL TO VIEW LOGIN‘) &&
($refering_url != ‘URL TO LOGIN VALIDATION){
$this->session->set_userdata('url', $refering_url);
}
after login is validated, on the controller, i should redirect the user , to the last page he was (the url saved on the session), to do that i used this code:
$this->session->set_userdata($data);
$url=$this->session->userdata('url');
redirect($url, 'refresh');

how can I redirect in .jsp while working with Ajax

I am developing application using Ajax and jsp.
My index.jsp page has HTML code for Login and some Ajax code in javascript. Ajax will call my another CheckLogin.jsp page
CheckLogin.jsp page checks on server for valid username and password. It returns "success" if it's valid otherwise will return message stating "username or password is not valid."
Now, when username and passwrod is valid, instead of success, I want to redirect the page to "Home.jsp" what should I do?
I am new to jsp. I appreciate your help on this.
JSP code gets run once on the server before it goes to the client, so JSP/JSTL cannot do a redirect following the success or otherwise of an AJAX call (without a full page refresh - which obviates the use of AJAX). You should to do the redirect with Javascript:
if (success) {
var successUrl = "Home.jsp"; // might be a good idea to return this URL in the successful AJAX call
window.location.href = successUrl;
}
On successful AJAX call/validation, the browser window will reload with the new URL (effectively a redirect).
Since I don't see your code, you can integrate this somewhere inside your validation :
<%
pageContext.forward("logged.jsp");
%>
function Edit() {
var allVals = $('#NEWFORMCampaignID').val();
if (allVals > 0) {
window.location = '/SMS/PrepareSMS?id='+allVals;
}
else
alert("Invalid campaign to Edit")
}
In order to redirect using Button click and pass some parameters, you can call the Controller Path(#RequestMapping(value="/SMS/PrepareSMS")) and then handle it there..

Resources