How to access one action class session in another action class in Struts2?
public String execute()
{
HttpServletRequest request=ServletActionContext.getRequest();
HttpSession session=request.getSession();
//System.out.println(" table "+tid);
//Map session = ActionContext.getContext().getSession();
Map<String,Integer> s =(Map)session.getAttribute("table"+tid);
if(s!=null)
{
System.out.println("in if");
for (Map.Entry<String,Integer> en : s.entrySet())
{
System.out.println(" in tableactio ");
}
Please Note : Session is unique to browser not to action.
in struts2 you an get session using below code :
ActionContext.getContext().getSession()
Example: Getting userid stored in session:
int userId = Integer.parseInt(ActionContext.getContext().getSession()
.get("userid").toString());
Related
Into class I get logged user like
public static GetUserById_Result GetUser(string userId)
{
GetUserById_Result user = new GetUserById_Result();
try
{
using (EF.SSMA oContext = new EF.SSMA())
{
user = oContext.GetUserById(userId).FirstOrDefault();
}
}
catch (Exception)
{
throw;
}
return user;
}
So it runs fine. But in the same class I want to acces user value into another method
public static List<GetUsers_Result> SelectAll()
{
List<GetUsers_Result> lstResult = new List<GetUsers_Result>();
try
{
using (EF.SSMA oContext = new EF.SSMA())
{
lstResult = oContext.GetUsers().Where().ToList();
}
}
catch (Exception ex)
{
throw ex;
}
return lstResult;
}
What I need to do to achieve that?, into controller is really simple I just do this:
var users = User.Identity.GetUserId();
GetUserById_Result currentUser = UserClass.GetUser(users);
var role = currentUser.BranchOfficeId;
But how can I acces it in the same class' I try to call GetUserId with
System.Web.HttpContext.Current.User.Identity.GetUserId();
but it just mark HttpContext in red and say "Cannot resolve symbol 'HttpContext'"
My target is to call only users who BranchOfficeId = user.BranchOfficeId
Help is very appreciated. Regards
If i understand your question well, make sure that you already installed the package Microsoft.Owin.Host.SystemWeb and add using System.Web, then use directely User.Identity.GetUserId()
The reason you can do this in the controller is because Controller has an HttpContext property, which has been created with the details of the current request, including the identity of the current user.
If you want to access the user from another class, you need to pass the user as an argument to your method. As an example:
using System.Security.Principal;
public class SomeClass
{
public void SomeMethod(IPrincipal user)
{
// Whatever you need
}
}
Then in your controller:
var someClass = new SomeClass();
someClass.SomeMethod(HttpContext.User);
However, if you're only interested in the user's name, then you can actually just pass a string instead:
public class SomeClass
{
public void SomeMethod(string username)
{
// Whatever you need
}
}
Then in your controller:
var someClass = new SomeClass();
someClass.SomeMethod(HttpContext.User.Identity.Name);
I have a problem knowing whether a user is authenticated or not when ajax requests are sent from jQuery.
HttpContext.User.Identity is not empty when a user does a regular request from their browser and the aspxauth cookie is set. When a user tries doing a ajax request from jQuery, the aspxauth is not set at all.
My Web.Config
<authentication mode="Forms">
<forms loginUrl="~/" />
</authentication>
Setting the FormsAuthentication Cookie
var cookie = new AuthCookie
{
UserId = user.UserId,
Email = user.Email,
Name = user.Name,
RememberMe = createPersistentCookie,
TimeZone = user.TimeZone,
CompanyId = user.CompanyId,
Roles = new List<string> { user.Role ?? "user" }
};
string userData = JsonConvert.SerializeObject(cookie);
var ticket = new FormsAuthenticationTicket(1, cookie.Email, DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
createPersistentCookie, userData);
string encTicket = FormsAuthentication.Encrypt(ticket);
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.Add(FormsAuthentication.Timeout) };
_httpContext.Response.Cookies.Add(httpCookie);
When I make requests through my broser, the auth cookie appears:
Whenever I make a request through javascript using $.get() or loading javascript scripts / Any other request through javascript, I get:
The odd thing is that on another ASP application I am using WebSecurity and that works perfectly. The auth cookie is always being sent back from client to server. For this ASP MVC 5 application, when I try to use the FormAuthentication, I cannot get the AuthCookie to proceed through all requests.
you are still able to decorate your class/method with [Authorize] and the like. If you're looking to check inside the controller method you have access to the User Property inherited from System.Web.Mvc.Controller or System.Web.Http.ApiController depending on your controller flavor :
//
// Summary:
// Returns the current principal associated with this request.
//
// Returns:
// The current principal associated with this request.
public IPrincipal User { get; set; }
it can be used like so:
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
// user has access - process request
}
Edit:
Here is an example of an [Api]Controller with an ajax[able] method that uses the controller's User property instead of HttpContext's:
public class HelloController : ApiController
{
[HttpGet]
public IHttpActionResult HelloWorld()
{
try
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
return Ok("Hello There " + User.Identity.Name + "!");
}
else
{
return Ok("Hello There Anonymous!");
}
}
catch { throw; }
}
}
I'm trying to create a LiveConnectClient with only a refresh token that was provided to me via asp.net identity (using OWIN) and the ProviderKey. It looks like the only way to do this without needing HttpContextBase is via InitializeSessionAsync.
When I try and create the client I'm getting:
Microsoft.Live.LiveAuthException: The user ID from the given RefreshTokenInfo instance does not match the refresh token.
Not really sure what user ID it is expecting as I'm giving it the provider key that was passed via ASP.NET Identity (17 chars in my case). Below is my code.
public class Class1
{
protected async Task<LiveConnectClient> GetLiveConnectClient()
{
var authClient = new LiveAuthClient(_clientId, _clientSecret, null, new RefreshTokenHandler(_refreshToken, _providerKey));
var session = await authClient.InitializeSessionAsync("http://.../signin-microsoft");
return new LiveConnectClient(session.Session);
}
}
public class RefreshTokenHandler : IRefreshTokenHandler
{
private readonly string _refreshToken;
private readonly string _userId;
public RefreshTokenHandler(string refreshToken, string userId)
{
_refreshToken = refreshToken;
_userId = userId;
}
public Task<RefreshTokenInfo> RetrieveRefreshTokenAsync()
{
return Task.FromResult(new RefreshTokenInfo(_refreshToken, _userId));
}
public async Task SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
{
await Task.Delay(0);
}
}
I am writing an Authorize filter attribute adn I'm having trouble figuring out how to get the current url as a string so I can pass it as a parameter to the LogOn action. The goal is that if a user successfully logs on, they will be redirected to the page they were originally trying to access.
public override void OnAuthorization(AuthorizeContext filterContext)
{
base.OnAuthorization(filterContext);
... my auth code ...
bool isAuth ;
... my auth code ...
if(!isAuth)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "Area", "" },
{ "Controller", "Account" },
{ "Action", "LogOn" },
{ "RedirectUrl", "/Url/String/For/Currnt/Request" } // how do I get this?
}
);
}
}
How do I get the full string Url from the current request?
Try:
var url = filterContext.HttpContext.Request.Url;
To get the complete URL you can try as suggested by the #rboarman but usually the RedirectUrl will be the relative url and for that you have to try the the RawUrl property of the Request object.
filterContext.HttpContext.Request.Url ===> http://somesite.com/admin/manage
filterContext.HttpContext.Request.RawUrl ====> /admin/manage
EDITED: Fixed the second example
In my specific case I was after the UrlReferrer URL.
filterContext.HttpContext.Request.UrlReferrer
This one let me redirect the user back to the page he was before trying to access an action he doesn't have permission to access.
This is the highest ranked result on Google so in Asp.net Core 2.0 this is how I'm doing it:
context.HttpContext.Request.Url();
using this extension method:
/// <summary>
/// Returns the absolute url.
/// </summary>
public static string Url(this HttpRequest request)
{
return $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
}
I have the following in my code:
if (Session["CurrentUrl"] != null)
{
var ip = new Uri((string)Session["CurrentUrl"]);
var ipNoPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery);
return Redirect(ipNoPort);
}
return Home();
It checks if a Session variable is set and then redirects to that URL or lets the action return to the Home method.
Does anyone have an example of how I could convert this into an action filter?
Also can I provide the action filter with the parameter of "Home" so it knows where to go to next?
Here is an example for ActionFilter that does redirect
public class TheFilter: ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
if (controllerName !="TopSecert")
return;
var redirectTarget = new RouteValueDictionary
{{"action", "ActionName"}, {"controller", "ControllerName"}};
filterContext.Result = new RedirectToRouteResult(redirectTarget);
// Or give a url (the last in this example):
filterContext = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsolutePath);
// The session you can get from the context like that:
var session = filterContext.HttpContext.Session;
}
}
Edit: change from Executing to Executed and added session handling.