You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@shiro.apache.org by 张云 <zy...@163.com> on 2016/08/11 15:19:19 UTC

security manager not available

hi,all

    I use shiro with spring and configure ShiroFilterFactoryBean without any customized filters.
         I set the filterChainDefinition:


/sys/menu = user


When I access the url, I think it will redirect me to loginUrl. But he pass the request and throw the exception where SecurityUtils.getSubject is called.


I step into the call, and find the exception is thrown by the ThreadContex.getSecurityManager. 


I want to know where the security manager is bound to ThreadContex? Or if I made a wrong configuration?


Thx.


发自 网易邮箱大师

Re: Re: security manager not available

Posted by Tomas Lund Petersen <ko...@gmail.com>.
Hi again,
I don't want to throw you in the wrong track. Im just sharing my experience
so thread lightly and anyone feel free to comment.

If you dont have a web.xml or dont have access to it as you have mentioned
you can try something like this
from czetsuya-tech jee 6 aproach to shiro
<http://czetsuya-tech.blogspot.com.ar/2012/10/how-to-integrate-apache-shiro-with.html#.V6yorvnhCUk>

public class SessionIdHandler implements SOAPHandler<SOAPMessageContext> {
static final String META_INF_HANDLERS_XML = "/META-INF/handlers.xml";

private static final String THREAD_STATE = "threadState";
private static final Logger log = LoggerFactory
.getLogger(SessionIdHandler.class);
// @Inject SecurityProducer sProducer;

// SessionIdHandler(){
//// sProducer = (SecurityProducer) BeanProvider
//// .lookupResource(BeanProvider.SECURITY_PRODUCER_RESOURCE);
// }
/**
* SOAP Request
*
* <?xml version="1.0" encoding="UTF-8"?><S:Envelope
* xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> <S:Header/> <S:Body>
* <ns2:logout xmlns:ns2="http://service.ursula.com/">
* <session_id>14f92165-64bd-4783-b111-7945012dd607</session_id>
* </ns2:logout> </S:Body> </S:Envelope>
*/
public boolean handleMessage(SOAPMessageContext mc) {
Boolean outbound = (Boolean) mc
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
System.out.println("SessionIdHandler Inbound soap Message");
try {
SecurityInterceptor.initSecurityManager();// se asegura de que se haya
inicializado el SecurityManager
SecurityManager sm = SecurityUtils.getSecurityManager();
Builder builder = (new Subject.Builder(sm));
Session session=null;
final SOAPMessage message = mc.getMessage();
final SOAPBody body = message.getSOAPBody();
NodeList element = body
.getElementsByTagName(LoginService.SESSION_ID_PARAM);
if (element.item(0) != null) {
System.out.println("SessionIdHandler Message has sessionId param");
String sessionId = element.item(0).getTextContent();
try{//trato de crear la session a partir del sessionId
 SessionKey sK = new DefaultSessionKey(sessionId);
  session =sm.getSession(sK);
 if(session == null){
 System.out.println("Session does not exist");
return false;
 } else {//la session se creo correctamente
 builder.sessionCreationEnabled(false);
 builder.session(session);
 }
}catch(SessionException se){//no se pudo crear la session a partir del
session id
System.out.println("sm.getSession(sK);= "+session+"
"+se.getClass().getSimpleName()+" "+ se.getMessage());
return false;
}
} else {
System.out.println("SessionIdHandler Message doesn't have sessionId param");
System.out.println("binding a new subject to the thread");
builder.sessionCreationEnabled(true);
}
*Subject subject = builder.buildSubject();*

* ThreadState threadState = new SubjectThreadState(subject);*
* threadState.bind();*
* mc.put(THREAD_STATE, threadState);// pongo el threadstate en el context
para liberarlo a la salida*
} catch (SOAPException e) {
log.info("SOAPException  = " + e.getMessage());
return false;
}
} else {// Cuando el mensaje es de salida aprobecho para limpiar el
threadstate.
ThreadState threadState = (ThreadState) mc.get(THREAD_STATE);
if (threadState != null) {
threadState.clear();
}
}

return true;
}

public Set<QName> getHeaders() {
return Collections.emptySet();
}

public void close(MessageContext mc) {
}

public boolean handleFault(SOAPMessageContext mc) {
return true;
}
}


