Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > Доп. проверка юзера в acegi


Автор: VictorCV 2.4.2009, 17:21
Короче, ситуация такая - после того, как acegi аутенцифицирует пользователя, необходимо выполнить ещё дополнительную проверку на авторизацию. Эта проверка заключается в том, что мы посылаем запрос на веб-сервис и , в зависимости от ответа, допускаем его к ресурсу ил выбрасываем обратно на логин с соответствующей ошибкой. Как такое сотворить? с acegi раньше не связывался, пол дня сижу мозг ломаю =( 

Автор: _sten_ 2.4.2009, 21:35
Попробуй в AccessDecisionManager добавить свой вотер который и будет делать нужную проверку:
Код

 <bean id="filterSecurityInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
        <property name="objectDefinitionSource" ref="definitionSource"/>
    </bean>

<bean id="httpRequestAccessDecisionManager" class="org.acegisecurity.vote.AffirmativeBased">
        <property name="allowIfAllAbstainDecisions" value="false"/>
        <property name="decisionVoters">
            <list>
                <ref local="myVoter"/>
                <ref local="roleVoter"/>
            </list>
        </property>
    </bean>

<bean id="myVoter" class="org.demo.MyVoter"/>


в вотере нужно просто реализовать интерфейс AccessDecisionVoter:
Код

public class MyVoter implements AccessDecisionVoter{
  public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    public boolean supports(Class clazz) {
        return true;
    }

    public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config) {

        if (...)
        return ACCESS_GRANTED;
        else
        return ACCESS_ABSTAIN;
    }
}

Автор: VictorCV 3.4.2009, 09:26
ок,  спасибо, так можно сделать, но вотер не решает ещё двух проблем -
1 - проверка должна осуществляться только 1 раз сразу после логина пользователя, 
2 - в случае отказа мы должны выдать пользователю сообщение об ошибке работы с сервисом, вотер же просто голосует да/нет
        В обоих случаях помогла бы просто передача параметров с страницы логина в вотер и обратно - это можно реализовать?

Автор: MisterCleric 3.4.2009, 10:25
Здравствуйте. Позвольте я тоже поучаствую.
Я, конечно, с acegi не работал, но последний проект сделал на http://static.springsource.org/spring-security/site/index.html

Так вот у меня тоже была подобная задача: после аутентификации пользователя еще проверить есть ли у него право входа. Типа юзер-то активен, но у него отняли право входа.
Еще такая ситуация, что аутентификация проходит через LDAP, а права хранятся у меня в базе.
Я решил проблему кастомизацией AuthenticationProvider
и того у меня вышло такое:
Код

public class MyAuthenticationProvider implements AuthenticationProvider {

    private LdapAuthenticationProvider ldapAuthenticationProvider;

    @Autowired
    private RoleManagerService roleManagerService;

    private Long authenticationCheckRightId;

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        authentication = ldapAuthenticationProvider.authenticate(authentication);
        GrantedAuthority[] authorities = authentication.getAuthorities();
        if (authorities == null) {
            throw new UsernameNotFoundException(
                    messages.getMessage("JdbcDaoImpl.noAuthority",
                            new Object[]{authentication.getPrincipal()}, "User {0} has no GrantedAuthority"), authentication.getPrincipal());
        }

        String roleCode = authorities[0].getAuthority();

        if (roleManagerService.hasPrincipalRight(authenticationCheckRightId, roleCode)) {
            return authentication;
        }
        authentication.setAuthenticated(false);
        throw new DisabledException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
    }

    public boolean supports(Class authentication) {
        return ldapAuthenticationProvider.supports(authentication);
    }

    public void setAuthenticationCheckRightId(Long authenticationCheckRightId) {
        this.authenticationCheckRightId = authenticationCheckRightId;
    }

    public void setLdapAuthenticationProvider(LdapAuthenticationProvider ldapAuthenticationProvider) {
        this.ldapAuthenticationProvider = ldapAuthenticationProvider;
    }
}


Код

 <beans:bean id="myAuthenticationProvider" class="mypackage.spring.security.MyAuthenticationProvider">
        <custom-authentication-provider/>
        <beans:property name="authenticationCheckRightId" value="1"/>
        <beans:property name="ldapAuthenticationProvider" ref="_ldapAuthenticationProvider"/>
    </beans:bean>

    <ldap-server url="${ldap.url}/${ldap.base.dn}" manager-dn="${ldap.login}" manager-password="${ldap.pwd}"/>

    <ldap-authentication-provider group-search-base="${ldap.roles.dir}" group-search-filter="${ldap.member.filter}"/>

    <ldap-user-service id="userService" user-search-filter="(uid={0})" user-search-base="${ldap.users.dir}"/>

И того BasicProcessingFilter вызывает AuthenticationManager, который содержит мой AuthenticationProvider
правда я задал мой кастомный и LDAP провайдер именно в такой последовательности, что мой вызывался первей. Ну такие вот неудобства

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)