如何在春季启动时配置自定义身份验证和授权?

时间:2018-06-28 10:19:51

标签: java spring spring-boot spring-security

我们从AuthenticationProvider实现了一个CutomAuthentication类,并且有一个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 :(得分:0)

您需要实现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);
    }
}

您将使用Java Configuration提供Spring Security配置并配置 CustomAuthenticationProvider 。您可以保护每个角色的资源成本。

@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

答案 1 :(得分:0)

第一步
您的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);
    }
}