如何将spring security与自定义身份验证提供程序集成

时间:2015-05-04 07:09:28

标签: java spring spring-mvc authentication spring-security

我正在使用第三方身份验证器,它在应用程序启动时显示并显示登录屏幕,并在成功验证后授予对应用程序的访问权限。

成功验证后,它会转发到弹簧控制器以供用户加载。

我想知道如何将spring security api用于自定义提供程序。

我想在完成身份验证之后调用spring security api,同时加载用户详细信息以构建角色和GrantedAuthority等。

控制器

@Controller
public class WelcomeController {

    @RequestMapping(value = { "/welcome" }, method = RequestMethod.POST)
    public ModelAndView defaultPage() {

        ModelAndView model = new ModelAndView();
        //... load user profile from third party authenticator.
        return model;

    }
}

安全配置

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyCustomAuthenticationProvider thirdPartyAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/admin/**")
            .access("hasRole('ROLE_ADMIN')")
                .and().exceptionHandling().accessDeniedPage("/error.html");

    }

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

}

自定义提供商

public class MyCustomAuthenticationProvider implements AuthenticationProvider{



    @Override
        public Authentication authenticate(Authentication authentication)   throws AuthenticationException {
            // use the credentials to try to authenticate against the third party system
            if (authenticatedAgainstThirdPartySystem()) {
                List<GrantedAuthority> grantedAuths = new ArrayList<>();
                return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
            } else {
                throw new AuthenticationException("Unable to auth against third party systems");
            }
        }

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

    }

任何建议?

0 个答案:

没有答案