Java spring security - intercept subdomain url for

2019-06-18 04:43发布

I have an application with spring security installed and working well -- it is currently running out of www.exampledomain.com.

I now want to expand the application running out of a subdomain. For example newapp.exampledomain.com.

The only problem is that for this new app a user needs to log in. In spring it is very easy to intercept urls via <intercept-url pattern="/Admin/*" access="ROLE_GENERAL"/>

but what do you do when you want to intercept a subdomain for login? For example the following doesnt work for me:

<intercept-url pattern="http://newapp.exampledomain.com/*" access="ROLE_GENERAL"/>

Any thoughts on how to get around this?

2条回答
看我几分像从前
2楼-- · 2019-06-18 05:19

One option would be to write your own AccessDecisionVoter which extends RoleVoter and adds an additional check based on the hostname. Something like this:

public class MyVoter extends RoleVoter {
  public int vote(Authentication authentication,
                java.lang.Object object,
                java.util.Collection<ConfigAttribute> attributes) {
    FilterInvocation filterInvocation = (FilterInvocation) object;
    HttpRequest request = filterInvocation.getHttpRequest();
    // get subdomain from request
    String subdomain = getSubdomain(request);
    if ("free".equals(subdomain)) {
      return ACCESS_GRANTED;
    }
    else {
      super.vote(authentication, object, attributes);
    }
  }
}

Then wire up your voter:

<security:http auto-config="true" 
               use-expressions="true" 
               access-decision-manager-ref="accessDecisionManager">
...
</security:http>

<bean id="accessDecisionManager"
      class="org.springframework.security.access.vote.UnanimousBased">
    <property name="decisionVoters">
        <list>
            <bean class="com.acme.MyVoter" />
        </list>
    </property>
</bean>

If you wanted to take it a step further you could also write your own configuration attributes which would allow you remove the hardcoded hostname checks in the voter and do something like:

<intercept-url pattern="/Admin/*" access="ROLE_GENERAL" domain="free.acme.com" />
查看更多
做个烂人
3楼-- · 2019-06-18 05:19

In your session cookie, domain should be explicitly set to exampledomain.com.

Application server is responsible for session cookie creation (JSESSIONID) but not Spring Security.

All you have to do is to inform your app server that you want to always have the same domain in cookie.

Add to your web.xml:

   <session-config>
        <cookie-config>
            <domain>exampledomain.com</domain>
        </cookie-config>
    </session-config>
查看更多
登录 后发表回答