Как настроить Custom Authentication and Authorization при весенней загрузке? - PullRequest
0 голосов
/ 28 июня 2018

У нас есть класс CutomAuthentication, реализующий из AuthenticationProvider, и у нас есть один класс CutomAccessDecisionMgr, включающий AccessDecisionManager. Как я могу зарегистрировать их в приложении в конфигурации Java?

В моем XML у меня есть

<beans:bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
    <beans:property name="accessDecisionManager" ref="accessDecisionManager" />
    <beans:property name="authenticationManager" ref="authenticationManager" />
    <beans:property name="securityMetadataSource" ref="securityMetadataSource" />
</beans:bean>

<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
        <authentication-provider ref="customAuthentication"></authentication-provider>
</authentication-manager>

<beans:bean name="accessDecisionManager" class="com.xy.dashboard.security.CustomAccessDecisionManager" ></beans:bean>

<beans:bean name="securityMetadataSource" class="com.xy.dashboard.security.InvocationSecurityMetadataSourceService">
</beans:bean>

<beans:bean id="customAuthentication" class="com.xy.dashboard.security.CustomAuthentication" />

<beans:bean id="securityExceptionTranslationHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
    <beans:property name="exceptionMappings">
        <beans:props>
            <beans:prop key="org.springframework.security.authentication.CredentialsExpiredException">/changepassword.xhtml</beans:prop>
        </beans:props>
    </beans:property>
    <beans:property name="defaultFailureUrl" value="/login.jsp" />
</beans:bean>

Ответы [ 2 ]

0 голосов
/ 28 июня 2018

Первый шаг ,
Ваш WebSecurityConfig должен быть таким,

@Configuration
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private CustomAuthenticationProvider authProvider;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http.formLogin().loginPage("/login").permitAll().and().requestMatchers()
                    .antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access").and().authorizeRequests()
                    .anyRequest().authenticated();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(authProvider);
        }
    }

Второй шаг ,
Вам нужно создать свой собственный класс для реализации AuthenticationProvider, это должно быть так

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    public static final Logger logger = org.slf4j.LoggerFactory.getLogger(CustomAuthenticationProvider.class);

    @Autowired
    AuthenicationService authenicationService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        logger.info("Username:" + name + " Password:" + password);
        ReturnResult result = authenicationService.authenicate(); // against third party authenicate
        if (result.isStatus()) {
            return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
        } else {
            throw new BadCredentialsException(result.getMsg());
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
0 голосов
/ 28 июня 2018

Вам необходимо реализовать интерфейс AuthenticationProvider и обеспечить реализацию метода authenticate().

@Component
public class CustomAuthenticationProvider
  implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (shouldAuthenticateAgainstThirdPartySystem()) {

            // use the credentials
            // and authenticate against the third-party system
            return new UsernamePasswordAuthenticationToken(
              name, password, new ArrayList<>());
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(
          UsernamePasswordAuthenticationToken.class);
    }
}

Вы должны предоставить конфигурацию Spring Security с помощью Java Configuration и настроить CustomAuthenticationProvider . Вы можете защитить свой ресурс Uris для каждой роли.

@Configuration
@EnableWebSecurity
@ComponentScan("org.baeldung.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Override
    protected void configure(
      AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

http://www.baeldung.com/spring-security-authentication-provider

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...