@Interceptor
public class SecurityInterceptor {

private Logger log = LoggerFactory.getLogger(SecurityInterceptor.class);
private static SecurityManager securityManager=null;

@PostConstruct
public void interceptPostConstruct(InvocationContext ctx) {
initSecurityManager();
}
*public static void initSecurityManager(){*
* if(securityManager==null){//inicializando securityManager*
* String  iniFile
=SecurityInterceptor.class.getResource("/META-INF/shiro.ini").toExternalForm();//ok!*
* securityManager = new IniSecurityManagerFactory(*
* iniFile).getInstance();*
* SecurityUtils.setSecurityManager(securityManager);//Esto lo agrega como
una referencia estatica de SecurityUtils. si lo corro mas de una vez se
pierden las sessiones. *
* }*
* }*
@PreDestroy
private void shutdown() {  }

@AroundInvoke
public Object interceptGet(InvocationContext ctx) throws Exception {
Subject subject = SecurityUtils.getSubject();
// log.info("SecurityInterceptor.interceptGet Securing )"
// +  ctx.getClass().getSimpleName() +" "+ ctx.getMethod());

final Class<? extends Object> runtimeClass = ctx.getTarget().getClass();

// Check if user is authenticated
boolean requiresAuthentication = false;
try { // check method first
Annotation a = ctx.getMethod().getAnnotation(
RequiresAuthentication.class);
if (a != null) {
// log.info("Method " + ctx.getMethod().getName()
// + " requires authentication.");// Annotation: " + a);
requiresAuthentication = true;
}

} catch (NullPointerException e) {
requiresAuthentication = false;
}

if (!requiresAuthentication) { // then check class level
try {
if (runtimeClass != null) {
Annotation a = runtimeClass
.getAnnotation(RequiresAuthentication.class);
if (a != null) {
// log.info("Class " + ctx.getClass().getName()
// + " requires authentication ");
requiresAuthentication = true;
}
} else {
//log.info("runtime Class is null");
throw (new NullPointerException());
}

} catch (NullPointerException e) {
requiresAuthentication = false;
}
}

if (requiresAuthentication) {
log.info("[security] checking for authenticated user.");
try {
if (!subject.isAuthenticated()) {
System.out.println("subject.isAuthenticated es false entoces respondo
AuthorizationException");
log.info("[security] user not authenticated.");
throw new AuthorizationException();
}else{
log.info("OK!! subject is authenticated");
}
} catch (Exception e) {
log.info("Access denied - {}: {}" + e.getClass().getName()
+ e.getMessage());
throw e;
}
}
/************************************************************/

// check if user has roles
boolean requiresRoles = false;
List<String> listOfRoles = null;

try { // check method first
RequiresRoles roles = ctx.getMethod().getAnnotation(
RequiresRoles.class);
listOfRoles = Arrays.asList(roles.value());
requiresRoles = true;
} catch (NullPointerException e) {
requiresRoles = false;
}

if (!requiresRoles || listOfRoles == null) { // check class
try {
RequiresRoles roles = runtimeClass
.getAnnotation(RequiresRoles.class);
listOfRoles = Arrays.asList(roles.value());
requiresRoles = true;
} catch (NullPointerException e) {
requiresRoles = false;
}
}

if (requiresRoles && listOfRoles != null) {
log.info("[security] checking for roles.");
try {
boolean[] boolRoles = subject.hasRoles(listOfRoles);
boolean roleVerified = false;
for (boolean b : boolRoles) {
if (b) {
roleVerified = true;
break;
}
}
if (!roleVerified) {
throw new javax.ejb.EJBException(
"Access denied. User doesn't have enough privilege Roles:"
+ listOfRoles + " to access this page.");
// throw new AuthorizationException(
// "Access denied. User doesn't have enough privilege Roles:"
// + listOfRoles + " to access this page.");
}
} catch (Exception e) {
log.info("Access denied - {}: {}" + e.getClass().getName()
+ e.getMessage());
throw e;
}
}
/************************************************************/

// and lastly check for permissions
boolean requiresPermissions = false;
List<String> listOfPermissionsString = null;

try { // check method first
RequiresPermissions permissions = ctx.getMethod().getAnnotation(
RequiresPermissions.class);
listOfPermissionsString = Arrays.asList(permissions.value());
requiresPermissions = true;
} catch (NullPointerException e) {
requiresPermissions = false;
}

if (!requiresPermissions || listOfPermissionsString == null) {
// check class
try {
RequiresPermissions permissions = runtimeClass
.getAnnotation(RequiresPermissions.class);
listOfPermissionsString = Arrays.asList(permissions.value());
requiresPermissions = true;
} catch (NullPointerException e) {
requiresPermissions = false;
}
}

if (requiresPermissions && listOfPermissionsString != null) {
log.info("[security] checking for permissions.");
List<Permission> listOfPermissions = new ArrayList<Permission>();
for (String p : listOfPermissionsString) {
listOfPermissions.add((Permission) new WildcardPermission(p));
}
try {
boolean[] boolPermissions = subject
.isPermitted(listOfPermissions);
boolean permitted = false;
for (boolean b : boolPermissions) {
if (b) {
permitted = true;
break;
}
}
if (!permitted) {
throw new AuthorizationException(
"Access denied. User doesn't have enough privilege Permissions:"
+ listOfRoles + " to access this page.");
}
} catch (Exception e) {
log.info("Access denied - {}: {}" + e.getClass().getName()
+ e.getMessage());
throw e;
}
}

return ctx.proceed();
}

}

On Thu, Aug 11, 2016 at 1:27 PM, 张云 <zy...@163.com> wrote:

> Thank you for your reply.
> But I don't have the permission to edit web.xml or write a
> WebApplicationIntializer.
> I go around this by wtriting a spring intial izing bean to load Shiro's
> environment and register the shiro filter. It works for
>
> /demo = authc
>
> When I request /demo, It redirct me to the loginUrl
>
> Maybe The problem is that I don't config shiro filter with the four
> Dispachers.
>
> Thanks again.
> By the way, do you known where the security manager is bound to
> ThreadContex ?
>
>
>
> 发自 网易邮箱大师 <http://u.163.com/signature>
> On 08/12/2016 00:12, Tomas Lund Petersen <ko...@gmail.com> wrote:
>
> Hi,
> Im not an expert but i wanted to give you a quick reply.
> I think its in the webFilter. But it depends of your configuration.
>
> take a look at http://shiro.apache.org/webapp-tutorial.html
> you should have something like this in your web.xml
>
> 1b: Enable Shiro in web.xml
>
> While we have a shiro.ini configuration, we need to actually *load* it
> and start a new Shiro environment and make that environment available to
> the web application.
>
> We do all of this by adding a few things to the existing
> src/main/webapp/WEB-INF/web.xml file:
>
> <listener>
>     <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
> </listener>
>
> <filter>
>     <filter-name>ShiroFilter</filter-name>
>  *   <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>*
> </filter>
>
> <filter-mapping>
>     <filter-name>ShiroFilter</filter-name>
>     <url-pattern>/*</url-pattern>
>     <dispatcher>REQUEST</dispatcher>
>     <dispatcher>FORWARD</dispatcher>
>     <dispatcher>INCLUDE</dispatcher>
>     <dispatcher>ERROR</dispatcher>
> </filter-mapping>
>
>
> On Thu, Aug 11, 2016 at 12:19 PM, 张云 <zy...@163.com> wrote:
>
>> hi,all
>>     I use shiro with spring and configure ShiroFilterFactoryBean without
>> any customized filters.
>>          I set the filterChainDefinition:
>>
>> /sys/menu = user
>>
>> When I access the url, I think it will redirect me to loginUrl. But he
>> pass the request and throw the exception where SecurityUtils.getSubject is
>> called.
>>
>> I step into the call, and find the exception is thrown by the
>> ThreadContex.getSecurityManager.
>>
>> I want to know where the security manager is bound to ThreadContex? Or if
>> I made a wrong configuration?
>>
>> Thx.
>>
>> 发自 网易邮箱大师 <http://u.163.com/signature>
>>
>>
>>
>
>
>

Re: security manager not available

Posted by Lenny Primak <lp...@hope.nyc.ny.us>.
It’s all done here:
<listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>

If you can’t edit web.xml (which is very, very strange) you can probably subclass the above classes with your own @WebListener and @WebFilter annotations
provided of course you are using Servlet 3.x or above.

> On Aug 11, 2016, at 11:27 AM, 张云 <zy...@163.com> wrote:
> 
> Thank you for your reply.
> But I don't have the permission to edit web.xml or write a WebApplicationIntializer.
> I go around this by wtriting a spring intial izing bean to load Shiro's environment and register the shiro filter. It works for
> 
> /demo = authc 
> 
> When I request /demo, It redirct me to the loginUrl
> 
> Maybe The problem is that I don't config shiro filter with the four Dispachers.
> 
> Thanks again.
> By the way, do you known where the security manager is bound to ThreadContex ?
> 
> 
> 
> 发自 网易邮箱大师 <http://u.163.com/signature>
> On 08/12/2016 00:12, Tomas Lund Petersen <ma...@gmail.com> wrote:
> Hi,
> Im not an expert but i wanted to give you a quick reply.
> I think its in the webFilter. But it depends of your configuration.
> 
> take a look at http://shiro.apache.org/webapp-tutorial.html <http://shiro.apache.org/webapp-tutorial.html>
> you should have something like this in your web.xml
> 
> 1b: Enable Shiro in web.xml
> 
> While we have a shiro.ini configuration, we need to actually load it and start a new Shiro environment and make that environment available to the web application.
> 
> We do all of this by adding a few things to the existing src/main/webapp/WEB-INF/web.xml file:
> 
> <listener>
>     <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
> </listener>
> 
> <filter>
>     <filter-name>ShiroFilter</filter-name>
>     <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
> </filter>
> 
> <filter-mapping>
>     <filter-name>ShiroFilter</filter-name>
>     <url-pattern>/*</url-pattern>
>     <dispatcher>REQUEST</dispatcher>
>     <dispatcher>FORWARD</dispatcher>
>     <dispatcher>INCLUDE</dispatcher>
>     <dispatcher>ERROR</dispatcher>
> </filter-mapping>
> 
> On Thu, Aug 11, 2016 at 12:19 PM, 张云 <zyunone@163.com <ma...@163.com>> wrote:
> hi,all
>     I use shiro with spring and configure ShiroFilterFactoryBean without any customized filters.
>          I set the filterChainDefinition:
> 
> /sys/menu = user
> 
> When I access the url, I think it will redirect me to loginUrl. But he pass the request and throw the exception where SecurityUtils.getSubject is called.
> 
> I step into the call, and find the exception is thrown by the ThreadContex.getSecurityManager. 
> 
> I want to know where the security manager is bound to ThreadContex? Or if I made a wrong configuration?
> 
> Thx.
> 
> 发自 网易邮箱大师 <http://u.163.com/signature>
> 
> 
> 
> 


Re: Re: security manager not available

Posted by 张云 <zy...@163.com>.
Thank you for your reply.
But I don't have the permission to edit web.xml or write a WebApplicationIntializer.
I go around this by wtriting a spring intial izing bean to load Shiro's environment and register the shiro filter. It works for


/demo = authc 


When I request /demo, It redirct me to the loginUrl


Maybe The problem is that I don't config shiro filter with the four Dispachers.


Thanks again.
By the way, do you known where the security manager is bound to ThreadContex ?






发自 网易邮箱大师
On 08/12/2016 00:12, Tomas Lund Petersen wrote:
Hi,
Im not an expert but i wanted to give you a quick reply.
I think its in the webFilter. But it depends of your configuration.


take a look at http://shiro.apache.org/webapp-tutorial.html
you should have something like this in your web.xml


1b: Enable Shiro in web.xml

While we have a shiro.ini configuration, we need to actually load it and start a new Shiro environment and make that environment available to the web application.

We do all of this by adding a few things to the existing src/main/webapp/WEB-INF/web.xml file:

<listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>ShiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>


On Thu, Aug 11, 2016 at 12:19 PM, 张云 <zy...@163.com> wrote:

hi,all

    I use shiro with spring and configure ShiroFilterFactoryBean without any customized filters.
         I set the filterChainDefinition:


/sys/menu = user


When I access the url, I think it will redirect me to loginUrl. But he pass the request and throw the exception where SecurityUtils.getSubject is called.


I step into the call, and find the exception is thrown by the ThreadContex.getSecurityManager. 


I want to know where the security manager is bound to ThreadContex? Or if I made a wrong configuration?


Thx.


发自 网易邮箱大师





Re: security manager not available

Posted by Tomas Lund Petersen <ko...@gmail.com>.
Hi,
Im not an expert but i wanted to give you a quick reply.
I think its in the webFilter. But it depends of your configuration.

take a look at http://shiro.apache.org/webapp-tutorial.html
you should have something like this in your web.xml

1b: Enable Shiro in web.xml

While we have a shiro.ini configuration, we need to actually *load* it and
start a new Shiro environment and make that environment available to the
web application.

We do all of this by adding a few things to the existing
src/main/webapp/WEB-INF/web.xml file:

<listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>ShiroFilter</filter-name>
 *   <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>*
</filter>

<filter-mapping>
    <filter-name>ShiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>


On Thu, Aug 11, 2016 at 12:19 PM, 张云 <zy...@163.com> wrote:

> hi,all
>     I use shiro with spring and configure ShiroFilterFactoryBean without
> any customized filters.
>          I set the filterChainDefinition:
>
> /sys/menu = user
>
> When I access the url, I think it will redirect me to loginUrl. But he
> pass the request and throw the exception where SecurityUtils.getSubject is
> called.
>
> I step into the call, and find the exception is thrown by the ThreadContex.
> getSecurityManager.
>
> I want to know where the security manager is bound to ThreadContex? Or if
> I made a wrong configuration?
>
> Thx.
>
> 发自 网易邮箱大师 <http://u.163.com/signature>
>
>
>