I'm using Apache Shiro 1.2.0 in a long-running application that reads messages from a queue and and takes action. The action taken requires a Shiro authenticated session, so I've implemented an "ActAsAuthenticationToken" and custom credentials matcher which allows us to login in with only the username. I'm using the DefaultSecurityManager with only my custom realm and subject factory injected. Everything else should be default.
As it is configured, everything worked fine for a while, but as the application ran a long time (not that long - like a full day) I started to get this stack trace whenever I did anything that required the session:
Caused by: org.apache.shiro.session.UnknownSessionException: There is no session with id [f5b7c3bf-2c53-40e9-a707-37f4265970aa]
at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:170)
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSessionFromDataSource(DefaultSessionManager.java:236)
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSession(DefaultSessionManager.java:222)
at org.apache.shiro.session.mgt.AbstractValidatingSessionManager.doGetSession(AbstractValidatingSessionManager.java:118)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupSession(AbstractNativeSessionManager.java:105)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupRequiredSession(AbstractNativeSessionManager.java:109)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.getAttribute(AbstractNativeSessionManager.java:206)
at org.apache.shiro.session.mgt.DelegatingSession.getAttribute(DelegatingSession.java:141)
at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
at com.factorlab.security.FactorlabDelegatingSubject.getUser(FactorlabDelegatingSubject.java:34)
at com.factorlab.security.FactorlabDelegatingSubject.getUser(FactorlabDelegatingSubject.java:10)
at com.factorlab.persistence.AbstractEntityDao.getCurrentUser(AbstractEntityDao.java:227)
at com.factorlab.persistence.AbstractEntityDao.fireEvent(AbstractEntityDao.java:215)
at com.factorlab.persistence.AbstractEntityDao.saveOrUpdate(AbstractEntityDao.java:190)
at com.factorlab.persistence.AbstractEntityDao.saveOrUpdate(AbstractEntityDao.java:177)
at com.factorlab.persistence.AbstractEntityDao.saveOrUpdate(AbstractEntityDao.java:38)
at sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:196)
at $Proxy72.saveOrUpdate(Unknown Source)
at com.factorlab.observations.sales.OpportunityScoreUpdateServiceImpl.receiveOpportunityEvent(OpportunityScoreUpdateServiceImpl.java:83)
at sun.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy76.receiveOpportunityEvent(Unknown Source)
at sun.reflect.GeneratedMethodAccessor102.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:69)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:84)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57)
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:102)
at org.springframework.integration.util.AbstractExpressionEvaluator.evaluateExpression(AbstractExpressionEvaluator.java:126)
at org.springframework.integration.util.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:227)
at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:127)
at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:73)
... 49 more
The really weird part (as far as I'm concerned) is that I have a successful login (or at least an indication that I already have been authenticated right before I get the error:
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
#Trace(dispatcher = true)
public void receiveOpportunityEvent(EntityEvent<Opportunity> event) {
sessionFactory.getCurrentSession().refresh(event.getEntity());
log.info("OpportunityScoreUpdateService receiveOpportunityEvent: " + event);
//
//
// Here we see that we are either authenticated or we log in successfully
//
//
if (!securityUtils.getSubject().isAuthenticated()) {
try {
securityUtils.getFactorlabSubject().login(new ActAsAuthenticationToken(event.getEventUsername()));
} catch (RuntimeException e) {
log.error("Could not log in user " + event.getEventUsername() + ": " + e.getMessage(), e);
return;
}
}
if (event.getEntity() instanceof ObservedOpportunity) {
ObservedOpportunity opportunity = (ObservedOpportunity) event.getEntity();
opportunity = (ObservedOpportunity) opportunityDao.getById(opportunity.getId(), SkippedCheck.PERMISSION, SkippedCheck.DELETED);
if (!opportunity.isDeleted()) {
List<Stage> stages = stageDao.getAllByZone(opportunity.getZone(), SkippedCheck.PERMISSION);
Map<Stage, Double> originalScoresByStage = new HashMap<Stage, Double>();
Map<Stage, Double> newScoresByStage = new HashMap<Stage, Double>();
final Double originalTotal = opportunity.getTotalScore();
for (Stage stage : stages) {
originalScoresByStage.put(stage, opportunity.getScoreByStage(stage));
double score = calculator.getScoreForOpportunityAndStage(opportunity, stage);
opportunity.setScoreByStage(stage, score);
newScoresByStage.put(stage, opportunity.getScoreByStage(stage));
}
final double newTotalScore = calculator.getTotalScoreForOpportunity(opportunity);
opportunity.setTheTotalScore(newTotalScore);
final boolean scoreChanged = originalTotal == null ||
Math.round(originalTotal) != Math.round(newTotalScore) ||
checkStageScoresChanged(originalScoresByStage, newScoresByStage);
if (scoreChanged) {
opportunity.setScoreCalculated(new Date());
//
//
// Here is where we get the exception
//
//
opportunityDao.saveOrUpdate(opportunity, SkippedCheck.PERMISSION);
} else {
opportunityDao.refresh(opportunity);
}
}
}
}
What could be causing this exception?
I was getting this error and found that completely destroying any existing session before calling subject.login(credentials) fixed it.
// Login the user
private Subject loginUser()
{
ensureUserIsLoggedOut();
Subject subject = SecurityUtils.getSubject();
subject.login(credentials);
}
And the supporting routines are:
// Logout the user fully before continuing.
private void ensureUserIsLoggedOut()
{
try
{
// Get the user if one is logged in.
Subject currentUser = SecurityUtils.getSubject();
if (currentUser == null)
return;
// Log the user out and kill their session if possible.
currentUser.logout();
Session session = currentUser.getSession(false);
if (session == null)
return;
session.stop();
}
catch (Exception e)
{
// Ignore all errors, as we're trying to silently
// log the user out.
}
}
Shiro is validating credentials against SecuritySubject, which is stored in Session. So, it's very likely your session expired after some time of inactivity. You can change expiration time in web.xml or you can use Shiro rememberMe function, but your client have to support cookies. After rememberMe function SecuritySubject will obtain different session and will return false against isAuthenticated, but isRemembered will return true.
The session will never expired This will produce another problem, when your session will never expire. It will most likely get you out of memory, because your web container is most likely using memory session manager.
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
Shiro rememberMe
http://shiro.apache.org/java-authentication-guide.html
//Example using most common scenario:
//String username and password. Acquire in
//system-specific manner (HTTP request, GUI, etc)
UsernamePasswordToken token =
new UsernamePasswordToken( username, password );
//”Remember Me” built-in, just do this:
token.setRememberMe(true);
We can disable the session storage in shiro.
The org.apache.shiro.mgt.DefaultSessionStorageEvaluator class contains a flag called sessionStorageEnabled. We can make it false.
I use the following in my spring application context for not using session storage.
<bean id="defaultSessionStorageEvaluator" class="org.apache.shiro.mgt.DefaultSessionStorageEvaluator">
<property name="sessionStorageEnabled" value="false" />
<bean id="defaultSubjectDAO" class="org.apache.shiro.mgt.DefaultSubjectDAO">
<property name="sessionStorageEvaluator" ref="defaultSessionStorageEvaluator" />
</bean>
Related
So I've built and published a new website that uses Azure B2C as the authentication mechanism.
What I found was that the login and sign would work fine for a while. But after a period of time, say couple of hours after visiting the site post deployment, I would find that on login or signup, after successful authentication, instead of being redirected back to the return url set up in the b2c configuration, my browser would get caught between an infinite loop between the post authentication landing page that is protected with an authorise attribute and the Azure B2C Login page, before finally finishing with Http 400 error message with the message - Bad Request - Request too long.
I did some googling around this and there are number of posts that suggest that the problem is with the cookie, and that deleting the cookie should resolve the issue. This is not the case. The only thing I have found to fix this is restarting the application on the webserver, or waiting say 24 hours for some kind of cache or application pool to reset. Anyone has any ideas what's going on here?
Ok, I think I may have found the answer.
Looks like there is an issue with Microsoft.Owin library and the way it sets cookies. Writing directly to System.Web solves this problem according to this article.
There are three suggested solutions:
Ensure session is established prior to authentication: The conflict between System.Web and Katana cookies is per request, so it may be possible for the application to establish the session on some request prior to the authentication flow. This should be easy to do when the user first arrives, but it may be harder to guarantee later when the session or auth cookies expire and/or need to be refreshed.
Disable the SessionStateModule: If the application is not relying on session information, but the session module is still setting a cookie that causes the above conflict, then you may consider disabling the session state module.
Reconfigure the CookieAuthenticationMiddleware to write directly to System.Web's cookie collection.
I will opt for the third option, which is to overwrite the default Cookie AuthenticationMiddleware, as they have suggested below.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
// ...
CookieManager = new SystemWebCookieManager()
});
public class SystemWebCookieManager : ICookieManager
{
public string GetRequestCookie(IOwinContext context, string key)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
var cookie = webContext.Request.Cookies[key];
return cookie == null ? null : cookie.Value;
}
public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
bool pathHasValue = !string.IsNullOrEmpty(options.Path);
bool expiresHasValue = options.Expires.HasValue;
var cookie = new HttpCookie(key, value);
if (domainHasValue)
{
cookie.Domain = options.Domain;
}
if (pathHasValue)
{
cookie.Path = options.Path;
}
if (expiresHasValue)
{
cookie.Expires = options.Expires.Value;
}
if (options.Secure)
{
cookie.Secure = true;
}
if (options.HttpOnly)
{
cookie.HttpOnly = true;
}
webContext.Response.AppendCookie(cookie);
}
public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
AppendResponseCookie(
context,
key,
string.Empty,
new CookieOptions
{
Path = options.Path,
Domain = options.Domain,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
}
}
I will give that a crack, and post my results back here.
In trying to integrate RavenDB usage with Service Stack, I ran across the following solution proposed for session management:
A: using RavenDB with ServiceStack
The proposal to use the line below to dispose of the DocumentSession object once the request is complete was an attractive one.
container.Register(c => c.Resolve<IDocumentStore>().OpenSession()).ReusedWithin(ReuseScope.Request);
From what I understand of the Funq logic, I'm registering a new DocumentSession object with the IoC container that will be resolved for IDocumentSession and will only exist for the duration of the request. That seemed like a very clean approach.
However, I have since run into the following max session requests exception from RavenDB:
The maximum number of requests (30) allowed for this session has been
reached. Raven limits the number of remote calls that a session is
allowed to make as an early warning system. Sessions are expected to
be short lived, and Raven provides facilities like Load(string[] keys)
to load multiple documents at once and batch saves.
Now, unless I'm missing something, I shouldn't be hitting a request cap on a single session if each session only exists for the duration of a single request. To get around this problem, I tried the following, quite ill-advised solution to no avail:
var session = container.Resolve<IDocumentStore>().OpenSession();
session.Advanced.MaxNumberOfRequestsPerSession = 50000;
container.Register(p => session).ReusedWithin(ReuseScope.Request);
Here is a sample of how I'm using the resolved DocumentSession instance:
private readonly IDocumentSession _session;
public UsersService(IDocumentSession session)
{
_session = session;
}
public ServiceResponse<UserProfile> Get(GetUser request)
{
var response = new ServiceResponse<UserProfile> {Successful = true};
try
{
var user = _session.Load<UserProfile>(request.UserId);
if (user == null || user.Deleted || !user.IsActive || !user.IsActive)
{
throw HttpError.NotFound("User {0} was not found.".Fmt(request.UserId));
}
response.Data = user;
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
response.StackTrace = ex.StackTrace;
response.Errors.Add(ex.Message);
response.Successful = false;
}
return response;
}
As far as I can see, I'm implementing SS + RavenDB "by the book" as far as the integration point goes, but I'm still getting this max session request exception and I don't understand how. I also cannot reliably replicate the exception or the conditions under which it is being thrown, which is very unsettling.
I'm having a really difficult time creating unit tests for my MVC4 application, using NUnit. Right now I'm just focusing on this one test in particular, which logs a user in OR creates them if they don't exist, and then logs them in. Here is the test :
[Test]
public void LoginValidUser()
{
//Start up the DB connection
App_Start_DB();
//Setup our default test user
string UserName = "LocalTestUser#penrouse.com";
string Password = "books";
bool LoginWorked = false;
//check and see if our test user exists
if (!WebSecurity.UserExists(UserName))
{
//If not, create them
WebSecurity.CreateUserAndAccount(UserName, Password, new
{
Name = "Local Test User",
IsPromotional = true,
IsAllowShare = true
});
//Log them in
LoginWorked = WebSecurity.Login(UserName, Password);
}
else
{
//This user already exists, just log them in
LoginWorked = WebSecurity.Login(UserName, Password);
}
Assert.IsTrue(LoginWorked);
Trace.WriteLine("Login Valid User Result : " + LoginWorked.ToString());
}
The problem is that every time I attempt WebSecurity.Login(), I get a null reference exception, and the stack trace points to :
System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie, String strCookiePath);
Calling that method directly before the login attempt the does not change the behavior. Thus, I have two questions :
Is there a better way to go about testing these parts of SimpleMembership?
If not, is there a good way to override or mock out the AuthCookie so that the login will work when tested in this way?
Any help\insight would be hugely appreciated.
I am evaluating ServiceStack using OrmLite. The built in Auth service, along with Session and Cache are so much better than ASP.NET membership provider.
However, out of the box the Auth Service does not provide some of the features required for apps we want to build like:
Change password
Locking of account after 3 unsuccessful logon attempts
Disabling user accounts
Password reminder question and answer
Audit log of log on attempts
Do I need to build custom auth provider or is there something out there which already does provides this functionality?
Many thanks!
I'm just starting to implement a password reset and can see two ways of achieving it (I've not tested - or even tried - either yet):
1.Create a class that inherits from Registration and handles PUT. It should then be possible to call the UpdateUserAuth method of the registration class which would change the password. The problem - for me - here is that the put validation requires username and password to be specified, not just one (We only use email as an identifier). This could be worked around by turning the validation feature off.
2.Create a password reset service that does what UpdateUserAuth does.
var session = this.GetSession();
var existingUser = UserAuthRepo.GetUserAuth(session, null);
if (existingUser == null)
{
throw HttpError.NotFound("User does not exist");
}
var newUserAuth = ToUserAuth(request);
UserAuthRepo.UpdateUserAuth(newUserAuth, existingUser, request.Password);
Obviously need to add some appropriate validation in.
UPDATED
I've put my change password reminder/reset service up as a gist (My first gist!)
here's what I did, works well. - I realise the "new" is a code-smell, just inject it :)
private int LoginAttempts = 0;
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var authRepo = authService.TryResolve<IUserAuthRepository>();
if (authRepo == null)
{
Log.WarnFormat("Tried to authenticate without a registered IUserAuthRepository");
return false;
}
var session = authService.GetSession();
UserAuth userAuth = null;
if (authRepo.TryAuthenticate(userName, password, out userAuth))
{
session.PopulateWith(userAuth);
session.IsAuthenticated = true;
session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
session.ProviderOAuthAccess = authRepo.GetUserOAuthProviders(session.UserAuthId)
.ConvertAll(x => (IOAuthTokens)x);
return true;
}
else
{
LoginAttempts++;
if (LoginAttempts >= 3)
{
ServiceStack.ServiceInterface.Service s = new Service();
s.Db.ExecuteSql("update [User] set AccountLocked = 'true' where Email='" + userName + "'");
}
authService.RemoveSession();
return false;
}
}
and I hope the mod_from_hell manages to leave this alone!!!
I have an EJB which makes a call to another server in the cell using HTTP (REST api).
At the EJB context the user is already authenticated and authorized, how can I propagate the security tokens to the other server avoiding the need to provide credentials in the request ?
It is possible to obtain WebSphere's Ltpa token from the security subject and pass it as a cookie for the HTTP call:
public static SingleSignonToken getSSOTokenFromSubject(final Subject subject) {
if (subject == null) {
return null;
}
return AccessController.doPrivileged(new PrivilegedAction<SingleSignonToken>() {
public SingleSignonToken run() {
Set<SingleSignonToken> ssoTokens = subject.getPrivateCredentials(SingleSignonToken.class);
for (SingleSignonToken ssoToken : ssoTokens) {
if (ssoToken.getName().equals("LtpaToken")) {
return ssoToken;
}
}
return null;
}
});
}
// Get cookie to add to outgoing HTTP requests
SingleSignonToken ssoToken = getSSOTokenFromSubject(subject);
String ssoTokenStr = null;
if (ssoToken != null) {
byte[] ssoTokenBytes = ssoToken.getBytes();
ssoTokenStr = com.ibm.ws.util.Base64.encode(ssoTokenBytes);
}
String ssoTokenCookie = "LtpaToken2=" + ssoTokenStr;
By adding the ssoTokenCookie to the request cookies there is no need to provider user credentials.
Cookie ltpaCookie = WebSecurityHelper.getSSOCookieFromSSOToken();
Extracts the SSO token from the subject of current thread and builds an SSO cookie out of it for use on downstream web invocations. Basically what the whole code in the post below does. This method is accessible from WAS 8.x I believe.
Following Jar is needed as compile reference:
com.ibm.ws.admin.client-8.5.0.jar
(I'm using WAS 8.5.5.11 for this example)